Skip to main content

graphrt_http/
policy.rs

1//! Egress policy and SSRF classification.
2
3use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
4use std::time::Duration;
5
6use url::{Host, Url};
7
8/// Rules for outbound HTTP requests made by workflow nodes.
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct EgressPolicy {
11    /// Allow loopback, private, link-local and other non-public addresses.
12    /// Off by default: workflows are untrusted input.
13    pub allow_private: bool,
14    /// If non-empty, only these hosts may be contacted. Entries match the host exactly,
15    /// or any subdomain when written as `*.example.com` or `.example.com`.
16    pub allowed_hosts: Vec<String>,
17    /// Hosts that may never be contacted (same matching rules). Checked before `allowed_hosts`.
18    pub denied_hosts: Vec<String>,
19    /// Permitted URL schemes.
20    pub allowed_schemes: Vec<String>,
21    /// Maximum redirects followed (each hop is re-validated). 0 disables redirects.
22    pub max_redirects: usize,
23    /// Maximum response body size in bytes.
24    pub max_response_bytes: usize,
25    pub connect_timeout: Duration,
26    /// Maximum idle time between reads.
27    pub read_timeout: Duration,
28    /// Default total request timeout when a node does not configure one.
29    pub total_timeout: Duration,
30    /// Optional egress proxy URL. Environment proxy variables are always ignored.
31    pub proxy: Option<String>,
32}
33
34impl Default for EgressPolicy {
35    fn default() -> Self {
36        Self {
37            allow_private: false,
38            allowed_hosts: Vec::new(),
39            denied_hosts: Vec::new(),
40            allowed_schemes: vec!["http".to_owned(), "https".to_owned()],
41            max_redirects: 5,
42            max_response_bytes: 10 * 1024 * 1024,
43            connect_timeout: Duration::from_secs(10),
44            read_timeout: Duration::from_secs(60),
45            total_timeout: Duration::from_secs(300),
46            proxy: None,
47        }
48    }
49}
50
51/// Reason a destination was refused.
52#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
53#[non_exhaustive]
54pub enum EgressError {
55    #[error("invalid URL `{0}`")]
56    InvalidUrl(String),
57    #[error("URL scheme `{0}` is not allowed")]
58    Scheme(String),
59    #[error("URL has no host")]
60    NoHost,
61    #[error("host `{0}` is not allowed by the egress policy")]
62    HostDenied(String),
63    #[error("address {0} is not a public address (private/loopback/link-local/reserved)")]
64    BlockedAddress(IpAddr),
65}
66
67impl EgressPolicy {
68    /// A policy for trusted, operator-configured endpoints (e.g. a code sandbox):
69    /// private addresses allowed, everything else default.
70    pub fn trusted() -> Self {
71        Self { allow_private: true, ..Self::default() }
72    }
73
74    /// Validate a URL before sending a request or following a redirect.
75    pub fn check_url(&self, url: &Url) -> Result<(), EgressError> {
76        let scheme = url.scheme();
77        if !self.allowed_schemes.iter().any(|s| s.eq_ignore_ascii_case(scheme)) {
78            return Err(EgressError::Scheme(scheme.to_owned()));
79        }
80        let host = url.host().ok_or(EgressError::NoHost)?;
81        let host_text = match &host {
82            Host::Domain(d) => d.trim_end_matches('.').to_ascii_lowercase(),
83            Host::Ipv4(ip) => ip.to_string(),
84            Host::Ipv6(ip) => ip.to_string(),
85        };
86        self.check_host_name(&host_text)?;
87        match host {
88            Host::Ipv4(ip) => self.check_ip(IpAddr::V4(ip)),
89            Host::Ipv6(ip) => self.check_ip(IpAddr::V6(ip)),
90            // Domain names are checked after resolution by the guarded resolver.
91            Host::Domain(_) => Ok(()),
92        }
93    }
94
95    /// Check a host name against the allow / deny lists.
96    pub fn check_host_name(&self, host: &str) -> Result<(), EgressError> {
97        let host = host.trim_end_matches('.').to_ascii_lowercase();
98        if self.denied_hosts.iter().any(|p| host_matches(p, &host)) {
99            return Err(EgressError::HostDenied(host));
100        }
101        if !self.allowed_hosts.is_empty() && !self.allowed_hosts.iter().any(|p| host_matches(p, &host)) {
102            return Err(EgressError::HostDenied(host));
103        }
104        Ok(())
105    }
106
107    /// Check a resolved or literal IP address.
108    pub fn check_ip(&self, ip: IpAddr) -> Result<(), EgressError> {
109        if self.allow_private || is_public(ip) { Ok(()) } else { Err(EgressError::BlockedAddress(ip)) }
110    }
111}
112
113/// `pattern` matches `host` exactly, or as a suffix when written `*.domain` / `.domain`.
114fn host_matches(pattern: &str, host: &str) -> bool {
115    let pattern = pattern.trim().trim_end_matches('.').to_ascii_lowercase();
116    if let Some(suffix) = pattern.strip_prefix("*.").or_else(|| pattern.strip_prefix('.')) {
117        host == suffix || host.ends_with(&format!(".{suffix}"))
118    } else {
119        host == pattern
120    }
121}
122
123/// Whether an address is globally routable (safe to contact from a multi-tenant runtime).
124pub fn is_public(ip: IpAddr) -> bool {
125    match ip {
126        IpAddr::V4(v4) => is_public_v4(v4),
127        IpAddr::V6(v6) => is_public_v6(v6),
128    }
129}
130
131fn is_public_v4(ip: Ipv4Addr) -> bool {
132    let [a, b, c, _] = ip.octets();
133    let blocked = ip.is_unspecified()          // 0.0.0.0
134        || a == 0                              // 0.0.0.0/8 "this network"
135        || ip.is_loopback()                    // 127.0.0.0/8
136        || ip.is_private()                     // 10/8, 172.16/12, 192.168/16
137        || ip.is_link_local()                  // 169.254/16 (cloud metadata)
138        || (a == 100 && (64..=127).contains(&b)) // 100.64/10 carrier-grade NAT
139        || (a == 192 && b == 0 && c == 0)      // 192.0.0.0/24 IETF protocol assignments
140        || (a == 192 && b == 0 && c == 2)      // 192.0.2.0/24 TEST-NET-1
141        || (a == 198 && b == 51 && c == 100)   // 198.51.100.0/24 TEST-NET-2
142        || (a == 203 && b == 0 && c == 113)    // 203.0.113.0/24 TEST-NET-3
143        || (a == 198 && (b == 18 || b == 19))  // 198.18/15 benchmarking
144        || (a == 192 && b == 88 && c == 99)    // 6to4 relay anycast
145        || ip == Ipv4Addr::new(168, 63, 129, 16) // Azure WireServer (platform agent endpoint)
146        || ip.is_multicast()                   // 224/4
147        || a >= 240; // 240/4 reserved, incl. 255.255.255.255 broadcast
148    !blocked
149}
150
151fn is_public_v6(ip: Ipv6Addr) -> bool {
152    // Addresses embedding an IPv4 address are judged by that address.
153    if let Some(v4) = embedded_v4(ip) {
154        return is_public_v4(v4);
155    }
156    let segments = ip.segments();
157    let first = segments.first().copied().unwrap_or(0);
158    let blocked = ip.is_unspecified()             // ::
159        || ip.is_loopback()                       // ::1
160        || ip.is_multicast()                      // ff00::/8
161        || (first & 0xfe00) == 0xfc00             // fc00::/7 unique local
162        || (first & 0xffc0) == 0xfe80             // fe80::/10 link local
163        || (first & 0xffc0) == 0xfec0             // fec0::/10 site local (deprecated)
164        || first == 0x2001 && segments.get(1) == Some(&0x0db8) // 2001:db8::/32 documentation
165        || first == 0x0100 && segments.get(1..4) == Some(&[0, 0, 0]) // 100::/64 discard
166        || first == 0x0064 && segments.get(1..3) == Some(&[0xff9b, 0x0001]) // 64:ff9b:1::/48 local-use NAT64
167        || first == 0x2001 && segments.get(1) == Some(&0) // 2001::/32 Teredo (tunnels to arbitrary IPv4)
168        || segments.get(..6) == Some(&[0, 0, 0, 0, 0, 0]); // ::/96 deprecated IPv4-compatible
169    !blocked
170}
171
172/// IPv4 address carried inside an IPv6 address: IPv4-mapped (`::ffff:a.b.c.d`),
173/// IPv4-translated (`::ffff:0:a.b.c.d`), NAT64 (`64:ff9b::/96`), 6to4 (`2002::/16`)
174/// and IPv4-compatible (`::a.b.c.d`).
175fn embedded_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
176    if let Some(v4) = ip.to_ipv4_mapped() {
177        return Some(v4);
178    }
179    let s = ip.segments();
180    let from_pair = |hi: u16, lo: u16| {
181        let [a, b] = hi.to_be_bytes();
182        let [c, d] = lo.to_be_bytes();
183        Ipv4Addr::new(a, b, c, d)
184    };
185    match s {
186        [0x0064, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(from_pair(hi, lo)),
187        [0, 0, 0, 0, 0xffff, 0, hi, lo] => Some(from_pair(hi, lo)),
188        [0x2002, hi, lo, ..] => Some(from_pair(hi, lo)),
189        [0, 0, 0, 0, 0, 0, hi, lo] if (hi, lo) != (0, 0) && (hi, lo) != (0, 1) => Some(from_pair(hi, lo)),
190        _ => None,
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    fn ip(s: &str) -> IpAddr {
199        s.parse().unwrap()
200    }
201
202    #[test]
203    fn classification_table() {
204        let blocked = [
205            "0.0.0.0",
206            "0.1.2.3",
207            "127.0.0.1",
208            "127.255.255.254",
209            "10.0.0.1",
210            "172.16.0.1",
211            "172.31.255.255",
212            "192.168.1.1",
213            "169.254.169.254",
214            "169.254.0.1",
215            "100.64.0.1",
216            "100.127.255.255",
217            "192.0.0.8",
218            "192.0.2.1",
219            "198.51.100.7",
220            "203.0.113.9",
221            "198.18.0.1",
222            "198.19.255.255",
223            "224.0.0.1",
224            "239.255.255.250",
225            "240.0.0.1",
226            "255.255.255.255",
227            "::",
228            "::1",
229            "::ffff:127.0.0.1",
230            "::ffff:0:7f00:1",
231            "::ffff:0:a9fe:a9fe",
232            "64:ff9b:1::a00:1",
233            "2001:0:4136:e378:8000:63bf:3fff:fdd2",
234            "168.63.129.16",
235            "::ffff:10.0.0.1",
236            "::ffff:169.254.169.254",
237            "::127.0.0.1",
238            "64:ff9b::7f00:1",
239            "64:ff9b::a9fe:a9fe",
240            "2002:7f00:1::",
241            "2002:c0a8:101::1",
242            "fc00::1",
243            "fd00::1",
244            "fd00:ec2::254",
245            "fe80::1",
246            "febf::1",
247            "fec0::1",
248            "ff02::1",
249            "2001:db8::1",
250            "100::1",
251        ];
252        for s in blocked {
253            assert!(!is_public(ip(s)), "{s} should be blocked");
254        }
255        let public = [
256            "1.1.1.1",
257            "8.8.8.8",
258            "93.184.216.34",
259            "100.63.255.255",
260            "100.128.0.1",
261            "172.15.255.255",
262            "172.32.0.1",
263            "192.169.0.1",
264            "169.253.0.1",
265            "2606:4700:4700::1111",
266            "2001:4860:4860::8888",
267            "::ffff:8.8.8.8",
268            "64:ff9b::808:808",
269            "2002:808:808::",
270        ];
271        for s in public {
272            assert!(is_public(ip(s)), "{s} should be public");
273        }
274    }
275
276    #[test]
277    fn literal_urls_are_checked() {
278        let p = EgressPolicy::default();
279        let check = |u: &str| p.check_url(&Url::parse(u).unwrap());
280        assert!(check("http://127.0.0.1/").is_err());
281        assert!(check("http://[::1]:8080/").is_err());
282        assert!(check("http://[::ffff:7f00:1]/").is_err());
283        // Alternative IPv4 notations are normalized by the URL parser.
284        assert!(check("http://2130706433/").is_err());
285        assert!(check("http://0x7f.1/").is_err());
286        assert!(check("http://0177.0.0.1/").is_err());
287        assert!(check("http://169.254.169.254/latest/meta-data").is_err());
288        assert!(check("ftp://example.com/").is_err());
289        assert!(check("file:///etc/passwd").is_err());
290        assert!(check("https://example.com/").is_ok());
291        assert!(check("http://8.8.8.8/").is_ok());
292        let open = EgressPolicy::trusted();
293        assert!(open.check_url(&Url::parse("http://127.0.0.1/").unwrap()).is_ok());
294    }
295
296    #[test]
297    fn host_lists() {
298        let p = EgressPolicy {
299            allowed_hosts: vec!["*.example.com".into(), "api.other.org".into()],
300            denied_hosts: vec!["evil.example.com".into()],
301            ..EgressPolicy::default()
302        };
303        assert!(p.check_host_name("example.com").is_ok());
304        assert!(p.check_host_name("a.b.example.com").is_ok());
305        assert!(p.check_host_name("API.other.org.").is_ok());
306        assert!(p.check_host_name("evil.example.com").is_err());
307        assert!(p.check_host_name("other.org").is_err());
308        assert!(p.check_host_name("notexample.com").is_err());
309    }
310}