Skip to main content

platform/
network.rs

1//! `LocalNetwork` — outbound requests from this process.
2//!
3//! Two policies apply to a request the model chose, each on every hop of a
4//! redirect chain: the deployment's allowlist, and staying off internal
5//! addresses (`is_internal_address`) unless the allowlist names the host. A
6//! request that asks for it (`HttpRequest::public_only`) gets the second
7//! whoever chose it, except on hops to the target it was sent to when it also
8//! says `internal_target`. A name is checked when the hop is sent and again by the
9//! resolver the connection itself uses, so a name that answers differently
10//! the second time still cannot reach inside.
11
12use std::collections::BTreeMap;
13use std::net::IpAddr;
14use std::sync::Arc;
15use std::time::Duration;
16
17use futures::StreamExt;
18
19use base::interface::exec::network::domain_key;
20use base::interface::exec::NetworkMode;
21use base::interface::exec::{
22    domains_name_host, is_internal_address, ExecError, HttpRequest, HttpResponse, HttpStream,
23    Network, Origin,
24};
25
26const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
27
28/// This process's own network, under the deployment's egress policy.
29pub struct LocalNetwork {
30    proxied: reqwest::Client,
31    direct: reqwest::Client,
32    public_only: reqwest::Client,
33    /// Hosts the model is allowed to reach. Empty means no restriction, which
34    /// is what an unconfigured deployment has always had.
35    allowed_domains: Vec<String>,
36    /// Hosts the deployment named, which a model-directed request may reach
37    /// even at an internal address.
38    vouched: Vec<String>,
39    /// Whether agent-directed egress is refused outright.
40    agent_offline: bool,
41    use_system_proxy: bool,
42    /// Sent as `User-Agent` where a request names none. Per network, not on
43    /// the shared clients: two pools in one process may be different products.
44    user_agent: Arc<str>,
45}
46
47impl Default for LocalNetwork {
48    fn default() -> Self {
49        Self::new(Vec::new(), false)
50    }
51}
52
53impl LocalNetwork {
54    pub fn new(allowed_domains: Vec<String>, agent_offline: bool) -> Self {
55        Self::with(allowed_domains.clone(), allowed_domains, agent_offline)
56    }
57
58    fn with(allowed_domains: Vec<String>, vouched: Vec<String>, agent_offline: bool) -> Self {
59        Self {
60            proxied: shared_client(ClientKind::Proxied),
61            direct: shared_client(ClientKind::Direct),
62            public_only: shared_client(ClientKind::PublicOnly),
63            allowed_domains,
64            vouched,
65            agent_offline,
66            use_system_proxy: use_system_proxy_now(),
67            user_agent: Arc::from(base::paths::Layout::default().user_agent()),
68        }
69    }
70
71    /// Requests that name no `User-Agent` send `user_agent`
72    /// ([`base::paths::Layout::user_agent`]).
73    pub fn with_user_agent(mut self, user_agent: impl Into<Arc<str>>) -> Self {
74        self.user_agent = user_agent.into();
75        self
76    }
77
78    /// The egress a deployment's `sandbox.network.mode` describes, read the
79    /// same way the sandbox backends read it so the two cannot disagree about
80    /// where the model may reach.
81    ///
82    /// Under `Unrestricted` the domain list restricts nothing, but a host it
83    /// names may still be reached at an internal address — the one thing the
84    /// list says in that mode is "these are mine". `Proxy` binds a sandboxed
85    /// command, not the model's own requests, which are read as under
86    /// `Unrestricted`.
87    pub fn for_agent_policy(mode: NetworkMode, allowed_domains: Vec<String>) -> Self {
88        match mode {
89            NetworkMode::Unrestricted | NetworkMode::Proxy => {
90                Self::with(Vec::new(), allowed_domains, false)
91            }
92            NetworkMode::DenyAll => Self::new(Vec::new(), true),
93            // An empty allowlist under this mode names nothing reachable, the
94            // same reading the sandbox backends give it.
95            NetworkMode::Allowlist if allowed_domains.is_empty() => Self::new(Vec::new(), true),
96            NetworkMode::Allowlist => Self::new(allowed_domains, false),
97        }
98    }
99
100    fn keeps_off_internal(&self, url: &url::Url, origin: Origin, public_only: bool) -> bool {
101        public_only || (origin == Origin::Agent && !self.vouches(url))
102    }
103
104    /// Whether this hop may reach an internal address: an operator's request
105    /// that named its own target as allowed, going back to that target.
106    fn may_reach_internal(&self, policy: &HopPolicy, url: &url::Url, origin: Origin) -> bool {
107        origin == Origin::Operator
108            && policy.internal_target.as_ref().is_some_and(|target| {
109                target.host_str() == url.host_str()
110                    && target.port_or_known_default() == url.port_or_known_default()
111            })
112    }
113
114    fn vouches(&self, url: &url::Url) -> bool {
115        let Some(host) = host_key(url) else {
116            return false;
117        };
118        let is_name = matches!(url.host(), Some(url::Host::Domain(_)));
119        self.vouched
120            .iter()
121            .map(|d| domain_key(d))
122            .any(|d| host == d || (is_name && host.ends_with(&format!(".{d}"))))
123    }
124
125    /// The hop's own address, or every address its name resolves to here.
126    ///
127    /// A name that does not resolve here is let through: sent directly it
128    /// fails on its own, and through a proxy it is the proxy's to resolve.
129    async fn refuse_internal(&self, url: &url::Url, origin: Origin) -> Result<(), ExecError> {
130        let addresses: Vec<IpAddr> = match url.host() {
131            Some(url::Host::Ipv4(ip)) => vec![IpAddr::V4(ip)],
132            Some(url::Host::Ipv6(ip)) => vec![IpAddr::V6(ip)],
133            Some(url::Host::Domain(name)) => {
134                let port = url.port_or_known_default().unwrap_or(0);
135                tokio::net::lookup_host((name, port))
136                    .await
137                    .map(|found| found.map(|a| a.ip()).collect())
138                    .unwrap_or_default()
139            }
140            None => return Err(ExecError::failed(format!("not a url: {url}"))),
141        };
142        match addresses.into_iter().find(|ip| is_internal_address(*ip)) {
143            Some(ip) => Err(internal_refusal(
144                url.host_str().unwrap_or_default(),
145                ip,
146                origin,
147            )),
148            None => Ok(()),
149        }
150    }
151
152    fn refuse(&self, url: &url::Url, origin: Origin) -> Result<(), ExecError> {
153        let host = url
154            .host_str()
155            .ok_or_else(|| ExecError::failed(format!("not a url: {url}")))?;
156        if self.listed(host, origin) {
157            return Ok(());
158        }
159        Err(if self.agent_offline {
160            ExecError::denied(format!(
161                "outbound network is off for model-directed requests, so {host} is unreachable"
162            ))
163        } else {
164            ExecError::denied(format!(
165                "{host} is not in the allowed domains for model-directed requests"
166            ))
167        })
168    }
169
170    fn client_for(&self, url: &url::Url) -> &reqwest::Client {
171        match client_kind_for(url, self.use_system_proxy) {
172            ClientKind::Direct => &self.direct,
173            _ => &self.proxied,
174        }
175    }
176}
177
178fn client_kind_for(url: &url::Url, use_system_proxy: bool) -> ClientKind {
179    if is_loopback(url) || !use_system_proxy {
180        ClientKind::Direct
181    } else {
182        ClientKind::Proxied
183    }
184}
185
186static USE_SYSTEM_PROXY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
187
188/// Whether this process's own HTTP follows the environment's proxy. Unset
189/// it does. The clients are process-wide and built on first use, so the
190/// answer has to be given before any request goes out and holds for the life
191/// of the process; a later, different answer is ignored.
192pub fn configure_system_proxy(use_system_proxy: bool) {
193    if USE_SYSTEM_PROXY.set(use_system_proxy).is_err() && use_system_proxy_now() != use_system_proxy
194    {
195        tracing::warn!(
196            "app.system_proxy changed after this process's HTTP clients were set up; restart to apply it"
197        );
198    }
199}
200
201pub fn use_system_proxy_now() -> bool {
202    USE_SYSTEM_PROXY.get().copied().unwrap_or(true)
203}
204
205/// The names of the proxy variables set in the environment, never their values.
206pub fn proxy_variables_set() -> Vec<String> {
207    PROXY_VARIABLES
208        .iter()
209        .filter(|k| std::env::var(k).is_ok_and(|v| !v.is_empty()))
210        .map(|k| k.to_string())
211        .collect()
212}
213
214/// The ambient `HTTP(S)_PROXY` means "reach the internet through this egress",
215/// not "also proxy calls to my own machine" — but reqwest applies it to
216/// loopback targets too unless `NO_PROXY` carves them out, and a local relay,
217/// vLLM or Ollama endpoint is a configuration people really run.
218fn is_loopback(url: &url::Url) -> bool {
219    match url.host() {
220        Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
221        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
222        Some(url::Host::Domain(d)) => d.eq_ignore_ascii_case("localhost"),
223        None => false,
224    }
225}
226
227fn host_key(url: &url::Url) -> Option<String> {
228    Some(match url.host()? {
229        url::Host::Domain(d) => d.trim_end_matches('.').to_ascii_lowercase(),
230        url::Host::Ipv4(ip) => ip.to_string(),
231        url::Host::Ipv6(ip) => ip.to_string(),
232    })
233}
234
235fn internal_refusal(host: &str, ip: IpAddr, origin: Origin) -> ExecError {
236    let place = if host.trim_matches(['[', ']']) == ip.to_string() {
237        format!("{host} is on this machine or a private network")
238    } else {
239        format!("{host} is {ip}, on this machine or a private network")
240    };
241    ExecError::denied(match origin {
242        Origin::Agent => format!(
243            "{place}; a model-directed request reaches such a host only when \
244             web.allowed_domains names it"
245        ),
246        Origin::Operator => format!("{place}, which this request may not reach"),
247    })
248}
249
250/// What a request carries from hop to hop of its redirect chain.
251struct HopPolicy {
252    /// The url it was sent to, when that target may be internal.
253    internal_target: Option<url::Url>,
254}
255
256/// What the `PublicOnly` client's resolver refuses with, found again in the
257/// error a refused connection comes back as.
258#[derive(Debug)]
259struct InternalDestination {
260    host: String,
261    ip: IpAddr,
262}
263
264impl std::fmt::Display for InternalDestination {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        write!(
267            f,
268            "{} resolves to the internal address {}",
269            self.host, self.ip
270        )
271    }
272}
273
274impl std::error::Error for InternalDestination {}
275
276/// Resolves a name for a connection the `PublicOnly` client makes, refusing
277/// it when any of its addresses is internal.
278///
279/// A configured proxy's own name is exempt: with a proxy, this resolver only
280/// ever sees the proxy, and a proxy on the local network is what a proxy
281/// usually is.
282struct PublicOnlyResolver {
283    proxies: Vec<String>,
284}
285
286impl reqwest::dns::Resolve for PublicOnlyResolver {
287    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
288        let host = name.as_str().trim_end_matches('.').to_ascii_lowercase();
289        let checked = !self.proxies.contains(&host);
290        Box::pin(async move {
291            let found: Vec<std::net::SocketAddr> =
292                tokio::net::lookup_host((host.as_str(), 0)).await?.collect();
293            if checked {
294                if let Some(ip) = found
295                    .iter()
296                    .map(|a| a.ip())
297                    .find(|ip| is_internal_address(*ip))
298                {
299                    return Err(InternalDestination { host, ip }.into());
300                }
301            }
302            Ok(Box::new(found.into_iter()) as reqwest::dns::Addrs)
303        })
304    }
305}
306
307const PROXY_VARIABLES: [&str; 6] = [
308    "HTTP_PROXY",
309    "http_proxy",
310    "HTTPS_PROXY",
311    "https_proxy",
312    "ALL_PROXY",
313    "all_proxy",
314];
315
316/// The hosts of the proxies in the environment, read the way reqwest reads
317/// them when it builds a client.
318fn proxy_hosts() -> Vec<String> {
319    PROXY_VARIABLES
320        .iter()
321        .filter_map(|k| std::env::var(k).ok())
322        .filter_map(|v| {
323            let v = if v.contains("://") {
324                v
325            } else {
326                format!("http://{v}")
327            };
328            url::Url::parse(&v).ok().as_ref().and_then(host_key)
329        })
330        .collect()
331}
332
333#[derive(Clone, Copy, Debug)]
334enum ClientKind {
335    Proxied,
336    Direct,
337    PublicOnly,
338}
339
340/// One connection pool per process, not one per `LocalNetwork`.
341///
342/// The client carries no policy — the allowlist and the offline switch live on
343/// the wrapper — so two deployments' worth of egress rules can share it, and a
344/// fresh one per tool call would throw away keep-alive and re-derive the TLS
345/// roots every time.
346fn shared_client(kind: ClientKind) -> reqwest::Client {
347    static PROXIED: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
348    static DIRECT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
349    static PUBLIC_ONLY: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
350    let cell = match kind {
351        ClientKind::Proxied => &PROXIED,
352        ClientKind::Direct => &DIRECT,
353        ClientKind::PublicOnly => &PUBLIC_ONLY,
354    };
355    cell.get_or_init(|| build_client(kind)).clone()
356}
357
358/// No total request timeout: it would bound the whole response body, which for
359/// a server-sent-event stream means tearing the connection down mid-answer.
360/// How long a call may take belongs to the caller.
361fn build_client(kind: ClientKind) -> reqwest::Client {
362    install_tls_provider();
363    let mut b = reqwest::Client::builder()
364        .connect_timeout(CONNECT_TIMEOUT)
365        .redirect(reqwest::redirect::Policy::none());
366    let system_proxy = use_system_proxy_now();
367    match kind {
368        ClientKind::Proxied => {
369            if !system_proxy {
370                b = b.no_proxy();
371            }
372        }
373        ClientKind::Direct => b = b.no_proxy(),
374        ClientKind::PublicOnly => {
375            if !system_proxy {
376                b = b.no_proxy();
377            }
378            b = b.dns_resolver(PublicOnlyResolver {
379                proxies: if system_proxy {
380                    proxy_hosts()
381                } else {
382                    Vec::new()
383                },
384            })
385        }
386    }
387    b.build().unwrap_or_else(|e| {
388        // The fallback is `reqwest`'s default, which is the *proxied* client —
389        // so falling back here would send loopback traffic through the ambient
390        // proxy, the one thing `no_proxy` exists to prevent. Say so rather
391        // than silently inverting the intent.
392        tracing::error!(error = %e, ?kind, "could not build the HTTP client; falling back to the default one");
393        reqwest::Client::default()
394    })
395}
396
397/// reqwest is built with `rustls-no-provider` (ring, not its aws-lc default)
398/// and panics on the first client it builds if no process-wide provider is
399/// installed — including clients built inside dependencies such as rmcp.
400pub fn install_tls_provider() {
401    static ONCE: std::sync::Once = std::sync::Once::new();
402    ONCE.call_once(|| {
403        let _ = rustls::crypto::ring::default_provider().install_default();
404    });
405}
406
407fn headers_of(map: &reqwest::header::HeaderMap) -> BTreeMap<String, String> {
408    map.iter()
409        .filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
410        .collect()
411}
412
413fn transport_error(url: &url::Url, e: reqwest::Error, origin: Origin) -> ExecError {
414    let mut cause: Option<&(dyn std::error::Error + 'static)> = std::error::Error::source(&e);
415    while let Some(c) = cause {
416        if let Some(d) = c.downcast_ref::<InternalDestination>() {
417            return internal_refusal(&d.host, d.ip, origin);
418        }
419        cause = c.source();
420    }
421    let url = without_userinfo(url);
422    // A request that never reached a server is this side failing, and the two
423    // are different sentences to whoever reads them.
424    if e.is_connect() || e.is_timeout() {
425        ExecError::unavailable(format!("{url}: {e}"))
426    } else {
427        ExecError::failed(format!("{url}: {e}"))
428    }
429}
430
431/// `url` fit for an error: a gateway's userinfo is a credential, the user
432/// name included when it is a token.
433fn without_userinfo(url: &url::Url) -> url::Url {
434    let mut shown = url.clone();
435    let _ = shown.set_username("");
436    let _ = shown.set_password(None);
437    shown
438}
439
440fn redirect_target(from: &url::Url, resp: &reqwest::Response) -> Option<url::Url> {
441    if !matches!(resp.status().as_u16(), 301 | 302 | 303 | 307 | 308) {
442        return None;
443    }
444    let location = resp
445        .headers()
446        .get(reqwest::header::LOCATION)?
447        .to_str()
448        .ok()?;
449    from.join(location).ok()
450}
451
452/// What of the caller's headers follows a redirect to another origin: only
453/// these, which describe the request rather than who sends it. A credential
454/// travels under whatever name the service picked (`x-api-key`, `api-key`, an
455/// MCP server's own header), so the others stay behind.
456fn keep_across_origins(headers: &mut BTreeMap<String, String>) {
457    headers.retain(|k, _| {
458        matches!(
459            k.to_ascii_lowercase().as_str(),
460            "accept"
461                | "accept-encoding"
462                | "accept-language"
463                | "content-type"
464                | "user-agent"
465                | "anthropic-version"
466                | "anthropic-beta"
467                | "openai-beta"
468                | "mcp-protocol-version"
469        )
470    });
471}
472
473#[async_trait::async_trait]
474impl Network for LocalNetwork {
475    async fn send(&self, req: HttpRequest, origin: Origin) -> Result<HttpResponse, ExecError> {
476        let cap = req.max_bytes;
477        let stream = self.open(req, origin).await?;
478
479        if let Some(cap) = cap {
480            if let Some(len) = stream
481                .headers
482                .get("content-length")
483                .and_then(|v| v.parse::<u64>().ok())
484            {
485                if len > cap {
486                    return Err(ExecError::failed(format!(
487                        "response is {len} bytes; cap is {cap} bytes"
488                    )));
489                }
490            }
491        }
492
493        let HttpStream {
494            status,
495            headers,
496            mut body,
497        } = stream;
498        let mut bytes = Vec::new();
499        while let Some(chunk) = body.next().await {
500            bytes.extend_from_slice(&chunk?);
501            if let Some(cap) = cap {
502                if bytes.len() as u64 > cap {
503                    return Err(ExecError::failed(format!(
504                        "response is over the {cap} byte cap"
505                    )));
506                }
507            }
508        }
509        Ok(HttpResponse {
510            status,
511            headers,
512            body: bytes,
513        })
514    }
515
516    async fn open(&self, req: HttpRequest, origin: Origin) -> Result<HttpStream, ExecError> {
517        let mut url = url::Url::parse(&req.url).map_err(|e| {
518            ExecError::failed(format!(
519                "not a url: {} ({e})",
520                base::text::scrub_url(&req.url)
521            ))
522        })?;
523        let policy = HopPolicy {
524            internal_target: req.internal_target.then(|| url.clone()),
525        };
526        let mut method = req.method;
527        let mut body = req.body;
528        let mut headers = req.headers;
529
530        for hop in 0..=req.max_redirects {
531            self.refuse(&url, origin)?;
532            let guarded = self.keeps_off_internal(&url, origin, req.public_only)
533                && !self.may_reach_internal(&policy, &url, origin);
534            if guarded {
535                self.refuse_internal(&url, origin).await?;
536            }
537
538            let m = reqwest::Method::from_bytes(method.as_bytes())
539                .map_err(|e| ExecError::failed(format!("{method}: {e}")))?;
540            let client = if guarded {
541                &self.public_only
542            } else {
543                self.client_for(&url)
544            };
545            let mut b = client.request(m.clone(), url.clone());
546            if !headers
547                .keys()
548                .any(|k| k.eq_ignore_ascii_case(reqwest::header::USER_AGENT.as_str()))
549            {
550                b = b.header(reqwest::header::USER_AGENT, &*self.user_agent);
551            }
552            for (k, v) in &headers {
553                b = b.header(k, v);
554            }
555            if let Some(body) = &body {
556                b = b.body(body.clone());
557            }
558            let resp = b
559                .send()
560                .await
561                .map_err(|e| transport_error(&url, e, origin))?;
562
563            if hop < req.max_redirects {
564                if let Some(next) = redirect_target(&url, &resp) {
565                    let code = resp.status().as_u16();
566                    let rewrites_to_get = code == 303
567                        || (matches!(code, 301 | 302)
568                            && m != reqwest::Method::GET
569                            && m != reqwest::Method::HEAD);
570                    if rewrites_to_get {
571                        method = "GET".into();
572                        body = None;
573                    }
574                    if next.origin() != url.origin() {
575                        keep_across_origins(&mut headers);
576                    }
577                    url = next;
578                    continue;
579                }
580            }
581
582            return Ok(HttpStream {
583                status: resp.status().as_u16(),
584                headers: headers_of(resp.headers()),
585                body: Box::pin(
586                    resp.bytes_stream()
587                        .map(|c| c.map(|b| b.to_vec()).map_err(ExecError::failed)),
588                ),
589            });
590        }
591        unreachable!("the loop returns or continues, and continues are bounded by max_redirects")
592    }
593
594    /// The allowlist, and for an address written out, whether it is internal.
595    /// A name's addresses are only known once it is resolved, at send.
596    fn permits(&self, host: &str, origin: Origin) -> bool {
597        if !self.listed(host, origin) {
598            return false;
599        }
600        let literal = domain_key(host).parse::<IpAddr>().ok();
601        match (origin, literal) {
602            (Origin::Agent, Some(ip)) if is_internal_address(ip) => {
603                let as_url = match ip {
604                    IpAddr::V4(_) => format!("http://{ip}/"),
605                    IpAddr::V6(_) => format!("http://[{ip}]/"),
606                };
607                url::Url::parse(&as_url).is_ok_and(|u| self.vouches(&u))
608            }
609            _ => true,
610        }
611    }
612}
613
614impl LocalNetwork {
615    fn listed(&self, host: &str, origin: Origin) -> bool {
616        match origin {
617            // An operator chose this endpoint. Applying the model's allowlist
618            // to it would cut the agent off from its own model.
619            Origin::Operator => true,
620            Origin::Agent if self.agent_offline => false,
621            Origin::Agent => {
622                // Hosts arrive lowercased from the url parser; the list
623                // arrives verbatim from settings.json. Compared as written,
624                // `Example.com` is an allowlist that matches nothing, and the
625                // deployment gets every request refused with no sign that its
626                // configuration is what refused them.
627                self.allowed_domains.is_empty() || domains_name_host(&self.allowed_domains, host)
628            }
629        }
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    #[test]
636    fn without_the_system_proxy_every_request_is_direct() {
637        let remote = url::Url::parse("https://example.com/").unwrap();
638        let local = url::Url::parse("http://127.0.0.1:9/").unwrap();
639        assert!(matches!(
640            client_kind_for(&remote, true),
641            ClientKind::Proxied
642        ));
643        assert!(matches!(
644            client_kind_for(&remote, false),
645            ClientKind::Direct
646        ));
647        assert!(matches!(client_kind_for(&local, true), ClientKind::Direct));
648        assert!(matches!(client_kind_for(&local, false), ClientKind::Direct));
649    }
650
651    use super::*;
652
653    #[test]
654    fn the_allowlist_binds_the_model_and_not_the_operator() {
655        let n = LocalNetwork::new(vec!["example.com".into()], false);
656        assert!(n.permits("example.com", Origin::Agent));
657        assert!(
658            n.permits("api.example.com", Origin::Agent),
659            "subdomains too"
660        );
661        assert!(!n.permits("evil.test", Origin::Agent));
662        assert!(
663            n.permits("evil.test", Origin::Operator),
664            "an operator-configured endpoint is not the model's choice to be \
665             restricted from — applying the allowlist here is how an agent \
666             loses its own model"
667        );
668    }
669
670    #[test]
671    fn an_empty_allowlist_is_no_restriction() {
672        let n = LocalNetwork::default();
673        assert!(n.permits("anything.test", Origin::Agent));
674    }
675
676    #[test]
677    fn offline_stops_the_model_and_leaves_the_engine_running() {
678        let n = LocalNetwork::new(Vec::new(), true);
679        assert!(!n.permits("example.com", Origin::Agent));
680        assert!(n.permits("example.com", Origin::Operator));
681    }
682
683    /// Hosts arrive lowercased from the parser; a list written by hand does
684    /// not. Compared as written, `Example.com` matches nothing and every
685    /// request is refused with no sign that the configuration is at fault.
686    #[test]
687    fn the_allowlist_is_not_case_sensitive() {
688        let n = LocalNetwork::for_agent_policy(
689            base::interface::exec::NetworkMode::Allowlist,
690            vec!["Example.COM".into()],
691        );
692        assert!(n.permits("example.com", Origin::Agent));
693        assert!(n.permits("api.example.com", Origin::Agent));
694    }
695
696    #[test]
697    fn a_suffix_that_is_not_a_subdomain_does_not_match() {
698        let n = LocalNetwork::new(vec!["example.com".into()], false);
699        assert!(
700            !n.permits("notexample.com", Origin::Agent),
701            "matching on a bare suffix would let any attacker-registered \
702             domain ending in the allowed one through"
703        );
704    }
705
706    #[test]
707    fn loopback_is_recognized_whatever_shape_it_is_written_in() {
708        for u in [
709            "http://127.0.0.1:8080/health",
710            "http://localhost/",
711            "https://LocalHost:9000",
712            "http://[::1]:3000",
713        ] {
714            assert!(is_loopback(&url::Url::parse(u).unwrap()), "{u}");
715        }
716        for u in [
717            "https://example.com",
718            "https://10.211.55.2:8001",
719            "https://api.anthropic.com/v1/messages",
720        ] {
721            assert!(!is_loopback(&url::Url::parse(u).unwrap()), "{u}");
722        }
723    }
724
725    #[test]
726    fn the_sandbox_network_mode_is_what_binds_the_model() {
727        let unrestricted =
728            LocalNetwork::for_agent_policy(NetworkMode::Unrestricted, vec!["example.com".into()]);
729        assert!(
730            unrestricted.permits("evil.test", Origin::Agent),
731            "a domain list without the mode that reads it restricts nothing, \
732             exactly as it does not restrict a sandboxed subprocess"
733        );
734
735        let listed =
736            LocalNetwork::for_agent_policy(NetworkMode::Allowlist, vec!["example.com".into()]);
737        assert!(listed.permits("example.com", Origin::Agent));
738        assert!(!listed.permits("evil.test", Origin::Agent));
739
740        let empty_list = LocalNetwork::for_agent_policy(NetworkMode::Allowlist, Vec::new());
741        assert!(!empty_list.permits("example.com", Origin::Agent));
742
743        let denied = LocalNetwork::for_agent_policy(NetworkMode::DenyAll, Vec::new());
744        assert!(!denied.permits("example.com", Origin::Agent));
745        assert!(denied.permits("api.anthropic.com", Origin::Operator));
746    }
747
748    #[tokio::test]
749    async fn a_refused_host_never_reaches_the_socket() {
750        let n = LocalNetwork::new(vec!["example.com".into()], false);
751        let err = n
752            .send(HttpRequest::get("http://127.0.0.1:1/"), Origin::Agent)
753            .await
754            .expect_err("port 1 on loopback would be a connection error, not a policy one");
755        assert!(
756            matches!(err, ExecError::Denied(_)),
757            "the policy has to answer before the connection is attempted, or \
758             a denied host is still a DNS lookup and a SYN: {err:?}"
759        );
760    }
761
762    #[tokio::test]
763    async fn the_same_host_is_reachable_for_an_operator() {
764        let n = LocalNetwork::new(vec!["example.com".into()], false);
765        let err = n
766            .send(HttpRequest::get("http://127.0.0.1:1/"), Origin::Operator)
767            .await
768            .expect_err("nothing listens on port 1");
769        assert!(
770            !matches!(err, ExecError::Denied(_)),
771            "an operator endpoint must get as far as the socket: {err:?}"
772        );
773    }
774
775    /// A server on this machine that counts what reaches it and answers each
776    /// request with `answer`.
777    async fn a_counting_server(
778        answer: impl Fn(u16) -> String + Send + Sync + 'static,
779    ) -> (u16, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
780        use tokio::io::{AsyncReadExt, AsyncWriteExt};
781        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
782            .await
783            .expect("bind");
784        let port = listener.local_addr().expect("addr").port();
785        let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
786        let seen = hits.clone();
787        tokio::spawn(async move {
788            while let Ok((mut sock, _)) = listener.accept().await {
789                seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
790                let mut buf = vec![0u8; 8192];
791                let _ = sock.read(&mut buf).await;
792                let _ = sock.write_all(answer(port).as_bytes()).await;
793                let _ = sock.shutdown().await;
794            }
795        });
796        (port, hits)
797    }
798
799    fn ok_response(_: u16) -> String {
800        "HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok".into()
801    }
802
803    #[tokio::test]
804    async fn a_transport_error_does_not_carry_the_urls_credentials() {
805        let closed = {
806            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
807            listener.local_addr().expect("addr").port()
808        };
809        let (hangs_up, _) = a_counting_server(|_| String::new()).await;
810        for port in [closed, hangs_up] {
811            let url = format!("http://relay:s3cr3t@127.0.0.1:{port}/v1/messages");
812            let err = LocalNetwork::default()
813                .send(HttpRequest::post(&url), Origin::Operator)
814                .await
815                .expect_err("nothing answers");
816            let text = err.to_string();
817            assert!(!text.contains("s3cr3t"), "{text}");
818            assert!(!text.contains("relay"), "{text}");
819            assert!(
820                text.contains(&format!("127.0.0.1:{port}/v1/messages")),
821                "{text}"
822            );
823        }
824    }
825
826    #[tokio::test]
827    async fn each_network_sends_its_own_user_agent_unless_the_request_names_one() {
828        use tokio::io::{AsyncReadExt, AsyncWriteExt};
829        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
830        let port = listener.local_addr().unwrap().port();
831        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
832        tokio::spawn(async move {
833            while let Ok((mut sock, _)) = listener.accept().await {
834                let mut buf = vec![0u8; 8192];
835                let n = sock.read(&mut buf).await.unwrap_or(0);
836                let _ = tx.send(String::from_utf8_lossy(&buf[..n]).to_lowercase());
837                let _ = sock.write_all(ok_response(0).as_bytes()).await;
838                let _ = sock.shutdown().await;
839            }
840        });
841        let url = format!("http://127.0.0.1:{port}/");
842        let agix = LocalNetwork::default();
843        let codix = LocalNetwork::default().with_user_agent("codix/1.0");
844        agix.send(HttpRequest::get(&url), Origin::Operator)
845            .await
846            .unwrap();
847        let seen = rx.recv().await.unwrap();
848        assert!(
849            seen.contains(&format!("user-agent: agix/{}", env!("CARGO_PKG_VERSION"))),
850            "{seen}"
851        );
852        codix
853            .send(HttpRequest::get(&url), Origin::Operator)
854            .await
855            .unwrap();
856        let seen = rx.recv().await.unwrap();
857        assert!(seen.contains("user-agent: codix/1.0"), "{seen}");
858        let mut named = HttpRequest::get(&url);
859        named.headers.insert("User-Agent".into(), "mine/2".into());
860        codix.send(named, Origin::Operator).await.unwrap();
861        let seen = rx.recv().await.unwrap();
862        assert_eq!(seen.matches("user-agent:").count(), 1, "{seen}");
863        assert!(seen.contains("user-agent: mine/2"), "{seen}");
864    }
865
866    #[tokio::test]
867    async fn agent_requests_to_private_addresses_are_refused() {
868        let (port, hits) = a_counting_server(ok_response).await;
869        let n = LocalNetwork::default();
870        for host in [
871            "127.0.0.1",
872            "localhost",
873            "LOCALHOST.",
874            "0.0.0.0",
875            "[::ffff:127.0.0.1]",
876            "[::ffff:7f00:1]",
877            "127.1",
878            "2130706433",
879            "x@127.0.0.1",
880            "x:y@localhost",
881        ] {
882            let err = n
883                .send(
884                    HttpRequest::get(format!("http://{host}:{port}/")),
885                    Origin::Agent,
886                )
887                .await
888                .expect_err(host);
889            assert!(matches!(err, ExecError::Denied(_)), "{host}: {err:?}");
890        }
891        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 0);
892        assert!(!n.permits("127.0.0.1", Origin::Agent));
893        assert!(!n.permits("[::1]", Origin::Agent));
894        assert!(n.permits("example.com", Origin::Agent));
895    }
896
897    #[tokio::test]
898    async fn a_host_the_deployment_named_is_reachable_at_an_internal_address() {
899        let (port, hits) = a_counting_server(ok_response).await;
900        for n in [
901            LocalNetwork::for_agent_policy(NetworkMode::Unrestricted, vec!["127.0.0.1".into()]),
902            LocalNetwork::for_agent_policy(NetworkMode::Allowlist, vec!["127.0.0.1".into()]),
903        ] {
904            let r = n
905                .send(
906                    HttpRequest::get(format!("http://127.0.0.1:{port}/")),
907                    Origin::Agent,
908                )
909                .await
910                .expect("a vouched host");
911            assert_eq!(r.body_text(), "ok");
912            assert!(n.permits("127.0.0.1", Origin::Agent));
913        }
914        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 2);
915    }
916
917    #[tokio::test]
918    async fn every_hop_of_a_redirect_is_kept_off_internal_addresses() {
919        let (inner_port, inner_hits) = a_counting_server(ok_response).await;
920        let (outer_port, _) = a_counting_server(move |_| {
921            format!(
922                "HTTP/1.1 302 Found\r\nlocation: http://localhost:{inner_port}/\r\n\
923                 content-length: 0\r\nconnection: close\r\n\r\n"
924            )
925        })
926        .await;
927        let n = LocalNetwork::for_agent_policy(NetworkMode::Unrestricted, vec!["127.0.0.1".into()]);
928        let err = n
929            .send(
930                HttpRequest::get(format!("http://127.0.0.1:{outer_port}/")),
931                Origin::Agent,
932            )
933            .await
934            .expect_err("the second hop is not a vouched host");
935        assert!(matches!(err, ExecError::Denied(_)), "{err:?}");
936        assert_eq!(inner_hits.load(std::sync::atomic::Ordering::SeqCst), 0);
937    }
938
939    #[tokio::test]
940    async fn a_public_only_request_is_refused_whoever_chose_it() {
941        let (port, hits) = a_counting_server(ok_response).await;
942        let n = LocalNetwork::default();
943        let url = format!("http://127.0.0.1:{port}/");
944        let err = n
945            .send(HttpRequest::post(&url).public_only(), Origin::Operator)
946            .await
947            .expect_err("an internal address");
948        assert!(matches!(err, ExecError::Denied(_)), "{err:?}");
949        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 0);
950
951        n.send(HttpRequest::post(&url), Origin::Operator)
952            .await
953            .expect("without the flag an operator endpoint is reached");
954        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 1);
955    }
956
957    #[tokio::test]
958    async fn an_internal_target_is_reached_and_only_that_target() {
959        let (port, hits) = a_counting_server(ok_response).await;
960        let n = LocalNetwork::default();
961        let url = format!("http://127.0.0.1:{port}/");
962        n.send(
963            HttpRequest::post(&url).public_only_but_target(),
964            Origin::Operator,
965        )
966        .await
967        .expect("the named target is reachable");
968        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 1);
969
970        let err = n
971            .send(
972                HttpRequest::post(format!("http://localhost:{port}/")).public_only_but_target(),
973                Origin::Agent,
974            )
975            .await
976            .expect_err("a model-directed request gains nothing from it");
977        assert!(matches!(err, ExecError::Denied(_)), "{err:?}");
978        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 1);
979    }
980
981    #[tokio::test]
982    async fn an_internal_target_cannot_redirect_to_another_internal_host() {
983        let (inner_port, inner_hits) = a_counting_server(ok_response).await;
984        let (outer_port, outer_hits) = a_counting_server(move |_| {
985            format!(
986                "HTTP/1.1 307 Temporary Redirect\r\nlocation: http://127.0.0.1:{inner_port}/\r\ncontent-length: 0\r\n\r\n"
987            )
988        })
989        .await;
990        let n = LocalNetwork::default();
991        let err = n
992            .send(
993                HttpRequest::post(format!("http://127.0.0.1:{outer_port}/"))
994                    .public_only_but_target(),
995                Origin::Operator,
996            )
997            .await
998            .expect_err("the second hop is another internal target");
999        assert!(matches!(err, ExecError::Denied(_)), "{err:?}");
1000        assert_eq!(outer_hits.load(std::sync::atomic::Ordering::SeqCst), 1);
1001        assert_eq!(inner_hits.load(std::sync::atomic::Ordering::SeqCst), 0);
1002    }
1003
1004    /// The connection resolves the name again; what it gets is checked there
1005    /// too, so a name that answers differently the second time is still
1006    /// refused — and the refusal comes back as one, not a connect error.
1007    #[tokio::test]
1008    async fn the_connection_itself_refuses_a_name_that_resolves_inside() {
1009        let (port, hits) = a_counting_server(ok_response).await;
1010        install_tls_provider();
1011        let client = reqwest::Client::builder()
1012            .no_proxy()
1013            .dns_resolver(PublicOnlyResolver {
1014                proxies: Vec::new(),
1015            })
1016            .build()
1017            .expect("client");
1018        let url = url::Url::parse(&format!("http://localhost:{port}/")).expect("url");
1019        let e = client
1020            .get(url.clone())
1021            .send()
1022            .await
1023            .expect_err("refused at resolution");
1024        let err = transport_error(&url, e, Origin::Agent);
1025        assert!(matches!(err, ExecError::Denied(_)), "{err:?}");
1026        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 0);
1027
1028        let through_proxy = PublicOnlyResolver {
1029            proxies: vec!["localhost".into()],
1030        };
1031        let name: reqwest::dns::Name = "localhost".parse().expect("name");
1032        assert!(
1033            reqwest::dns::Resolve::resolve(&through_proxy, name)
1034                .await
1035                .is_ok(),
1036            "a configured proxy's own name is the one internal name this resolver serves"
1037        );
1038    }
1039}