Skip to main content

alien_core/resources/
sandbox_policy.rs

1//! Runtime sandbox destination policies and public-address validation.
2
3use sha2::{Digest, Sha256};
4use std::net::Ipv4Addr;
5
6use alien_error::{AlienError, Context, IntoAlienError};
7use ipnet::Ipv4Net;
8use serde::{Deserialize, Deserializer, Serialize};
9#[cfg(feature = "openapi")]
10use utoipa::openapi::schema::{ArrayBuilder, ObjectBuilder, OneOfBuilder, Type};
11
12use crate::error::{ErrorData, Result};
13
14/// Per-sandbox outbound policy enforced by the gateway.
15///
16/// Mail ports 25, 465 and 587 require an explicit port in an allowlist target,
17/// such as `smtp.example.com:587`; `internet` and portless targets exclude them.
18/// This protects the deployment's shared outbound IP from mail abuse and blocklisting,
19/// which could disrupt every tenant's access through that IP.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21#[serde(rename_all = "camelCase")]
22pub enum EgressPolicy {
23    /// Public internet access except mail ports 25, 465 and 587.
24    /// Private and link-local destinations remain forbidden.
25    Internet,
26    /// Explicit destinations; unspecified ports exclude 25, 465 and 587.
27    /// Wildcards include the apex. An explicit port can allow a mail destination.
28    /// `link:<resource-id>` names a service the stack links to the sandbox; nothing else
29    /// reaches a link, so `allow: []` refuses links too.
30    #[serde(untagged)]
31    Allow {
32        /// Hostnames, wildcard hostnames, IPv4 literals, IPv4 CIDRs (optionally with a port),
33        /// or `link:<resource-id>`.
34        allow: Vec<String>,
35    },
36}
37
38// Utoipa does not support serde's per-variant `untagged`, so describe the wire union explicitly.
39#[cfg(feature = "openapi")]
40impl utoipa::PartialSchema for EgressPolicy {
41    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
42        OneOfBuilder::new()
43            .description(Some("Per-sandbox outbound policy. Mail ports 25, 465 and 587 require an explicit allowlist port, such as smtp.example.com:587; internet and portless targets exclude them. This protects the deployment's shared outbound IP from mail abuse and blocklisting that could disrupt every tenant."))
44            .item(
45                ObjectBuilder::new()
46                    .schema_type(Type::String)
47                    .enum_values(Some(["internet"])),
48            )
49            .item(
50                ObjectBuilder::new()
51                    .property(
52                        "allow",
53                        ArrayBuilder::new()
54                            .items(ObjectBuilder::new().schema_type(Type::String))
55                            .min_items(Some(0))
56                            .max_items(Some(4096)),
57                    )
58                    .required("allow")
59                    .additional_properties(Some(
60                        utoipa::openapi::schema::AdditionalProperties::FreeForm(false),
61                    )),
62            )
63            .into()
64    }
65}
66
67#[cfg(feature = "openapi")]
68impl utoipa::ToSchema for EgressPolicy {}
69
70impl<'de> Deserialize<'de> for EgressPolicy {
71    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
72        #[derive(Deserialize)]
73        #[serde(rename_all = "camelCase")]
74        enum Mode {
75            Internet,
76        }
77        #[derive(Deserialize)]
78        #[serde(deny_unknown_fields)]
79        struct Allow {
80            allow: Vec<String>,
81        }
82        #[derive(Deserialize)]
83        #[serde(untagged)]
84        enum Input {
85            Mode(Mode),
86            Allow(Allow),
87        }
88        Ok(match Input::deserialize(deserializer)? {
89            Input::Mode(Mode::Internet) => Self::Internet,
90            Input::Allow(Allow { allow }) => Self::Allow { allow },
91        })
92    }
93}
94
95impl EgressPolicy {
96    /// Validates every target before a deployment or runtime request can take effect.
97    pub fn validate(&self) -> Result<()> {
98        self.targets().map(|_| ())
99    }
100
101    /// Returns a validated policy with ASCII, lowercase names and canonical IP networks.
102    pub fn normalized(&self) -> Result<Self> {
103        match self {
104            Self::Allow { .. } => Ok(Self::Allow {
105                allow: self.targets()?.iter().map(Target::canonical).collect(),
106            }),
107            _ => Ok(self.clone()),
108        }
109    }
110
111    /// Canonical JSON used to authenticate gateway policy writes: normalized, sorted, no whitespace.
112    /// Duplicate entries remain present; sorting makes input order irrelevant to the digest.
113    pub fn canonical_json(&self) -> Result<Vec<u8>> {
114        let mut policy = self.normalized()?;
115        if let Self::Allow { allow } = &mut policy {
116            allow.sort_unstable();
117        }
118        serde_json::to_vec(&policy)
119            .into_alien_error()
120            .context(ErrorData::SandboxEgressInvalid {
121                target: "policy".to_string(),
122                reason: "could not encode canonical policy".to_string(),
123            })
124    }
125
126    /// SHA-256 digest authenticating the policy body in an admin JWS.
127    pub fn policy_digest(&self) -> Result<String> {
128        Ok(format!(
129            "sha256:{:x}",
130            Sha256::digest(self.canonical_json()?)
131        ))
132    }
133
134    /// Whether this policy lets the sandbox reach the service its stack links as `resource_id`.
135    ///
136    /// The stack's links are the ceiling; this only narrows them. `internet` keeps every
137    /// declared link, an allowlist keeps the links it names as `link:<resource-id>`, and an
138    /// empty allowlist keeps none. A name the stack does not link matches nothing here, and the
139    /// gateway answers only for declared links.
140    pub fn allows_link(&self, resource_id: &str) -> bool {
141        match self {
142            Self::Internet => true,
143            Self::Allow { allow } => allow.iter().any(|entry| {
144                Target::parse(entry)
145                    .is_ok_and(|target| matches!(&target.host, Host::Link(id) if id == resource_id))
146            }),
147        }
148    }
149
150    /// Whether this policy has a `link:<resource-id>` entry, which releases before links cannot
151    /// read.
152    pub fn names_links(&self) -> bool {
153        match self {
154            Self::Internet => false,
155            Self::Allow { allow } => allow
156                .iter()
157                .any(|entry| entry.starts_with(LINK_TARGET_PREFIX)),
158        }
159    }
160
161    /// Whether a concrete public destination and port match this policy.
162    pub fn allows(&self, host: &str, port: u16) -> Result<bool> {
163        let destination = format!("{host}:{port}");
164        let target = Target::parse(&destination)?;
165        if matches!(target.host, Host::Link(_)) {
166            return Err(invalid(&destination, "a link is not a destination"));
167        }
168        // Sandboxes share one outbound IP: unsolicited mail can get that IP blocklisted
169        // for every tenant. Explicit destination:port grants retain legitimate mail use.
170        let mail = matches!(port, 25 | 465 | 587);
171        Ok((!mail && matches!(self, Self::Internet))
172            || self
173                .targets()?
174                .iter()
175                .any(|entry| (!mail || entry.port == Some(port)) && entry.contains(&target)))
176    }
177
178    fn targets(&self) -> Result<Vec<Target>> {
179        let Self::Allow { allow } = self else {
180            return Ok(Vec::new());
181        };
182        if allow.len() > 4096 {
183            return Err(AlienError::new(ErrorData::SandboxEgressPolicyTooLarge {
184                limit: "4096 targets".to_string(),
185            }));
186        }
187        let targets = allow
188            .iter()
189            .map(|target| Target::parse(target))
190            .collect::<Result<Vec<_>>>()?;
191        // Valid targets are ASCII without JSON escape characters. Include object/array syntax,
192        // two quotes per target and commas to measure the exact canonical JSON byte length.
193        let canonical_bytes = 12 - usize::from(!targets.is_empty())
194            + targets
195                .iter()
196                .map(|target| target.canonical().len() + 3)
197                .sum::<usize>();
198        if canonical_bytes > 256 * 1024 {
199            return Err(AlienError::new(ErrorData::SandboxEgressPolicyTooLarge {
200                limit: "256 KiB of canonical JSON".to_string(),
201            }));
202        }
203        Ok(targets)
204    }
205}
206
207#[derive(Debug)]
208struct Target {
209    host: Host,
210    port: Option<u16>,
211}
212
213#[derive(Debug)]
214enum Host {
215    Name {
216        name: String,
217        wildcard: bool,
218    },
219    Network(Ipv4Net),
220    /// A service the stack links to the sandbox, by resource id. It never matches a host or
221    /// an address: only the gateway's declared links resolve it.
222    Link(String),
223}
224
225/// Prefix of a policy entry naming a linked service rather than a destination.
226pub const LINK_TARGET_PREFIX: &str = "link:";
227
228fn invalid(target: &str, reason: &str) -> AlienError<ErrorData> {
229    AlienError::new(ErrorData::SandboxEgressInvalid {
230        target: target.to_string(),
231        reason: reason.to_string(),
232    })
233}
234
235impl Target {
236    fn parse(target: &str) -> Result<Self> {
237        if let Some(id) = target.strip_prefix(LINK_TARGET_PREFIX) {
238            // The ports are the link's declared ports; a policy cannot name others.
239            crate::stack_authoring::validate_resource_id(id).map_err(|reason| {
240                invalid(
241                    target,
242                    &format!("expected link:<resource-id> with no port; the resource id {reason}"),
243                )
244            })?;
245            return Ok(Self {
246                host: Host::Link(id.to_string()),
247                port: None,
248            });
249        }
250        let (host, port) = match target.rsplit_once(':') {
251            Some((host, port)) => {
252                if port.is_empty() || !port.bytes().all(|c| c.is_ascii_digit()) {
253                    return Err(invalid(
254                        target,
255                        "port must be an integer between 1 and 65535",
256                    ));
257                }
258                let port: u16 =
259                    port.parse()
260                        .into_alien_error()
261                        .context(ErrorData::SandboxEgressInvalid {
262                            target: target.to_string(),
263                            reason: "port must be between 1 and 65535".to_string(),
264                        })?;
265                if port == 0 {
266                    return Err(invalid(target, "port must be between 1 and 65535"));
267                }
268                (host, Some(port))
269            }
270            None => (target, None),
271        };
272        let host = host.strip_suffix('.').unwrap_or(host);
273        let network = if host.contains('/') {
274            Some(
275                host.parse::<Ipv4Net>()
276                    .into_alien_error()
277                    .context(ErrorData::SandboxEgressInvalid {
278                        target: target.to_string(),
279                        reason: "expected an IPv4 CIDR".to_string(),
280                    })?
281                    .trunc(),
282            )
283        } else {
284            host.parse::<Ipv4Addr>().ok().map(Ipv4Net::from)
285        };
286        if let Some(network) = network {
287            // Test intersection, not just the first address: a broad CIDR can include private IPs.
288            if DENIED_RANGES.iter().any(|&(address, prefix)| {
289                let denied = Ipv4Net::new_assert(Ipv4Addr::from(address), prefix);
290                denied.contains(&network) || network.contains(&denied)
291            }) {
292                return Err(invalid(
293                    target,
294                    "private, link-local and special-use IPv4 ranges are forbidden",
295                ));
296            }
297            return Ok(Self {
298                host: Host::Network(network),
299                port,
300            });
301        }
302        let (name, wildcard) = match host.strip_prefix("*.") {
303            Some(name) => (name, true),
304            None => (host, false),
305        };
306        let name = idna::domain_to_ascii_strict(name)
307            .into_alien_error()
308            .context(ErrorData::SandboxEgressInvalid {
309                target: target.to_string(),
310                reason: "expected a DNS hostname".to_string(),
311            })?
312            .to_ascii_lowercase();
313        if name.len() > 253
314            || !name.contains('.')
315            || name.split('.').any(|label| {
316                label.is_empty()
317                    || label.len() > 63
318                    || label.starts_with('-')
319                    || label.ends_with('-')
320                    || !label
321                        .bytes()
322                        .all(|c| c.is_ascii_alphanumeric() || c == b'-')
323            })
324            || name
325                .rsplit('.')
326                .next()
327                .is_some_and(|label| label.bytes().all(|c| c.is_ascii_digit()))
328        {
329            return Err(invalid(
330                target,
331                "expected a hostname, *.hostname, IPv4 literal or IPv4 CIDR",
332            ));
333        }
334        if psl::domain_str(&name).is_none() {
335            return Err(invalid(
336                target,
337                "public suffixes cannot be allowed as destinations",
338            ));
339        }
340        Ok(Self {
341            host: Host::Name { name, wildcard },
342            port,
343        })
344    }
345
346    fn canonical(&self) -> String {
347        let host = match &self.host {
348            Host::Name { name, wildcard } => format!("{}{name}", if *wildcard { "*." } else { "" }),
349            Host::Network(network) if network.prefix_len() == 32 => network.addr().to_string(),
350            Host::Network(network) => network.to_string(),
351            Host::Link(id) => return format!("{LINK_TARGET_PREFIX}{id}"),
352        };
353        match self.port {
354            Some(port) => format!("{host}:{port}"),
355            None => host,
356        }
357    }
358
359    fn contains(&self, target: &Self) -> bool {
360        if self.port.is_some() && self.port != target.port {
361            return false;
362        }
363        match (&self.host, &target.host) {
364            (Host::Network(parent), Host::Network(child)) => parent.contains(child),
365            (
366                Host::Name {
367                    name: parent,
368                    wildcard: parent_wildcard,
369                },
370                Host::Name {
371                    name: child,
372                    wildcard: child_wildcard,
373                },
374            ) => {
375                if *parent_wildcard {
376                    child == parent
377                        || child
378                            .strip_suffix(parent)
379                            .is_some_and(|prefix| prefix.ends_with('.') && prefix.len() > 1)
380                } else {
381                    !child_wildcard && child == parent
382                }
383            }
384            _ => false,
385        }
386    }
387}
388
389/// Whether an IPv4 address is public unicast, excluding metadata and special-use ranges.
390pub fn is_public_ipv4(ip: Ipv4Addr) -> bool {
391    !non_public_ipv4_ranges().any(|range| range.contains(&ip))
392}
393
394/// The IPv4 ranges `is_public_ipv4` refuses, for enforcement points that match ranges
395/// rather than single addresses, such as a NetworkPolicy `ipBlock`.
396pub fn non_public_ipv4_ranges() -> impl Iterator<Item = Ipv4Net> {
397    DENIED_RANGES
398        .iter()
399        .map(|&(address, prefix)| Ipv4Net::new_assert(Ipv4Addr::from(address), prefix))
400}
401
402// Includes shared address space, metadata endpoints and non-unicast/reserved ranges.
403const DENIED_RANGES: &[(u32, u8)] = &[
404    (0x00000000, 8),
405    (0x0a000000, 8),
406    (0x64400000, 10),
407    (0x7f000000, 8),
408    (0xa9fe0000, 16),
409    (0xac100000, 12),
410    (0xc0a80000, 16),
411    (0xc0000000, 24),
412    (0xc0000200, 24),
413    (0xc6120000, 15),
414    (0xc6336400, 24),
415    (0xcb007100, 24),
416    (0xe0000000, 3),
417    (0xa83f8110, 32),
418];
419
420#[cfg(test)]
421mod tests;