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.is_multicast()                   // 224/4
146        || a >= 240; // 240/4 reserved, incl. 255.255.255.255 broadcast
147    !blocked
148}
149
150fn is_public_v6(ip: Ipv6Addr) -> bool {
151    // Addresses embedding an IPv4 address are judged by that address.
152    if let Some(v4) = embedded_v4(ip) {
153        return is_public_v4(v4);
154    }
155    let segments = ip.segments();
156    let first = segments.first().copied().unwrap_or(0);
157    let blocked = ip.is_unspecified()             // ::
158        || ip.is_loopback()                       // ::1
159        || ip.is_multicast()                      // ff00::/8
160        || (first & 0xfe00) == 0xfc00             // fc00::/7 unique local
161        || (first & 0xffc0) == 0xfe80             // fe80::/10 link local
162        || (first & 0xffc0) == 0xfec0             // fec0::/10 site local (deprecated)
163        || first == 0x2001 && segments.get(1) == Some(&0x0db8) // 2001:db8::/32 documentation
164        || first == 0x0100 && segments.get(1..4) == Some(&[0, 0, 0]) // 100::/64 discard
165        || segments.get(..6) == Some(&[0, 0, 0, 0, 0, 0]); // ::/96 deprecated IPv4-compatible
166    !blocked
167}
168
169/// IPv4 address carried inside an IPv6 address: IPv4-mapped (`::ffff:a.b.c.d`),
170/// NAT64 (`64:ff9b::/96`), 6to4 (`2002::/16`) and IPv4-compatible (`::a.b.c.d`).
171fn embedded_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
172    if let Some(v4) = ip.to_ipv4_mapped() {
173        return Some(v4);
174    }
175    let s = ip.segments();
176    let from_pair = |hi: u16, lo: u16| {
177        let [a, b] = hi.to_be_bytes();
178        let [c, d] = lo.to_be_bytes();
179        Ipv4Addr::new(a, b, c, d)
180    };
181    match s {
182        [0x0064, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(from_pair(hi, lo)),
183        [0x2002, hi, lo, ..] => Some(from_pair(hi, lo)),
184        [0, 0, 0, 0, 0, 0, hi, lo] if (hi, lo) != (0, 0) && (hi, lo) != (0, 1) => Some(from_pair(hi, lo)),
185        _ => None,
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    fn ip(s: &str) -> IpAddr {
194        s.parse().unwrap()
195    }
196
197    #[test]
198    fn classification_table() {
199        let blocked = [
200            "0.0.0.0",
201            "0.1.2.3",
202            "127.0.0.1",
203            "127.255.255.254",
204            "10.0.0.1",
205            "172.16.0.1",
206            "172.31.255.255",
207            "192.168.1.1",
208            "169.254.169.254",
209            "169.254.0.1",
210            "100.64.0.1",
211            "100.127.255.255",
212            "192.0.0.8",
213            "192.0.2.1",
214            "198.51.100.7",
215            "203.0.113.9",
216            "198.18.0.1",
217            "198.19.255.255",
218            "224.0.0.1",
219            "239.255.255.250",
220            "240.0.0.1",
221            "255.255.255.255",
222            "::",
223            "::1",
224            "::ffff:127.0.0.1",
225            "::ffff:10.0.0.1",
226            "::ffff:169.254.169.254",
227            "::127.0.0.1",
228            "64:ff9b::7f00:1",
229            "64:ff9b::a9fe:a9fe",
230            "2002:7f00:1::",
231            "2002:c0a8:101::1",
232            "fc00::1",
233            "fd00::1",
234            "fd00:ec2::254",
235            "fe80::1",
236            "febf::1",
237            "fec0::1",
238            "ff02::1",
239            "2001:db8::1",
240            "100::1",
241        ];
242        for s in blocked {
243            assert!(!is_public(ip(s)), "{s} should be blocked");
244        }
245        let public = [
246            "1.1.1.1",
247            "8.8.8.8",
248            "93.184.216.34",
249            "100.63.255.255",
250            "100.128.0.1",
251            "172.15.255.255",
252            "172.32.0.1",
253            "192.169.0.1",
254            "169.253.0.1",
255            "2606:4700:4700::1111",
256            "2001:4860:4860::8888",
257            "::ffff:8.8.8.8",
258            "64:ff9b::808:808",
259            "2002:808:808::",
260        ];
261        for s in public {
262            assert!(is_public(ip(s)), "{s} should be public");
263        }
264    }
265
266    #[test]
267    fn literal_urls_are_checked() {
268        let p = EgressPolicy::default();
269        let check = |u: &str| p.check_url(&Url::parse(u).unwrap());
270        assert!(check("http://127.0.0.1/").is_err());
271        assert!(check("http://[::1]:8080/").is_err());
272        assert!(check("http://[::ffff:7f00:1]/").is_err());
273        // Alternative IPv4 notations are normalized by the URL parser.
274        assert!(check("http://2130706433/").is_err());
275        assert!(check("http://0x7f.1/").is_err());
276        assert!(check("http://0177.0.0.1/").is_err());
277        assert!(check("http://169.254.169.254/latest/meta-data").is_err());
278        assert!(check("ftp://example.com/").is_err());
279        assert!(check("file:///etc/passwd").is_err());
280        assert!(check("https://example.com/").is_ok());
281        assert!(check("http://8.8.8.8/").is_ok());
282        let open = EgressPolicy::trusted();
283        assert!(open.check_url(&Url::parse("http://127.0.0.1/").unwrap()).is_ok());
284    }
285
286    #[test]
287    fn host_lists() {
288        let p = EgressPolicy {
289            allowed_hosts: vec!["*.example.com".into(), "api.other.org".into()],
290            denied_hosts: vec!["evil.example.com".into()],
291            ..EgressPolicy::default()
292        };
293        assert!(p.check_host_name("example.com").is_ok());
294        assert!(p.check_host_name("a.b.example.com").is_ok());
295        assert!(p.check_host_name("API.other.org.").is_ok());
296        assert!(p.check_host_name("evil.example.com").is_err());
297        assert!(p.check_host_name("other.org").is_err());
298        assert!(p.check_host_name("notexample.com").is_err());
299    }
300}