Skip to main content

base/interface/exec/
network.rs

1//! `Network` — outbound requests, and whether they may leave.
2//!
3//! Every client in the engine builds its requests through this. What a host
4//! can *replace* today is narrower: the provider a tool uses arrives through
5//! `ToolContext.exec`, while the model, OAuth, telemetry and registry clients
6//! each construct their own. Their traffic is `Origin::Operator`, which no
7//! policy restricts, so the behavior is right — but auditing or going offline
8//! as a whole needs an injection point that does not exist yet.
9
10use std::collections::BTreeMap;
11
12use super::ExecError;
13
14/// Who chose this destination.
15///
16/// The distinction the engine's network policy has always needed and never
17/// had. `allowed_domains` answers "where may the model reach", not "what may
18/// this process connect to" — applying it to everything would cut the agent
19/// off from its own model endpoint.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Origin {
22    /// The model picked the destination: a `WebFetch` url, a `Ping` host,
23    /// `curl` inside a Bash command. Subject to `allowed_domains`, and kept
24    /// off [internal addresses](is_internal_address) unless `allowed_domains`
25    /// names the host.
26    Agent,
27    /// An operator configured the endpoint: the model API, an MCP server,
28    /// telemetry, the plugin marketplace, an OAuth provider. Not subject to
29    /// `allowed_domains`, but still routed here so a deployment can audit,
30    /// rate-limit or go offline as a whole.
31    Operator,
32}
33
34/// How many redirects a provider follows when the caller does not say.
35///
36/// Ten, the figure `reqwest` picks by default, so a caller with no opinion on
37/// redirects gets the behavior it would have had without this contract.
38pub const DEFAULT_MAX_REDIRECTS: u8 = 10;
39
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct HttpRequest {
42    pub method: String,
43    pub url: String,
44    pub headers: BTreeMap<String, String>,
45    pub body: Option<Vec<u8>>,
46    /// Largest response body this caller will accept, in bytes. `None` puts
47    /// no ceiling on it.
48    pub max_bytes: Option<u64>,
49    /// How many redirects the provider may follow on this caller's behalf.
50    ///
51    /// Zero hands the 3xx back instead, which is what a caller wants when the
52    /// redirect target is itself a decision — `WebFetch` returns it to the
53    /// model rather than chasing it.
54    pub max_redirects: u8,
55    /// Refuse every hop whose destination is an
56    /// [internal address](is_internal_address), whoever chose it.
57    ///
58    /// For an endpoint an operator wrote down whose content still comes from
59    /// outside — an HTTP hook is a URL in a settings file a repository can
60    /// ship. `Origin::Agent` requests get the same refusal without asking.
61    pub public_only: bool,
62    /// With `public_only`, the host and port `url` names may be internal:
63    /// a hop to exactly that target is let through, every other hop is still
64    /// held to `public_only`. An `Origin::Agent` request gains nothing from it.
65    pub internal_target: bool,
66}
67
68impl HttpRequest {
69    pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
70        Self {
71            method: method.into(),
72            url: url.into(),
73            headers: BTreeMap::new(),
74            body: None,
75            max_bytes: None,
76            max_redirects: DEFAULT_MAX_REDIRECTS,
77            public_only: false,
78            internal_target: false,
79        }
80    }
81
82    pub fn public_only(mut self) -> Self {
83        self.public_only = true;
84        self
85    }
86
87    /// `public_only`, except that the target `url` names may be internal.
88    pub fn public_only_but_target(mut self) -> Self {
89        self.public_only = true;
90        self.internal_target = true;
91        self
92    }
93
94    pub fn get(url: impl Into<String>) -> Self {
95        Self::new("GET", url)
96    }
97
98    pub fn post(url: impl Into<String>) -> Self {
99        Self::new("POST", url)
100    }
101
102    pub fn header(mut self, k: impl Into<String>, v: impl Into<String>) -> Self {
103        self.headers.insert(k.into(), v.into());
104        self
105    }
106
107    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
108        self.body = Some(body.into());
109        self
110    }
111
112    pub fn max_bytes(mut self, n: u64) -> Self {
113        self.max_bytes = Some(n);
114        self
115    }
116
117    pub fn max_redirects(mut self, n: u8) -> Self {
118        self.max_redirects = n;
119        self
120    }
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct HttpResponse {
125    pub status: u16,
126    pub headers: BTreeMap<String, String>,
127    pub body: Vec<u8>,
128}
129
130impl HttpResponse {
131    pub fn body_text(&self) -> String {
132        String::from_utf8_lossy(&self.body).into_owned()
133    }
134}
135
136/// A response whose body has not been read yet.
137///
138/// The model API is a server-sent-event stream that stays open for the length
139/// of an answer, so an egress that could only hand back a finished body could
140/// not carry the one request the engine makes most. Status and headers arrive
141/// first because that is what the retry ladder classifies on, before a single
142/// body byte exists.
143pub struct HttpStream {
144    pub status: u16,
145    pub headers: BTreeMap<String, String>,
146    pub body: futures::stream::BoxStream<'static, Result<Vec<u8>, ExecError>>,
147}
148
149/// Every outbound request, in one place.
150///
151/// A provider follows redirects up to [`HttpRequest::max_redirects`] and must
152/// re-apply its policy to each hop: a destination the model was allowed to
153/// name could otherwise redirect to one it was not, and the allowlist would
154/// hold only for the first request of a chain. The same goes for refusing
155/// internal addresses, which also has to hold for the address it connects to,
156/// not only the one a name resolved to when it was checked.
157#[async_trait::async_trait]
158pub trait Network: Send + Sync {
159    /// Send, and read the whole body.
160    async fn send(&self, req: HttpRequest, origin: Origin) -> Result<HttpResponse, ExecError>;
161
162    /// Send, and hand back the body as it arrives.
163    ///
164    /// The default reads it all first, which is right for a provider that
165    /// answers from a fixture and wrong for one talking to a live model
166    /// endpoint.
167    async fn open(&self, req: HttpRequest, origin: Origin) -> Result<HttpStream, ExecError> {
168        let r = self.send(req, origin).await?;
169        Ok(HttpStream {
170            status: r.status,
171            headers: r.headers,
172            body: Box::pin(futures::stream::once(async move { Ok(r.body) })),
173        })
174    }
175
176    /// Whether a host would be allowed, without sending anything.
177    ///
178    /// Exists for the callers that have to decide before there is a request:
179    /// `Ping`, and building a sandbox profile that names the hosts a
180    /// subprocess may reach.
181    fn permits(&self, host: &str, origin: Origin) -> bool;
182}
183
184/// Whether `ip` is this machine or a network behind it rather than the public
185/// internet: unspecified, loopback, private, link-local, carrier-grade NAT,
186/// unique-local, site-local, multicast and the reserved blocks, and an IPv6
187/// address that carries one of those IPv4 ones (mapped, compatible, NAT64,
188/// 6to4).
189///
190/// Whether `domains` — `web.allowed_domains`, as written in settings —
191/// names `host`, itself or as a subdomain. Case, a trailing dot and the
192/// brackets around an IPv6 address do not matter.
193pub fn domains_name_host(domains: &[String], host: &str) -> bool {
194    let host = domain_key(host);
195    domains.iter().any(|d| {
196        let d = domain_key(d);
197        !d.is_empty() && (host == d || host.ends_with(&format!(".{d}")))
198    })
199}
200
201/// A `web.allowed_domains` entry or a host, in the form
202/// [`domains_name_host`] compares them in.
203pub fn domain_key(entry: &str) -> String {
204    let bare = entry
205        .trim()
206        .trim_start_matches('[')
207        .trim_end_matches(']')
208        .trim_end_matches('.');
209    match bare.parse::<std::net::IpAddr>() {
210        Ok(ip) => ip.to_string(),
211        Err(_) => bare.to_ascii_lowercase(),
212    }
213}
214
215/// Whether a `web.allowed_domains` entry names this machine's loopback:
216/// `localhost` or a loopback address.
217pub fn names_loopback(entry: &str) -> bool {
218    let key = domain_key(entry);
219    key == "localhost"
220        || key
221            .parse::<std::net::IpAddr>()
222            .is_ok_and(|ip| ip.is_loopback())
223}
224
225/// The one answer to "may a destination chosen from outside reach this", for
226/// a model-directed fetch and an HTTP hook alike.
227pub fn is_internal_address(ip: std::net::IpAddr) -> bool {
228    match ip {
229        std::net::IpAddr::V4(v4) => internal_v4(v4),
230        std::net::IpAddr::V6(v6) => internal_v6(v6),
231    }
232}
233
234fn internal_v4(ip: std::net::Ipv4Addr) -> bool {
235    let [a, b, c, _] = ip.octets();
236    a == 0
237        || ip.is_loopback()
238        || ip.is_private()
239        || ip.is_link_local()
240        || (a == 100 && (64..128).contains(&b))
241        || (a == 192 && b == 0 && c == 0)
242        || (a == 198 && (b == 18 || b == 19))
243        || ip.is_multicast()
244        || a >= 240
245}
246
247fn internal_v6(ip: std::net::Ipv6Addr) -> bool {
248    let first = ip.segments()[0];
249    ip.is_unspecified()
250        || ip.is_loopback()
251        || (first & 0xfe00) == 0xfc00
252        || (first & 0xffc0) == 0xfe80
253        || (first & 0xffc0) == 0xfec0
254        || ip.is_multicast()
255        || matches!(ip.segments(), [0x64, 0xff9b, 1, ..])
256        || carried_v4(ip).is_some_and(internal_v4)
257}
258
259/// The IPv4 address an IPv6 one is a way of reaching: mapped
260/// (`::ffff:a.b.c.d`), SIIT (`::ffff:0:a.b.c.d`), compatible (`::a.b.c.d`),
261/// NAT64 (`64:ff9b::/96`, and the local-use `64:ff9b:1::/48` with the
262/// address in its last 32 bits), 6to4 (`2002::/16`) and Teredo's client
263/// (`2001::/32`, stored inverted).
264pub fn carried_v4(ip: std::net::Ipv6Addr) -> Option<std::net::Ipv4Addr> {
265    if let Some(v4) = ip.to_ipv4_mapped() {
266        return Some(v4);
267    }
268    let from = |hi: u16, lo: u16| {
269        let [a, b] = hi.to_be_bytes();
270        let [c, d] = lo.to_be_bytes();
271        std::net::Ipv4Addr::new(a, b, c, d)
272    };
273    match ip.segments() {
274        [0, 0, 0, 0, 0, 0, hi, lo] => Some(from(hi, lo)),
275        [0, 0, 0, 0, 0xffff, 0, hi, lo] => Some(from(hi, lo)),
276        [0x64, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(from(hi, lo)),
277        [0x64, 0xff9b, 1, _, _, _, hi, lo] => Some(from(hi, lo)),
278        [0x2002, hi, lo, ..] => Some(from(hi, lo)),
279        [0x2001, 0, _, _, _, _, hi, lo] => Some(from(!hi, !lo)),
280        _ => None,
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::{is_internal_address, names_loopback};
287
288    #[test]
289    fn localhost_and_the_loopback_addresses_name_the_loopback() {
290        for entry in [
291            "localhost",
292            "LOCALHOST.",
293            "127.0.0.1",
294            "127.1.2.3",
295            "::1",
296            "[::1]",
297        ] {
298            assert!(names_loopback(entry), "{entry}");
299        }
300        for entry in ["example.com", "localhost.example.com", "10.0.0.1", "*", ""] {
301            assert!(!names_loopback(entry), "{entry}");
302        }
303    }
304
305    #[test]
306    fn every_spelling_of_this_machine_and_the_networks_behind_it_is_internal() {
307        for ip in [
308            "0.0.0.0",
309            "0.1.2.3",
310            "127.0.0.1",
311            "127.255.0.9",
312            "10.0.0.5",
313            "172.16.0.1",
314            "172.31.255.255",
315            "192.168.1.1",
316            "169.254.169.254",
317            "100.64.0.1",
318            "100.127.255.255",
319            "192.0.0.8",
320            "198.18.0.1",
321            "224.0.0.1",
322            "240.0.0.1",
323            "255.255.255.255",
324            "::",
325            "::1",
326            "::ffff:127.0.0.1",
327            "::ffff:10.0.0.1",
328            "::ffff:169.254.169.254",
329            "::127.0.0.1",
330            "64:ff9b::7f00:1",
331            "2002:7f00:1::",
332            "2002:c0a8:101::1",
333            "::ffff:0:7f00:1",
334            "::ffff:0:a00:1",
335            "64:ff9b:1::a9fe:a9fe",
336            "64:ff9b:1:2::808:808",
337            "2001:0:4136:e378:8000:63bf:80ff:fffe",
338            "2001:0:4136:e378:8000:63bf:f5ff:fffe",
339            "fc00::1",
340            "fd12:3456::1",
341            "fe80::1",
342            "febf::1",
343            "fec0::1",
344            "ff02::1",
345        ] {
346            assert!(is_internal_address(ip.parse().expect("an address")), "{ip}");
347        }
348    }
349
350    #[test]
351    fn the_public_internet_is_not() {
352        for ip in [
353            "8.8.8.8",
354            "1.1.1.1",
355            "100.63.255.255",
356            "100.128.0.1",
357            "172.15.255.255",
358            "172.32.0.1",
359            "93.184.216.34",
360            "2001:4860:4860::8888",
361            "2606:4700::1111",
362            "::ffff:8.8.8.8",
363            "64:ff9b::808:808",
364            "2002:808:808::1",
365            "::ffff:0:808:808",
366            "2001:0:4136:e378:8000:63bf:f7f7:f7f7",
367        ] {
368            assert!(
369                !is_internal_address(ip.parse().expect("an address")),
370                "{ip}"
371            );
372        }
373    }
374}