Skip to main content

adk_core/egress/
mod.rs

1//! Network egress policy: which hosts, ports and addresses a connection may reach.
2//!
3//! An [`EgressPolicy`] is a set of [`EgressRule`]s plus two switches, and [`decide`] is a
4//! pure function from a policy and an [`EgressTarget`] to an allow or an [`EgressDenial`].
5//! A connection by host name passes two checks: the name and port before resolution, and
6//! every address the name resolves to at connect time.
7//!
8//! | Rule | Example | Admits |
9//! |------|---------|--------|
10//! | Any host | `*`, `*:443` | Every host name, and IP literals whose address passes the address check |
11//! | Exact host | `api.example.com`, `api.example.com:443` | That name |
12//! | Subdomains | `*.example.com`, `*.example.com:443` | Every name below `example.com`, not `example.com` itself |
13//! | CIDR | `10.0.0.0/8`, `10.0.0.5:5432`, `[fd00::/8]:443` | IP literals in the range on the port, and names that resolve into the range |
14//!
15//! | Address check | Outcome |
16//! |---------------|---------|
17//! | [`AddressClass::Metadata`] (cloud metadata and credential endpoints) | Always refused, whatever the rules say |
18//! | [`AddressClass::Public`] | Admitted |
19//! | Any other class (loopback, private, link-local, ...) | Admitted only inside a CIDR rule, or when [`EgressPolicy::with_private_networks`] is set |
20//!
21//! A rule without a port admits every port. Plain `http` URLs are refused unless
22//! [`EgressPolicy::with_plain_http`] is set. A host name whose last label is numeric, such as
23//! `0x7f.1`, is refused because resolvers read it as an IPv4 address.
24//!
25//! [`EgressPolicy::narrow`] intersects two policies: a destination passes the result only when
26//! it passes both. An operator's policy is the ceiling, and every lower layer narrows it.
27//!
28//! [`ContextUrls`] answers a different question: whether a URL a model chose already appeared
29//! in the conversation, so a fetch tool can refuse a URL the model composed to carry data out
30//! (see [`provenance`] for the sources and the matching rule).
31//!
32//! [`GuardedClient`] (feature `egress-client`) is an HTTP client that enforces a policy on
33//! every request URL, every resolved address and every redirect hop, ignores the environment's
34//! proxy settings, and is never replaced by an unguarded client when it cannot be built.
35//!
36//! # Limits
37//!
38//! - **Not data-loss prevention**: an admitted host receives whatever is sent to it.
39//! - **Not proof against domain fronting**: a host rule matches the name a client asks for;
40//!   a shared CDN can route that connection to another tenant.
41//! - **Only checked connections are covered**: a socket opened directly by code that does not
42//!   consult the policy, including third-party code in the agent's process, is not contained.
43//!
44//! # Example
45//!
46//! ```rust
47//! use adk_core::egress::{EgressPolicy, EgressTarget};
48//!
49//! let operator = EgressPolicy::allowlist(["*.example.com:443", "api.github.com:443"]).unwrap();
50//! let tool = EgressPolicy::allowlist(["api.github.com"]).unwrap();
51//! let effective = operator.narrow(&tool);
52//!
53//! assert!(effective.decide(&EgressTarget::Name { host: "api.github.com", port: 443 }).is_ok());
54//! assert!(effective.decide(&EgressTarget::Name { host: "api.github.com", port: 80 }).is_err());
55//! assert!(effective.decide(&EgressTarget::Name { host: "docs.example.com", port: 443 }).is_err());
56//! assert!(
57//!     effective
58//!         .decide(&EgressTarget::Address {
59//!             host: "api.github.com",
60//!             address: "10.0.0.7".parse().unwrap(),
61//!         })
62//!         .is_err()
63//! );
64//! ```
65//!
66//! [`decide`]: EgressPolicy::decide
67
68mod address;
69#[cfg(feature = "egress-client")]
70mod client;
71pub mod provenance;
72
73use std::collections::HashMap;
74use std::fmt;
75use std::net::{IpAddr, Ipv4Addr, SocketAddr};
76use std::str::FromStr;
77
78use async_trait::async_trait;
79use serde::{Deserialize, Deserializer, Serialize, Serializer};
80
81pub use address::{AddressClass, classify, is_non_public};
82#[cfg(feature = "egress-client")]
83pub use client::{EgressClientError, EgressResolver, GuardedClient, GuardedClientBuilder};
84pub use provenance::{ContextUrls, ToolResultSources, UrlSources, normalize_url};
85
86/// Which host names a [`EgressRule::Host`] admits.
87///
88/// # Example
89///
90/// ```rust
91/// use adk_core::egress::HostPattern;
92///
93/// let pattern: HostPattern = "*.example.com".parse().unwrap();
94/// assert!(pattern.matches("api.example.com"));
95/// assert!(!pattern.matches("example.com"));
96/// ```
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub enum HostPattern {
99    /// Every host name.
100    Any,
101    /// One host name, lowercase, without a trailing dot.
102    Exact(String),
103    /// Every name below this domain (written `*.domain`), not the domain itself.
104    Subdomains(String),
105}
106
107impl HostPattern {
108    /// Whether `host` matches; `host` is compared case-insensitively, without a trailing dot.
109    pub fn matches(&self, host: &str) -> bool {
110        let host = normalize_host(host);
111        match self {
112            Self::Any => true,
113            Self::Exact(name) => host == *name,
114            Self::Subdomains(domain) => {
115                host.len() > domain.len() + 1
116                    && host.ends_with(domain.as_str())
117                    && host.as_bytes()[host.len() - domain.len() - 1] == b'.'
118            }
119        }
120    }
121}
122
123impl FromStr for HostPattern {
124    type Err = EgressRuleError;
125
126    fn from_str(s: &str) -> Result<Self, Self::Err> {
127        let invalid = |reason: &str| EgressRuleError::new(s, reason);
128        let host = normalize_host(s);
129        if host == "*" {
130            return Ok(Self::Any);
131        }
132        let (domain, wildcard) = match host.strip_prefix("*.") {
133            Some(domain) => (domain, true),
134            None => (host.as_str(), false),
135        };
136        if domain.is_empty() || domain.len() > 253 {
137            return Err(invalid("a host name has 1 to 253 characters"));
138        }
139        for label in domain.split('.') {
140            if label.is_empty() || label.len() > 63 {
141                return Err(invalid("every label of a host name has 1 to 63 characters"));
142            }
143            if !label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
144                return Err(invalid(
145                    "a host name holds letters, digits, '-' and '_' only; write \
146                     internationalized names in their xn-- form, and a wildcard only as a \
147                     leading '*.'",
148                ));
149            }
150        }
151        if is_numeric_host(domain) {
152            return Err(invalid("a numeric host name is read as an IPv4 address; write a CIDR"));
153        }
154        Ok(if wildcard { Self::Subdomains(domain.to_string()) } else { Self::Exact(host) })
155    }
156}
157
158impl fmt::Display for HostPattern {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::Any => f.write_str("*"),
162            Self::Exact(name) => f.write_str(name),
163            Self::Subdomains(domain) => write!(f, "*.{domain}"),
164        }
165    }
166}
167
168/// An IP address range: a network address and a prefix length.
169///
170/// An IPv4-mapped IPv6 range (`::ffff:a.b.c.d/96+`) is stored as its IPv4 range, and
171/// [`contains`](Self::contains) compares IPv4-mapped addresses as IPv4.
172///
173/// # Example
174///
175/// ```rust
176/// use adk_core::egress::IpCidr;
177///
178/// let cidr: IpCidr = "10.0.0.0/8".parse().unwrap();
179/// assert!(cidr.contains("10.20.30.40".parse().unwrap()));
180/// assert!(cidr.contains("::ffff:10.0.0.1".parse().unwrap()));
181/// assert!(!cidr.contains("11.0.0.1".parse().unwrap()));
182/// assert!("10.0.0.1/8".parse::<IpCidr>().is_err());
183/// ```
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
185pub struct IpCidr {
186    network: IpAddr,
187    prefix: u8,
188}
189
190impl IpCidr {
191    /// A range of `prefix` leading bits of `network`.
192    ///
193    /// # Errors
194    ///
195    /// Returns an error when `prefix` is longer than the address or `network` has bits set
196    /// after the prefix.
197    pub fn new(network: IpAddr, prefix: u8) -> Result<Self, EgressRuleError> {
198        let (network, prefix) = match network {
199            IpAddr::V6(v6) if prefix >= 96 => match v6.to_ipv4_mapped() {
200                Some(v4) => (IpAddr::V4(v4), prefix - 96),
201                None => (network, prefix),
202            },
203            IpAddr::V4(_) | IpAddr::V6(_) => (network, prefix),
204        };
205        let text = format!("{network}/{prefix}");
206        let bits = match network {
207            IpAddr::V4(_) => 32,
208            IpAddr::V6(_) => 128,
209        };
210        if prefix > bits {
211            return Err(EgressRuleError::new(&text, "the prefix is longer than the address"));
212        }
213        let cidr = Self { network, prefix };
214        if cidr.masked(network) != address_bits(network) {
215            return Err(EgressRuleError::new(
216                &text,
217                "the address has bits set after the prefix; write the network address",
218            ));
219        }
220        Ok(cidr)
221    }
222
223    /// The network address.
224    pub fn network(&self) -> IpAddr {
225        self.network
226    }
227
228    /// The prefix length in bits.
229    pub fn prefix(&self) -> u8 {
230        self.prefix
231    }
232
233    /// Whether `ip` is inside the range.
234    pub fn contains(&self, ip: IpAddr) -> bool {
235        let ip = ip.to_canonical();
236        let same_family = matches!(
237            (self.network, ip),
238            (IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
239        );
240        same_family && self.masked(ip) == self.masked(self.network)
241    }
242
243    fn masked(&self, ip: IpAddr) -> u128 {
244        let width: u32 = match ip {
245            IpAddr::V4(_) => 32,
246            IpAddr::V6(_) => 128,
247        };
248        let host_bits = width - u32::from(self.prefix).min(width);
249        let bits = address_bits(ip);
250        if host_bits >= 128 { 0 } else { (bits >> host_bits) << host_bits }
251    }
252}
253
254fn address_bits(ip: IpAddr) -> u128 {
255    match ip {
256        IpAddr::V4(v4) => u128::from(u32::from(v4)),
257        IpAddr::V6(v6) => u128::from(v6),
258    }
259}
260
261impl FromStr for IpCidr {
262    type Err = EgressRuleError;
263
264    fn from_str(s: &str) -> Result<Self, Self::Err> {
265        let invalid = |reason: &str| EgressRuleError::new(s, reason);
266        let (address, prefix) = match s.split_once('/') {
267            Some((address, prefix)) => (address, Some(prefix)),
268            None => (s, None),
269        };
270        let network: IpAddr = address.parse().map_err(|_| invalid("not an IP address"))?;
271        let prefix = match prefix {
272            Some(prefix) => prefix.parse().map_err(|_| invalid("the prefix is not a number"))?,
273            None if network.is_ipv4() => 32,
274            None => 128,
275        };
276        Self::new(network, prefix).map_err(|e| EgressRuleError { rule: s.to_string(), ..e })
277    }
278}
279
280impl fmt::Display for IpCidr {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        write!(f, "{}/{}", self.network, self.prefix)
283    }
284}
285
286/// One rule of an [`EgressPolicy`].
287///
288/// Rules parse from and display as text; a rule without a port admits every port.
289///
290/// | Text | Rule |
291/// |------|------|
292/// | `*`, `*:443` | Any host name |
293/// | `api.example.com`, `api.example.com:443` | One host name |
294/// | `*.example.com`, `*.example.com:443` | Every subdomain |
295/// | `10.0.0.0/8`, `10.0.0.5:5432`, `fd00::/8`, `[fd00::/8]:443`, `[::1]:8080` | An address range |
296///
297/// # Example
298///
299/// ```rust
300/// use adk_core::egress::EgressRule;
301///
302/// let rule: EgressRule = "*.example.com:443".parse().unwrap();
303/// assert_eq!(rule.to_string(), "*.example.com:443");
304/// assert_eq!(EgressRule::host("API.Example.com.").unwrap().on_port(8443).to_string(), "api.example.com:8443");
305/// assert!("exa mple.com".parse::<EgressRule>().is_err());
306/// ```
307#[derive(Debug, Clone, PartialEq, Eq, Hash)]
308pub enum EgressRule {
309    /// Admits host names.
310    Host {
311        /// The names admitted.
312        pattern: HostPattern,
313        /// The one port admitted, or every port.
314        port: Option<u16>,
315    },
316    /// Admits an address range.
317    Cidr {
318        /// The range admitted.
319        cidr: IpCidr,
320        /// The one port admitted for IP literals in the range, or every port.
321        port: Option<u16>,
322    },
323}
324
325impl EgressRule {
326    /// A rule admitting every host name on every port.
327    pub fn any_host() -> Self {
328        Self::Host { pattern: HostPattern::Any, port: None }
329    }
330
331    /// A rule admitting `host` (a name, or `*.domain` for its subdomains) on every port.
332    ///
333    /// # Errors
334    ///
335    /// Returns an error when `host` is not a valid host name or wildcard.
336    pub fn host(host: &str) -> Result<Self, EgressRuleError> {
337        Ok(Self::Host { pattern: host.parse()?, port: None })
338    }
339
340    /// A rule admitting `cidr` on every port.
341    pub fn cidr(cidr: IpCidr) -> Self {
342        Self::Cidr { cidr, port: None }
343    }
344
345    /// Restricts the rule to `port`.
346    #[must_use]
347    pub fn on_port(self, port: u16) -> Self {
348        match self {
349            Self::Host { pattern, .. } => Self::Host { pattern, port: Some(port) },
350            Self::Cidr { cidr, .. } => Self::Cidr { cidr, port: Some(port) },
351        }
352    }
353
354    fn admits_port(&self, port: u16) -> bool {
355        match self {
356            Self::Host { port: allowed, .. } | Self::Cidr { port: allowed, .. } => {
357                allowed.is_none_or(|allowed| allowed == port)
358            }
359        }
360    }
361}
362
363impl FromStr for EgressRule {
364    type Err = EgressRuleError;
365
366    fn from_str(s: &str) -> Result<Self, Self::Err> {
367        let invalid = |reason: &str| EgressRuleError::new(s, reason);
368        let text = s.trim();
369        let parse_port = |port: &str| match port.parse::<u16>() {
370            Ok(0) | Err(_) => Err(invalid("the port is a number from 1 to 65535")),
371            Ok(port) => Ok(port),
372        };
373        let at_port = |rule: Self, port: Option<&str>| match port {
374            Some(port) => Ok(rule.on_port(parse_port(port)?)),
375            None => Ok(rule),
376        };
377        if text.is_empty() {
378            return Err(invalid("the rule is empty"));
379        }
380        if let Some(rest) = text.strip_prefix('[') {
381            let (inner, after) =
382                rest.split_once(']').ok_or_else(|| invalid("a '[' has no closing ']'"))?;
383            let port = match after {
384                "" => None,
385                after => Some(
386                    after.strip_prefix(':').ok_or_else(|| invalid("expected ':port' after ']'"))?,
387                ),
388            };
389            let cidr = inner.parse().map_err(|e: EgressRuleError| invalid(&e.reason))?;
390            return at_port(Self::cidr(cidr), port);
391        }
392        // More than one ':' is a bare IPv6 address or range, which takes no port.
393        if text.matches(':').count() > 1 {
394            let cidr = text.parse().map_err(|e: EgressRuleError| invalid(&e.reason))?;
395            return Ok(Self::cidr(cidr));
396        }
397        let (host, port) = match text.rsplit_once(':') {
398            Some((host, port)) => (host, Some(port)),
399            None => (text, None),
400        };
401        if host.contains('/') || host.parse::<Ipv4Addr>().is_ok() {
402            let cidr = host.parse().map_err(|e: EgressRuleError| invalid(&e.reason))?;
403            return at_port(Self::cidr(cidr), port);
404        }
405        let pattern = host.parse().map_err(|e: EgressRuleError| invalid(&e.reason))?;
406        at_port(Self::Host { pattern, port: None }, port)
407    }
408}
409
410impl fmt::Display for EgressRule {
411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412        match self {
413            Self::Host { pattern, port: None } => write!(f, "{pattern}"),
414            Self::Host { pattern, port: Some(port) } => write!(f, "{pattern}:{port}"),
415            Self::Cidr { cidr, port: None } => write!(f, "{cidr}"),
416            Self::Cidr { cidr, port: Some(port) } if cidr.network.is_ipv6() => {
417                write!(f, "[{cidr}]:{port}")
418            }
419            Self::Cidr { cidr, port: Some(port) } => write!(f, "{cidr}:{port}"),
420        }
421    }
422}
423
424impl Serialize for EgressRule {
425    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
426        serializer.collect_str(self)
427    }
428}
429
430impl<'de> Deserialize<'de> for EgressRule {
431    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
432        let text = String::deserialize(deserializer)?;
433        text.parse().map_err(serde::de::Error::custom)
434    }
435}
436
437/// A rule that does not parse.
438#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
439#[error(
440    "invalid egress rule '{rule}': {reason}. A rule is a host (api.example.com), a wildcard \
441     (*.example.com), '*' for any host, or a CIDR (10.0.0.0/8), each optionally followed by \
442     ':port'; write an IPv6 range with a port as [fd00::/8]:443"
443)]
444pub struct EgressRuleError {
445    /// The rule text.
446    pub rule: String,
447    /// What is wrong with it.
448    pub reason: String,
449}
450
451impl EgressRuleError {
452    fn new(rule: &str, reason: &str) -> Self {
453        Self { rule: rule.to_string(), reason: reason.to_string() }
454    }
455}
456
457/// A destination [`EgressPolicy::decide`] checks.
458///
459/// A connection by name passes when both its [`Name`](Self::Name) and every
460/// [`Address`](Self::Address) the name resolves to pass.
461#[derive(Debug, Clone, Copy, PartialEq, Eq)]
462pub enum EgressTarget<'a> {
463    /// A host name and port, before resolution. A host that is an IP address literal,
464    /// bracketed or not, is checked as a [`Literal`](Self::Literal).
465    Name {
466        /// The host name.
467        host: &'a str,
468        /// The port.
469        port: u16,
470    },
471    /// One address `host` resolved to, at connect time.
472    Address {
473        /// The host name that resolved to `address`, for the denial message.
474        host: &'a str,
475        /// The resolved address.
476        address: IpAddr,
477    },
478    /// An IP address literal and port.
479    Literal(SocketAddr),
480}
481
482/// Why an [`EgressPolicy`] refused a destination.
483///
484/// The `Display` form is the guidance a caller or a model reads; [`code`](Self::code) is
485/// a stable identifier for audit records.
486#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
487pub enum EgressDenial {
488    /// No host rule admits the name and port.
489    #[error(
490        "egress to {host}:{port} is refused: no rule of the egress policy admits it; add a host \
491         rule for it to the policy if it should be reachable"
492    )]
493    HostNotAllowed {
494        /// The host name.
495        host: String,
496        /// The port.
497        port: u16,
498    },
499    /// An IP address literal no rule admits.
500    #[error(
501        "egress to the IP address {address} is refused: no CIDR rule of the egress policy admits \
502         it; connect by host name, or add a CIDR rule for the address"
503    )]
504    LiteralNotAllowed {
505        /// The address and port.
506        address: SocketAddr,
507    },
508    /// A non-public address outside every CIDR rule.
509    #[error(
510        "egress to {host} is refused: it reaches {address}, a {class} address; non-public \
511         addresses need a CIDR rule for them or private networks allowed in the egress policy"
512    )]
513    AddressNotAllowed {
514        /// The host name or literal.
515        host: String,
516        /// The address.
517        address: IpAddr,
518        /// The address's class.
519        class: AddressClass,
520    },
521    /// A cloud metadata or credential endpoint, which no policy admits.
522    #[error(
523        "egress to {host} is refused: {address} is a cloud metadata or credential endpoint, \
524         which is always blocked"
525    )]
526    MetadataAddress {
527        /// The host name or literal.
528        host: String,
529        /// The address.
530        address: IpAddr,
531    },
532    /// A host name some resolvers read as an IPv4 address.
533    #[error(
534        "egress to '{host}' is refused: a host name ending in a numeric label is read as an \
535         IPv4 address by some resolvers; use the dotted-quad address"
536    )]
537    AmbiguousHost {
538        /// The host name.
539        host: String,
540    },
541    /// Plain `http` under a policy that requires `https`.
542    #[error(
543        "egress to {host} over plain http is refused; use https, or allow plain http in the \
544         egress policy"
545    )]
546    PlainHttp {
547        /// The host.
548        host: String,
549    },
550    /// A URL scheme other than `http` or `https`.
551    #[error("egress over the URL scheme '{scheme}' is refused; use https")]
552    Scheme {
553        /// The scheme.
554        scheme: String,
555    },
556    /// A URL that does not parse or has no host.
557    #[error("egress URL is invalid: {reason}")]
558    InvalidUrl {
559        /// What is wrong with it.
560        reason: String,
561    },
562}
563
564impl EgressDenial {
565    /// A stable identifier for audit records, such as `egress.host_not_allowed`.
566    pub fn code(&self) -> &'static str {
567        match self {
568            Self::HostNotAllowed { .. } => "egress.host_not_allowed",
569            Self::LiteralNotAllowed { .. } => "egress.literal_not_allowed",
570            Self::AddressNotAllowed { .. } => "egress.address_not_allowed",
571            Self::MetadataAddress { .. } => "egress.metadata_address",
572            Self::AmbiguousHost { .. } => "egress.ambiguous_host",
573            Self::PlainHttp { .. } => "egress.plain_http",
574            Self::Scheme { .. } => "egress.scheme",
575            Self::InvalidUrl { .. } => "egress.invalid_url",
576        }
577    }
578}
579
580/// The first [`EgressDenial`] in `error`'s source chain, such as the refusal inside a failed
581/// [`GuardedClient`] request.
582///
583/// # Example
584///
585/// ```rust
586/// use adk_core::egress::{EgressDenial, find_denial};
587///
588/// let denial = EgressDenial::AmbiguousHost { host: "0x7f.1".into() };
589/// assert_eq!(find_denial(&denial), Some(&denial));
590/// ```
591pub fn find_denial<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a EgressDenial> {
592    let mut current = Some(error);
593    while let Some(error) = current {
594        if let Some(denial) = error.downcast_ref::<EgressDenial>() {
595            return Some(denial);
596        }
597        current = error.source();
598    }
599    None
600}
601
602#[derive(Debug, Clone, PartialEq, Eq, Default)]
603struct RuleSet {
604    rules: Vec<EgressRule>,
605    private_networks: bool,
606    plain_http: bool,
607}
608
609impl RuleSet {
610    fn admits_name(&self, host: &str, port: u16) -> bool {
611        self.rules.iter().any(|rule| match rule {
612            EgressRule::Host { pattern, .. } => pattern.matches(host) && rule.admits_port(port),
613            EgressRule::Cidr { .. } => false,
614        })
615    }
616
617    fn admits_address(&self, address: IpAddr, class: AddressClass) -> bool {
618        class.is_public()
619            || self.private_networks
620            || self.rules.iter().any(|rule| match rule {
621                EgressRule::Cidr { cidr, .. } => cidr.contains(address),
622                EgressRule::Host { .. } => false,
623            })
624    }
625
626    fn admits_literal(&self, address: SocketAddr, class: AddressClass) -> Result<(), EgressDenial> {
627        let in_range = self.rules.iter().any(|rule| match rule {
628            EgressRule::Cidr { cidr, .. } => {
629                cidr.contains(address.ip()) && rule.admits_port(address.port())
630            }
631            EgressRule::Host { .. } => false,
632        });
633        let any_host = self.rules.iter().any(|rule| {
634            matches!(rule, EgressRule::Host { pattern: HostPattern::Any, .. })
635                && rule.admits_port(address.port())
636        });
637        if in_range || (any_host && self.admits_address(address.ip(), class)) {
638            Ok(())
639        } else if any_host {
640            Err(EgressDenial::AddressNotAllowed {
641                host: address.ip().to_string(),
642                address: address.ip(),
643                class,
644            })
645        } else {
646            Err(EgressDenial::LiteralNotAllowed { address })
647        }
648    }
649}
650
651impl fmt::Display for RuleSet {
652    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653        if self.rules.is_empty() {
654            f.write_str("nothing")?;
655        }
656        for (index, rule) in self.rules.iter().enumerate() {
657            if index > 0 {
658                f.write_str(", ")?;
659            }
660            write!(f, "{rule}")?;
661        }
662        if self.private_networks {
663            f.write_str(" +private-networks")?;
664        }
665        if self.plain_http {
666            f.write_str(" +plain-http")?;
667        }
668        Ok(())
669    }
670}
671
672/// Which hosts, ports and addresses connections may reach; see the [module](self) docs.
673///
674/// The default is [`public_only`](Self::public_only).
675///
676/// # Example
677///
678/// ```rust
679/// use adk_core::egress::{EgressPolicy, EgressRule, EgressTarget};
680///
681/// let policy = EgressPolicy::deny_all()
682///     .allow("pypi.org:443".parse().unwrap())
683///     .allow("*.pythonhosted.org:443".parse().unwrap())
684///     .allow(EgressRule::cidr("10.20.0.0/16".parse().unwrap()).on_port(5432));
685///
686/// assert!(policy.check_url("https://files.pythonhosted.org/simple/").is_ok());
687/// assert!(policy.check_url("http://pypi.org/").is_err());
688/// assert!(policy.decide(&EgressTarget::Literal("10.20.1.2:5432".parse().unwrap())).is_ok());
689/// assert!(policy.decide(&EgressTarget::Literal("10.20.1.2:22".parse().unwrap())).is_err());
690/// assert!(EgressPolicy::default().check_url("https://169.254.169.254/latest").is_err());
691/// ```
692#[derive(Debug, Clone, PartialEq, Eq)]
693pub struct EgressPolicy {
694    // Every layer must admit a destination; `narrow` appends layers, so a narrowed policy
695    // never admits more than any policy it was narrowed by.
696    layers: Vec<RuleSet>,
697    // Set by `narrow`: the builder methods then change nothing, since editing any layer could
698    // widen a policy the result was narrowed by.
699    narrowed: bool,
700}
701
702impl Default for EgressPolicy {
703    fn default() -> Self {
704        Self::public_only()
705    }
706}
707
708impl EgressPolicy {
709    /// A policy that admits nothing until rules are added.
710    pub fn deny_all() -> Self {
711        Self { layers: vec![RuleSet::default()], narrowed: false }
712    }
713
714    /// Any host over `https`, on public addresses only.
715    pub fn public_only() -> Self {
716        Self::deny_all().allow(EgressRule::any_host())
717    }
718
719    /// Any host over `http` or `https`, on any address except cloud metadata endpoints.
720    ///
721    /// For in-cluster receivers and tests, where an operator configures every endpoint; never
722    /// where callers register their own URLs.
723    pub fn allow_private_networks() -> Self {
724        Self::public_only().with_private_networks().with_plain_http()
725    }
726
727    /// A policy admitting exactly `rules`, over `https`, with non-public addresses admitted only
728    /// inside CIDR rules.
729    ///
730    /// # Errors
731    ///
732    /// Returns the first rule that does not parse.
733    ///
734    /// # Example
735    ///
736    /// ```rust
737    /// use adk_core::egress::EgressPolicy;
738    ///
739    /// let policy = EgressPolicy::allowlist(["api.github.com:443", "*.githubusercontent.com"]).unwrap();
740    /// assert!(policy.check_url("https://raw.githubusercontent.com/a/b").is_ok());
741    /// assert!(EgressPolicy::allowlist(["https://api.github.com"]).is_err());
742    /// ```
743    pub fn allowlist<I, S>(rules: I) -> Result<Self, EgressRuleError>
744    where
745        I: IntoIterator<Item = S>,
746        S: AsRef<str>,
747    {
748        rules
749            .into_iter()
750            .try_fold(Self::deny_all(), |policy, rule| Ok(policy.allow(rule.as_ref().parse()?)))
751    }
752
753    /// Adds `rule`. A narrowed policy is unchanged: it can only be narrowed further.
754    #[must_use]
755    pub fn allow(mut self, rule: EgressRule) -> Self {
756        if !self.narrowed && !self.layers[0].rules.contains(&rule) {
757            self.layers[0].rules.push(rule);
758        }
759        self
760    }
761
762    /// Admits loopback, private and other non-public addresses (never cloud metadata). A
763    /// narrowed policy is unchanged: it can only be narrowed further.
764    #[must_use]
765    pub fn with_private_networks(mut self) -> Self {
766        if !self.narrowed {
767            self.layers[0].private_networks = true;
768        }
769        self
770    }
771
772    /// Admits plain `http` URLs. A narrowed policy is unchanged: it can only be narrowed
773    /// further.
774    #[must_use]
775    pub fn with_plain_http(mut self) -> Self {
776        if !self.narrowed {
777            self.layers[0].plain_http = true;
778        }
779        self
780    }
781
782    /// Whether the policy came from [`narrow`](Self::narrow), so the builder methods no longer
783    /// change it.
784    pub fn is_narrowed(&self) -> bool {
785        self.narrowed
786    }
787
788    /// The intersection of `self` and `other`: a destination passes only when it passes both.
789    ///
790    /// The result can only be narrowed further: [`allow`](Self::allow) and the switches leave it
791    /// unchanged, so no layer below an operator's ceiling can widen it.
792    ///
793    /// # Example
794    ///
795    /// ```rust
796    /// use adk_core::egress::EgressPolicy;
797    ///
798    /// let ceiling = EgressPolicy::allowlist(["*.example.com"]).unwrap();
799    /// let wider = EgressPolicy::allowlist(["*.example.com", "evil.test"]).unwrap();
800    /// let narrowed = ceiling.narrow(&wider);
801    /// assert!(narrowed.check_url("https://api.example.com/").is_ok());
802    /// assert!(narrowed.check_url("https://evil.test/").is_err());
803    /// ```
804    #[must_use]
805    pub fn narrow(&self, other: &Self) -> Self {
806        let mut layers = self.layers.clone();
807        for layer in &other.layers {
808            if !layers.contains(layer) {
809                layers.push(layer.clone());
810            }
811        }
812        Self { layers, narrowed: true }
813    }
814
815    /// Whether plain `http` URLs are admitted.
816    pub fn allows_plain_http(&self) -> bool {
817        self.layers.iter().all(|layer| layer.plain_http)
818    }
819
820    /// Whether every non-public address (except cloud metadata) is admitted.
821    pub fn allows_private_networks(&self) -> bool {
822        self.layers.iter().all(|layer| layer.private_networks)
823    }
824
825    /// Admits or refuses `target`.
826    ///
827    /// # Errors
828    ///
829    /// Returns why `target` is refused.
830    pub fn decide(&self, target: &EgressTarget<'_>) -> Result<(), EgressDenial> {
831        match *target {
832            EgressTarget::Name { host, port } => {
833                let unbracketed =
834                    host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
835                if let Ok(ip) = unbracketed.parse::<IpAddr>() {
836                    return self.decide(&EgressTarget::Literal(SocketAddr::new(ip, port)));
837                }
838                let host = normalize_host(host);
839                if is_numeric_host(&host) {
840                    return Err(EgressDenial::AmbiguousHost { host });
841                }
842                if !self.layers.iter().all(|layer| layer.admits_name(&host, port)) {
843                    return Err(EgressDenial::HostNotAllowed { host, port });
844                }
845                // localhost names resolve to loopback (RFC 6761) whatever DNS says.
846                if host == "localhost" || host.ends_with(".localhost") {
847                    let loopback = IpAddr::V4(Ipv4Addr::LOCALHOST);
848                    return self.decide(&EgressTarget::Address { host: &host, address: loopback });
849                }
850                Ok(())
851            }
852            EgressTarget::Address { host, address } => {
853                let class = classify(address);
854                if class == AddressClass::Metadata {
855                    return Err(EgressDenial::MetadataAddress { host: host.to_string(), address });
856                }
857                if self.layers.iter().all(|layer| layer.admits_address(address, class)) {
858                    Ok(())
859                } else {
860                    Err(EgressDenial::AddressNotAllowed { host: host.to_string(), address, class })
861                }
862            }
863            EgressTarget::Literal(address) => {
864                let class = classify(address.ip());
865                if class == AddressClass::Metadata {
866                    return Err(EgressDenial::MetadataAddress {
867                        host: address.ip().to_string(),
868                        address: address.ip(),
869                    });
870                }
871                self.layers.iter().try_for_each(|layer| layer.admits_literal(address, class))
872            }
873        }
874    }
875
876    /// Parses `url` and checks its scheme, host and port; see
877    /// [`check_parsed_url`](Self::check_parsed_url).
878    ///
879    /// # Errors
880    ///
881    /// Returns why the URL is refused.
882    pub fn check_url(&self, url: &str) -> Result<url::Url, EgressDenial> {
883        let parsed =
884            url::Url::parse(url).map_err(|e| EgressDenial::InvalidUrl { reason: e.to_string() })?;
885        self.check_parsed_url(&parsed)?;
886        Ok(parsed)
887    }
888
889    /// Checks a URL's scheme (`https`, or `http` when admitted), and its host and port: an IP
890    /// address literal completely, a host name before resolution. The addresses a name resolves
891    /// to are checked by the client that connects, as [`EgressTarget::Address`].
892    ///
893    /// # Errors
894    ///
895    /// Returns why the URL is refused.
896    pub fn check_parsed_url(&self, url: &url::Url) -> Result<(), EgressDenial> {
897        let host = || url.host_str().unwrap_or_default().to_string();
898        match url.scheme() {
899            "https" => {}
900            "http" if self.allows_plain_http() => {}
901            "http" => return Err(EgressDenial::PlainHttp { host: host() }),
902            other => return Err(EgressDenial::Scheme { scheme: other.to_string() }),
903        }
904        let port = url
905            .port_or_known_default()
906            .ok_or_else(|| EgressDenial::InvalidUrl { reason: "the URL has no port".into() })?;
907        match url.host() {
908            Some(url::Host::Domain(host)) => self.decide(&EgressTarget::Name { host, port }),
909            Some(url::Host::Ipv4(ip)) => {
910                self.decide(&EgressTarget::Literal(SocketAddr::new(IpAddr::V4(ip), port)))
911            }
912            Some(url::Host::Ipv6(ip)) => {
913                self.decide(&EgressTarget::Literal(SocketAddr::new(IpAddr::V6(ip), port)))
914            }
915            None => Err(EgressDenial::InvalidUrl { reason: "the URL has no host".into() }),
916        }
917    }
918}
919
920impl fmt::Display for EgressPolicy {
921    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
922        for (index, layer) in self.layers.iter().enumerate() {
923            if index > 0 {
924                f.write_str("; narrowed by ")?;
925            }
926            write!(f, "{layer}")?;
927        }
928        Ok(())
929    }
930}
931
932fn normalize_host(host: &str) -> String {
933    host.strip_suffix('.').unwrap_or(host).to_ascii_lowercase()
934}
935
936/// Whether the last label is decimal or `0x` hex, which `inet_aton`-style resolvers read as
937/// part of an IPv4 address (`127.1`, `0x7f.1`, `2130706433`).
938fn is_numeric_host(host: &str) -> bool {
939    let last = host.rsplit('.').next().unwrap_or(host);
940    let hex = last.strip_prefix("0x").map(|digits| digits.bytes().all(|b| b.is_ascii_hexdigit()));
941    (!last.is_empty() && last.bytes().all(|b| b.is_ascii_digit())) || hex == Some(true)
942}
943
944/// What a tool declares about the network destinations a call reaches ([`Tool::egress`]).
945///
946/// Under a run egress policy ([`RunConfig::egress_policy`](crate::RunConfig::egress_policy)),
947/// [`authorize_tool_call`](crate::authorize_tool_call) refuses a call before it runs unless
948/// [`EgressPolicy::admits_tool`] admits its declaration. Without a run egress policy the
949/// declaration is not consulted. A declaration is the tool author's statement; only the
950/// connections of a [`GuardedClient`] or a sandbox's egress proxy are enforced.
951///
952/// | Declaration | Under a run egress policy |
953/// |-------------|---------------------------|
954/// | `Undeclared` (the default) | Refused |
955/// | `None` | Admitted: the call opens no network connection |
956/// | `Configured` | Admitted: the call reaches only endpoints the operator fixed when building the tool (a database, a model provider), never one its arguments choose |
957/// | `Enforced` | Admitted: every connection the call makes is checked against the run's policy when it is made |
958/// | `Destinations(rules)` | Admitted when the policy covers every rule ([`EgressPolicy::covers`]) |
959///
960/// [`Tool::egress`]: crate::Tool::egress
961///
962/// # Example
963///
964/// ```rust
965/// use adk_core::egress::{EgressPolicy, ToolEgress};
966///
967/// let policy = EgressPolicy::allowlist(["api.github.com:443"]).unwrap();
968/// let call = ToolEgress::for_urls(["https://api.github.com/repos/a/b"]);
969/// assert!(policy.admits_tool(&call).is_ok());
970/// assert!(policy.admits_tool(&ToolEgress::for_urls(["https://example.com/"])).is_err());
971/// assert!(policy.admits_tool(&ToolEgress::Undeclared).is_err());
972/// assert!(policy.admits_tool(&ToolEgress::None).is_ok());
973/// ```
974#[derive(Debug, Clone, Default, PartialEq, Eq)]
975pub enum ToolEgress {
976    /// The tool says nothing about its network use.
977    #[default]
978    Undeclared,
979    /// The call opens no network connection.
980    None,
981    /// The call reaches only endpoints the operator fixed when building the tool.
982    Configured,
983    /// Every connection the call makes is checked against the run's egress policy when it is
984    /// made, by a [`GuardedClient`] built from it or by a sandbox's egress proxy.
985    Enforced,
986    /// The call reaches only these destinations.
987    Destinations(Vec<EgressRule>),
988}
989
990impl ToolEgress {
991    /// The destinations of `urls`: each URL's host and port (`https` 443 and `http` 80 by
992    /// default). A URL that does not parse, has no host, or names a numeric host makes the
993    /// whole declaration [`Undeclared`](Self::Undeclared), which a run egress policy refuses.
994    pub fn for_urls<I, S>(urls: I) -> Self
995    where
996        I: IntoIterator<Item = S>,
997        S: AsRef<str>,
998    {
999        let mut rules = Vec::new();
1000        for url in urls {
1001            let Ok(parsed) = url::Url::parse(url.as_ref()) else { return Self::Undeclared };
1002            let Some(port) = parsed.port_or_known_default() else { return Self::Undeclared };
1003            let rule = match parsed.host() {
1004                Some(url::Host::Domain(host)) => match EgressRule::host(host) {
1005                    Ok(rule) => rule,
1006                    Err(_) => return Self::Undeclared,
1007                },
1008                Some(url::Host::Ipv4(ip)) => {
1009                    EgressRule::cidr(IpCidr { network: ip.into(), prefix: 32 })
1010                }
1011                Some(url::Host::Ipv6(ip)) => {
1012                    EgressRule::cidr(IpCidr { network: ip.into(), prefix: 128 })
1013                }
1014                None => return Self::Undeclared,
1015            };
1016            rules.push(rule.on_port(port));
1017        }
1018        Self::Destinations(rules)
1019    }
1020}
1021
1022impl EgressPolicy {
1023    /// Whether every destination `rule` names passes the policy's host, port and literal
1024    /// rules. Addresses are not checked here: a name in a covered rule is still refused at
1025    /// connect time when it resolves to an address the policy refuses.
1026    ///
1027    /// Coverage is by a single rule of each layer: a declared `*.example.com` is covered by
1028    /// `*.example.com` or `*`, not by a list of its subdomains; a declared CIDR only by a CIDR
1029    /// rule containing it.
1030    ///
1031    /// # Example
1032    ///
1033    /// ```rust
1034    /// use adk_core::egress::{EgressPolicy, EgressRule};
1035    ///
1036    /// let policy = EgressPolicy::allowlist(["*.example.com:443"]).unwrap();
1037    /// assert!(policy.covers(&"api.example.com:443".parse().unwrap()));
1038    /// assert!(policy.covers(&"*.eu.example.com:443".parse().unwrap()));
1039    /// assert!(!policy.covers(&"api.example.com".parse().unwrap()));
1040    /// assert!(!policy.covers(&EgressRule::any_host()));
1041    /// ```
1042    pub fn covers(&self, rule: &EgressRule) -> bool {
1043        self.layers.iter().all(|layer| layer.rules.iter().any(|own| subsumes(own, rule)))
1044    }
1045
1046    /// Admits or refuses a tool call by its declaration; see [`ToolEgress`].
1047    ///
1048    /// # Errors
1049    ///
1050    /// Returns why the declaration is refused.
1051    pub fn admits_tool(&self, egress: &ToolEgress) -> Result<(), String> {
1052        match egress {
1053            ToolEgress::None | ToolEgress::Configured | ToolEgress::Enforced => Ok(()),
1054            ToolEgress::Undeclared => {
1055                Err("the run has an egress policy and the tool does not declare the network \
1056                 destinations it reaches (Tool::egress); declare them, or run it without an \
1057                 egress policy"
1058                    .to_string())
1059            }
1060            ToolEgress::Destinations(rules) => match rules.iter().find(|rule| !self.covers(rule)) {
1061                Some(rule) => Err(format!(
1062                    "the call reaches {rule}, which the run's egress policy ({self}) does not \
1063                     admit"
1064                )),
1065                None => Ok(()),
1066            },
1067        }
1068    }
1069}
1070
1071/// Whether `own` admits every destination `declared` names.
1072fn subsumes(own: &EgressRule, declared: &EgressRule) -> bool {
1073    let ports = |own: &Option<u16>, declared: &Option<u16>| match (own, declared) {
1074        (None, _) => true,
1075        (Some(own), Some(declared)) => own == declared,
1076        (Some(_), None) => false,
1077    };
1078    match (own, declared) {
1079        (
1080            EgressRule::Host { pattern: own_pattern, port: own_port },
1081            EgressRule::Host { pattern, port },
1082        ) => {
1083            let names = match (own_pattern, pattern) {
1084                (HostPattern::Any, _) => true,
1085                (HostPattern::Exact(own), HostPattern::Exact(name)) => own == name,
1086                (HostPattern::Subdomains(_), HostPattern::Exact(name)) => own_pattern.matches(name),
1087                (HostPattern::Subdomains(own), HostPattern::Subdomains(domain)) => {
1088                    domain == own || own_pattern.matches(domain)
1089                }
1090                (HostPattern::Exact(_), HostPattern::Any | HostPattern::Subdomains(_))
1091                | (HostPattern::Subdomains(_), HostPattern::Any) => false,
1092            };
1093            names && ports(own_port, port)
1094        }
1095        (EgressRule::Cidr { cidr: own, port: own_port }, EgressRule::Cidr { cidr, port }) => {
1096            own.prefix <= cidr.prefix && own.contains(cidr.network) && ports(own_port, port)
1097        }
1098        (EgressRule::Host { .. }, EgressRule::Cidr { .. })
1099        | (EgressRule::Cidr { .. }, EgressRule::Host { .. }) => false,
1100    }
1101}
1102
1103/// Resolves host names for an egress check, so tests and proxies can supply their own answers.
1104///
1105/// # Example
1106///
1107/// ```rust
1108/// use adk_core::egress::{HostResolver, StaticResolver};
1109///
1110/// # async fn example() -> std::io::Result<()> {
1111/// let resolver = StaticResolver::new().with_host("api.test", ["10.0.0.7".parse().unwrap()]);
1112/// let expected: std::net::IpAddr = "10.0.0.7".parse().unwrap();
1113/// assert_eq!(resolver.resolve("api.test").await?, vec![expected]);
1114/// # Ok(())
1115/// # }
1116/// ```
1117#[async_trait]
1118pub trait HostResolver: Send + Sync + fmt::Debug {
1119    /// Every address `host` resolves to.
1120    ///
1121    /// # Errors
1122    ///
1123    /// Returns the lookup failure.
1124    async fn resolve(&self, host: &str) -> std::io::Result<Vec<IpAddr>>;
1125}
1126
1127/// The operating system's resolver (feature `egress-dns`).
1128#[cfg(feature = "egress-dns")]
1129#[derive(Debug, Clone, Copy, Default)]
1130pub struct SystemResolver;
1131
1132#[cfg(feature = "egress-dns")]
1133#[async_trait]
1134impl HostResolver for SystemResolver {
1135    async fn resolve(&self, host: &str) -> std::io::Result<Vec<IpAddr>> {
1136        Ok(tokio::net::lookup_host((host, 0)).await?.map(|address| address.ip()).collect())
1137    }
1138}
1139
1140/// A fixed map from host names to addresses, for tests and closed deployments.
1141#[derive(Debug, Clone, Default)]
1142pub struct StaticResolver {
1143    hosts: HashMap<String, Vec<IpAddr>>,
1144}
1145
1146impl StaticResolver {
1147    /// An empty map; every lookup fails.
1148    pub fn new() -> Self {
1149        Self::default()
1150    }
1151
1152    /// Maps `host` to `addresses`.
1153    #[must_use]
1154    pub fn with_host(
1155        mut self,
1156        host: impl AsRef<str>,
1157        addresses: impl IntoIterator<Item = IpAddr>,
1158    ) -> Self {
1159        self.hosts.insert(normalize_host(host.as_ref()), addresses.into_iter().collect());
1160        self
1161    }
1162}
1163
1164#[async_trait]
1165impl HostResolver for StaticResolver {
1166    async fn resolve(&self, host: &str) -> std::io::Result<Vec<IpAddr>> {
1167        self.hosts.get(&normalize_host(host)).cloned().ok_or_else(|| {
1168            std::io::Error::new(std::io::ErrorKind::NotFound, format!("{host} has no address"))
1169        })
1170    }
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175    use super::*;
1176
1177    fn name(host: &str, port: u16) -> EgressTarget<'_> {
1178        EgressTarget::Name { host, port }
1179    }
1180
1181    fn literal(address: &str) -> EgressTarget<'static> {
1182        EgressTarget::Literal(address.parse().unwrap())
1183    }
1184
1185    #[test]
1186    fn rules_round_trip_through_text() {
1187        for text in [
1188            "*",
1189            "*:443",
1190            "api.example.com",
1191            "api.example.com:443",
1192            "*.example.com",
1193            "*.example.com:8443",
1194            "10.0.0.0/8",
1195            "10.0.0.5/32:5432",
1196            "fd00::/8",
1197            "[fd00::/8]:443",
1198            "[::1/128]:8080",
1199        ] {
1200            let rule: EgressRule = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
1201            assert_eq!(rule.to_string(), text);
1202            assert_eq!(rule.to_string().parse::<EgressRule>().unwrap(), rule);
1203        }
1204        assert_eq!("10.0.0.5:5432".parse::<EgressRule>().unwrap().to_string(), "10.0.0.5/32:5432");
1205        assert_eq!("[::1]:8080".parse::<EgressRule>().unwrap().to_string(), "[::1/128]:8080");
1206        assert_eq!(
1207            "API.Example.COM.".parse::<EgressRule>().unwrap().to_string(),
1208            "api.example.com"
1209        );
1210        assert_eq!("::ffff:10.0.0.0/104".parse::<EgressRule>().unwrap().to_string(), "10.0.0.0/8");
1211    }
1212
1213    #[test]
1214    fn malformed_rules_are_refused() {
1215        for text in [
1216            "",
1217            "https://api.example.com",
1218            "api.example.com:0",
1219            "api.example.com:70000",
1220            "api.example.com:x",
1221            "*example.com",
1222            "a.*.example.com",
1223            "exa mple.com",
1224            "example..com",
1225            "0x7f.1",
1226            "127.1",
1227            "10.0.0.1/8",
1228            "10.0.0.0/33",
1229            "[fd00::/8",
1230            "[fd00::/8]443",
1231            "[api.example.com]:443",
1232        ] {
1233            assert!(text.parse::<EgressRule>().is_err(), "{text} must not parse");
1234        }
1235    }
1236
1237    #[test]
1238    fn subdomain_wildcards_exclude_the_domain_and_lookalikes() {
1239        let policy = EgressPolicy::allowlist(["*.example.com"]).unwrap();
1240        assert!(policy.decide(&name("a.example.com", 443)).is_ok());
1241        assert!(policy.decide(&name("a.b.example.com", 443)).is_ok());
1242        assert!(policy.decide(&name("A.Example.Com.", 443)).is_ok());
1243        for host in ["example.com", "badexample.com", "example.com.evil.test"] {
1244            assert_eq!(
1245                policy.decide(&name(host, 443)),
1246                Err(EgressDenial::HostNotAllowed { host: host.to_string(), port: 443 })
1247            );
1248        }
1249    }
1250
1251    #[test]
1252    fn ports_restrict_host_and_cidr_rules() {
1253        let policy = EgressPolicy::allowlist(["api.example.com:443", "10.0.0.0/8:5432"]).unwrap();
1254        assert!(policy.decide(&name("api.example.com", 443)).is_ok());
1255        assert!(policy.decide(&name("api.example.com", 80)).is_err());
1256        assert!(policy.decide(&literal("10.1.2.3:5432")).is_ok());
1257        assert_eq!(
1258            policy.decide(&literal("10.1.2.3:22")),
1259            Err(EgressDenial::LiteralNotAllowed { address: "10.1.2.3:22".parse().unwrap() })
1260        );
1261    }
1262
1263    #[test]
1264    fn non_public_addresses_need_a_cidr_or_private_networks() {
1265        let address = |host, ip: &str| EgressTarget::Address { host, address: ip.parse().unwrap() };
1266        let listed = EgressPolicy::allowlist(["db.internal"]).unwrap();
1267        assert!(listed.decide(&address("db.internal", "93.184.216.34")).is_ok());
1268        assert_eq!(
1269            listed.decide(&address("db.internal", "10.0.0.5")),
1270            Err(EgressDenial::AddressNotAllowed {
1271                host: "db.internal".into(),
1272                address: "10.0.0.5".parse().unwrap(),
1273                class: AddressClass::Private,
1274            })
1275        );
1276        let ranged = listed.clone().allow("10.0.0.0/24".parse().unwrap());
1277        assert!(ranged.decide(&address("db.internal", "10.0.0.5")).is_ok());
1278        assert!(ranged.decide(&address("db.internal", "10.0.1.5")).is_err());
1279        let private = listed.with_private_networks();
1280        assert!(private.decide(&address("db.internal", "10.0.1.5")).is_ok());
1281        assert!(private.decide(&address("db.internal", "::1")).is_ok());
1282    }
1283
1284    #[test]
1285    fn metadata_is_refused_by_every_policy() {
1286        let policies = [
1287            EgressPolicy::allow_private_networks(),
1288            EgressPolicy::allowlist(["*", "169.254.0.0/16", "0.0.0.0/0", "::/0"])
1289                .unwrap()
1290                .with_private_networks(),
1291        ];
1292        for policy in policies {
1293            for ip in ["169.254.169.254", "168.63.129.16", "100.100.100.200", "fd00:ec2::254"] {
1294                let address: IpAddr = ip.parse().unwrap();
1295                assert!(matches!(
1296                    policy.decide(&EgressTarget::Literal(SocketAddr::new(address, 80))),
1297                    Err(EgressDenial::MetadataAddress { .. })
1298                ));
1299                assert!(matches!(
1300                    policy.decide(&EgressTarget::Address { host: "metadata.test", address }),
1301                    Err(EgressDenial::MetadataAddress { .. })
1302                ));
1303            }
1304            assert!(policy.check_url("http://[::ffff:169.254.169.254]/latest").is_err());
1305        }
1306    }
1307
1308    #[test]
1309    fn literals_need_a_cidr_unless_any_host_admits_them() {
1310        let listed = EgressPolicy::allowlist(["api.example.com"]).unwrap();
1311        assert_eq!(
1312            listed.decide(&literal("93.184.216.34:443")),
1313            Err(EgressDenial::LiteralNotAllowed { address: "93.184.216.34:443".parse().unwrap() })
1314        );
1315        let public = EgressPolicy::public_only();
1316        assert!(public.decide(&literal("93.184.216.34:443")).is_ok());
1317        assert!(matches!(
1318            public.decide(&literal("127.0.0.1:443")),
1319            Err(EgressDenial::AddressNotAllowed { class: AddressClass::Loopback, .. })
1320        ));
1321        // A literal written as a name is still checked as a literal.
1322        assert!(listed.decide(&name("[::1]", 443)).is_err());
1323        assert!(listed.decide(&name("10.0.0.1", 443)).is_err());
1324    }
1325
1326    #[test]
1327    fn localhost_names_are_checked_as_loopback() {
1328        let public = EgressPolicy::public_only();
1329        for host in ["localhost", "api.localhost", "LOCALHOST."] {
1330            assert!(matches!(
1331                public.decide(&name(host, 80)),
1332                Err(EgressDenial::AddressNotAllowed { class: AddressClass::Loopback, .. })
1333            ));
1334        }
1335        assert!(EgressPolicy::allow_private_networks().decide(&name("localhost", 80)).is_ok());
1336    }
1337
1338    #[test]
1339    fn numeric_host_names_are_ambiguous() {
1340        for host in ["0x7f.1", "127.1", "2130706433", "example.123", "a.0xff"] {
1341            assert_eq!(
1342                EgressPolicy::public_only().decide(&name(host, 443)),
1343                Err(EgressDenial::AmbiguousHost { host: host.to_string() })
1344            );
1345        }
1346        assert!(EgressPolicy::public_only().decide(&name("1password.com", 443)).is_ok());
1347    }
1348
1349    #[test]
1350    fn urls_are_checked_for_scheme_host_and_port() {
1351        let policy = EgressPolicy::default();
1352        for url in [
1353            "http://example.com/hook",
1354            "https://127.0.0.1/hook",
1355            "https://10.0.0.1/hook",
1356            "https://169.254.169.254/latest",
1357            "https://[::1]/hook",
1358            "https://[::ffff:192.168.1.1]/hook",
1359            "https://[64:ff9b::a00:1]/hook",
1360            "https://[2002:c0a8:101::1]/hook",
1361            "https://localhost/hook",
1362            "https://api.localhost/hook",
1363            "https://0x7f.1/hook",
1364            "https://198.18.0.1/hook",
1365            "https://240.0.0.1/hook",
1366            "https://168.63.129.16/machine",
1367            "ftp://example.com/hook",
1368            "not a url",
1369        ] {
1370            assert!(policy.check_url(url).is_err(), "{url}");
1371        }
1372        for url in [
1373            "https://example.com/hook",
1374            "https://93.184.216.34/hook",
1375            "https://[2606:4700::1111]/x",
1376        ] {
1377            assert!(policy.check_url(url).is_ok(), "{url}");
1378        }
1379        let http = EgressPolicy::allowlist(["api.example.com:8080"]).unwrap().with_plain_http();
1380        assert!(http.check_url("http://api.example.com:8080/").is_ok());
1381        assert!(http.check_url("http://api.example.com/").is_err());
1382    }
1383
1384    #[test]
1385    fn narrowing_keeps_switches_only_when_both_set_them() {
1386        let open = EgressPolicy::allow_private_networks();
1387        let strict = EgressPolicy::public_only();
1388        let narrowed = open.narrow(&strict);
1389        assert!(!narrowed.allows_plain_http());
1390        assert!(!narrowed.allows_private_networks());
1391        assert!(narrowed.check_url("http://example.com/").is_err());
1392        assert!(narrowed.check_url("https://10.0.0.1/").is_err());
1393        // A narrowed policy cannot be widened, not even past its own first layer.
1394        let rewidened = strict
1395            .narrow(&EgressPolicy::allowlist(["*.test"]).unwrap())
1396            .allow(EgressRule::host("b.test").unwrap())
1397            .allow(EgressRule::host("evil.example").unwrap())
1398            .with_private_networks();
1399        assert!(rewidened.is_narrowed());
1400        assert!(rewidened.check_url("https://b.test/").is_ok());
1401        assert!(rewidened.check_url("https://evil.example/").is_err());
1402        assert!(rewidened.check_url("https://10.0.0.1/").is_err());
1403        assert_eq!(open.narrow(&open).to_string(), open.to_string());
1404        assert_eq!(narrowed.to_string(), "* +private-networks +plain-http; narrowed by *");
1405    }
1406
1407    #[test]
1408    fn denials_are_found_through_error_chains() {
1409        #[derive(Debug, thiserror::Error)]
1410        #[error("request failed")]
1411        struct Wrapper(#[source] EgressDenial);
1412        let denial = EgressDenial::PlainHttp { host: "a.test".into() };
1413        let wrapped = Wrapper(denial.clone());
1414        assert_eq!(find_denial(&wrapped), Some(&denial));
1415        assert_eq!(denial.code(), "egress.plain_http");
1416        let io = std::io::Error::other("unrelated");
1417        assert_eq!(find_denial(&io), None);
1418    }
1419
1420    #[test]
1421    fn declarations_are_covered_rule_by_rule() {
1422        let policy =
1423            EgressPolicy::allowlist(["*.example.com:443", "api.github.com", "10.0.0.0/8:5432"])
1424                .unwrap();
1425        let rule = |text: &str| text.parse::<EgressRule>().unwrap();
1426        for covered in [
1427            "a.example.com:443",
1428            "*.b.example.com:443",
1429            "api.github.com:22",
1430            "api.github.com",
1431            "10.1.0.0/16:5432",
1432            "10.1.2.3:5432",
1433        ] {
1434            assert!(policy.covers(&rule(covered)), "{covered}");
1435        }
1436        for refused in [
1437            "example.com:443",
1438            "*.example.com",
1439            "a.example.com:80",
1440            "*",
1441            "github.com:443",
1442            "10.0.0.0/8",
1443            "11.0.0.1:5432",
1444            "*.github.com:443",
1445        ] {
1446            assert!(!policy.covers(&rule(refused)), "{refused}");
1447        }
1448        let narrowed = policy.narrow(&EgressPolicy::allowlist(["api.github.com:443"]).unwrap());
1449        assert!(narrowed.covers(&rule("api.github.com:443")));
1450        assert!(!narrowed.covers(&rule("api.github.com:22")));
1451    }
1452
1453    #[test]
1454    fn tool_declarations_are_admitted_by_kind() {
1455        let policy = EgressPolicy::allowlist(["docs.rs:443"]).unwrap();
1456        for admitted in [
1457            ToolEgress::None,
1458            ToolEgress::Configured,
1459            ToolEgress::Enforced,
1460            ToolEgress::for_urls(["https://docs.rs/adk"]),
1461        ] {
1462            assert!(policy.admits_tool(&admitted).is_ok(), "{admitted:?}");
1463        }
1464        for refused in [
1465            ToolEgress::Undeclared,
1466            ToolEgress::for_urls(["https://docs.rs/a", "https://crates.io/b"]),
1467            ToolEgress::for_urls(["http://docs.rs/"]),
1468            ToolEgress::for_urls(["not a url"]),
1469            ToolEgress::for_urls(["https://93.184.216.34/"]),
1470        ] {
1471            assert!(policy.admits_tool(&refused).is_err(), "{refused:?}");
1472        }
1473        assert_eq!(
1474            ToolEgress::for_urls(["https://0x7f.1/"]),
1475            ToolEgress::Destinations(vec!["127.0.0.1:443".parse().unwrap()])
1476        );
1477        assert_eq!(
1478            ToolEgress::for_urls(["https://127.1/"]),
1479            ToolEgress::Destinations(vec!["127.0.0.1:443".parse().unwrap()])
1480        );
1481    }
1482
1483    #[tokio::test]
1484    async fn static_resolver_answers_only_known_hosts() {
1485        let resolver = StaticResolver::new().with_host("API.test.", ["10.0.0.1".parse().unwrap()]);
1486        assert_eq!(
1487            resolver.resolve("api.test").await.unwrap(),
1488            vec!["10.0.0.1".parse::<IpAddr>().unwrap()]
1489        );
1490        assert_eq!(
1491            resolver.resolve("other.test").await.unwrap_err().kind(),
1492            std::io::ErrorKind::NotFound
1493        );
1494    }
1495}