1mod 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub enum HostPattern {
99 Any,
101 Exact(String),
103 Subdomains(String),
105}
106
107impl HostPattern {
108 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
185pub struct IpCidr {
186 network: IpAddr,
187 prefix: u8,
188}
189
190impl IpCidr {
191 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 pub fn network(&self) -> IpAddr {
225 self.network
226 }
227
228 pub fn prefix(&self) -> u8 {
230 self.prefix
231 }
232
233 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
308pub enum EgressRule {
309 Host {
311 pattern: HostPattern,
313 port: Option<u16>,
315 },
316 Cidr {
318 cidr: IpCidr,
320 port: Option<u16>,
322 },
323}
324
325impl EgressRule {
326 pub fn any_host() -> Self {
328 Self::Host { pattern: HostPattern::Any, port: None }
329 }
330
331 pub fn host(host: &str) -> Result<Self, EgressRuleError> {
337 Ok(Self::Host { pattern: host.parse()?, port: None })
338 }
339
340 pub fn cidr(cidr: IpCidr) -> Self {
342 Self::Cidr { cidr, port: None }
343 }
344
345 #[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 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#[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 pub rule: String,
447 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
462pub enum EgressTarget<'a> {
463 Name {
466 host: &'a str,
468 port: u16,
470 },
471 Address {
473 host: &'a str,
475 address: IpAddr,
477 },
478 Literal(SocketAddr),
480}
481
482#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
487pub enum EgressDenial {
488 #[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 host: String,
496 port: u16,
498 },
499 #[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 address: SocketAddr,
507 },
508 #[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 host: String,
516 address: IpAddr,
518 class: AddressClass,
520 },
521 #[error(
523 "egress to {host} is refused: {address} is a cloud metadata or credential endpoint, \
524 which is always blocked"
525 )]
526 MetadataAddress {
527 host: String,
529 address: IpAddr,
531 },
532 #[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 host: String,
540 },
541 #[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 host: String,
549 },
550 #[error("egress over the URL scheme '{scheme}' is refused; use https")]
552 Scheme {
553 scheme: String,
555 },
556 #[error("egress URL is invalid: {reason}")]
558 InvalidUrl {
559 reason: String,
561 },
562}
563
564impl EgressDenial {
565 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
580pub 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#[derive(Debug, Clone, PartialEq, Eq)]
693pub struct EgressPolicy {
694 layers: Vec<RuleSet>,
697 narrowed: bool,
700}
701
702impl Default for EgressPolicy {
703 fn default() -> Self {
704 Self::public_only()
705 }
706}
707
708impl EgressPolicy {
709 pub fn deny_all() -> Self {
711 Self { layers: vec![RuleSet::default()], narrowed: false }
712 }
713
714 pub fn public_only() -> Self {
716 Self::deny_all().allow(EgressRule::any_host())
717 }
718
719 pub fn allow_private_networks() -> Self {
724 Self::public_only().with_private_networks().with_plain_http()
725 }
726
727 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 #[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 #[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 #[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 pub fn is_narrowed(&self) -> bool {
785 self.narrowed
786 }
787
788 #[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 pub fn allows_plain_http(&self) -> bool {
817 self.layers.iter().all(|layer| layer.plain_http)
818 }
819
820 pub fn allows_private_networks(&self) -> bool {
822 self.layers.iter().all(|layer| layer.private_networks)
823 }
824
825 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 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 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 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
936fn 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
975pub enum ToolEgress {
976 #[default]
978 Undeclared,
979 None,
981 Configured,
983 Enforced,
986 Destinations(Vec<EgressRule>),
988}
989
990impl ToolEgress {
991 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 pub fn covers(&self, rule: &EgressRule) -> bool {
1043 self.layers.iter().all(|layer| layer.rules.iter().any(|own| subsumes(own, rule)))
1044 }
1045
1046 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
1071fn 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#[async_trait]
1118pub trait HostResolver: Send + Sync + fmt::Debug {
1119 async fn resolve(&self, host: &str) -> std::io::Result<Vec<IpAddr>>;
1125}
1126
1127#[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#[derive(Debug, Clone, Default)]
1142pub struct StaticResolver {
1143 hosts: HashMap<String, Vec<IpAddr>>,
1144}
1145
1146impl StaticResolver {
1147 pub fn new() -> Self {
1149 Self::default()
1150 }
1151
1152 #[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 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 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}