alien-core 3.3.72

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Runtime sandbox destination policies and public-address validation.

use sha2::{Digest, Sha256};
use std::net::Ipv4Addr;

use alien_error::{AlienError, Context, IntoAlienError};
use ipnet::Ipv4Net;
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "openapi")]
use utoipa::openapi::schema::{ArrayBuilder, ObjectBuilder, OneOfBuilder, Type};

use crate::error::{ErrorData, Result};

/// Per-sandbox outbound policy enforced by the gateway.
///
/// Mail ports 25, 465 and 587 require an explicit port in an allowlist target,
/// 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,
/// which could disrupt every tenant's access through that IP.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum EgressPolicy {
    /// Public internet access except mail ports 25, 465 and 587.
    /// Private and link-local destinations remain forbidden.
    Internet,
    /// Explicit destinations; unspecified ports exclude 25, 465 and 587.
    /// Wildcards include the apex. An explicit port can allow a mail destination.
    /// `link:<resource-id>` names a service the stack links to the sandbox; nothing else
    /// reaches a link, so `allow: []` refuses links too.
    #[serde(untagged)]
    Allow {
        /// Hostnames, wildcard hostnames, IPv4 literals, IPv4 CIDRs (optionally with a port),
        /// or `link:<resource-id>`.
        allow: Vec<String>,
    },
}

// Utoipa does not support serde's per-variant `untagged`, so describe the wire union explicitly.
#[cfg(feature = "openapi")]
impl utoipa::PartialSchema for EgressPolicy {
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        OneOfBuilder::new()
            .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."))
            .item(
                ObjectBuilder::new()
                    .schema_type(Type::String)
                    .enum_values(Some(["internet"])),
            )
            .item(
                ObjectBuilder::new()
                    .property(
                        "allow",
                        ArrayBuilder::new()
                            .items(ObjectBuilder::new().schema_type(Type::String))
                            .min_items(Some(0))
                            .max_items(Some(4096)),
                    )
                    .required("allow")
                    .additional_properties(Some(
                        utoipa::openapi::schema::AdditionalProperties::FreeForm(false),
                    )),
            )
            .into()
    }
}

#[cfg(feature = "openapi")]
impl utoipa::ToSchema for EgressPolicy {}

impl<'de> Deserialize<'de> for EgressPolicy {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        enum Mode {
            Internet,
        }
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Allow {
            allow: Vec<String>,
        }
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Input {
            Mode(Mode),
            Allow(Allow),
        }
        Ok(match Input::deserialize(deserializer)? {
            Input::Mode(Mode::Internet) => Self::Internet,
            Input::Allow(Allow { allow }) => Self::Allow { allow },
        })
    }
}

impl EgressPolicy {
    /// Validates every target before a deployment or runtime request can take effect.
    pub fn validate(&self) -> Result<()> {
        self.targets().map(|_| ())
    }

    /// Returns a validated policy with ASCII, lowercase names and canonical IP networks.
    pub fn normalized(&self) -> Result<Self> {
        match self {
            Self::Allow { .. } => Ok(Self::Allow {
                allow: self.targets()?.iter().map(Target::canonical).collect(),
            }),
            _ => Ok(self.clone()),
        }
    }

    /// Canonical JSON used to authenticate gateway policy writes: normalized, sorted, no whitespace.
    /// Duplicate entries remain present; sorting makes input order irrelevant to the digest.
    pub fn canonical_json(&self) -> Result<Vec<u8>> {
        let mut policy = self.normalized()?;
        if let Self::Allow { allow } = &mut policy {
            allow.sort_unstable();
        }
        serde_json::to_vec(&policy)
            .into_alien_error()
            .context(ErrorData::SandboxEgressInvalid {
                target: "policy".to_string(),
                reason: "could not encode canonical policy".to_string(),
            })
    }

    /// SHA-256 digest authenticating the policy body in an admin JWS.
    pub fn policy_digest(&self) -> Result<String> {
        Ok(format!(
            "sha256:{:x}",
            Sha256::digest(self.canonical_json()?)
        ))
    }

    /// Whether this policy lets the sandbox reach the service its stack links as `resource_id`.
    ///
    /// The stack's links are the ceiling; this only narrows them. `internet` keeps every
    /// declared link, an allowlist keeps the links it names as `link:<resource-id>`, and an
    /// empty allowlist keeps none. A name the stack does not link matches nothing here, and the
    /// gateway answers only for declared links.
    pub fn allows_link(&self, resource_id: &str) -> bool {
        match self {
            Self::Internet => true,
            Self::Allow { allow } => allow.iter().any(|entry| {
                Target::parse(entry)
                    .is_ok_and(|target| matches!(&target.host, Host::Link(id) if id == resource_id))
            }),
        }
    }

    /// Whether this policy has a `link:<resource-id>` entry, which releases before links cannot
    /// read.
    pub fn names_links(&self) -> bool {
        match self {
            Self::Internet => false,
            Self::Allow { allow } => allow
                .iter()
                .any(|entry| entry.starts_with(LINK_TARGET_PREFIX)),
        }
    }

    /// Whether a concrete public destination and port match this policy.
    pub fn allows(&self, host: &str, port: u16) -> Result<bool> {
        let destination = format!("{host}:{port}");
        let target = Target::parse(&destination)?;
        if matches!(target.host, Host::Link(_)) {
            return Err(invalid(&destination, "a link is not a destination"));
        }
        // Sandboxes share one outbound IP: unsolicited mail can get that IP blocklisted
        // for every tenant. Explicit destination:port grants retain legitimate mail use.
        let mail = matches!(port, 25 | 465 | 587);
        Ok((!mail && matches!(self, Self::Internet))
            || self
                .targets()?
                .iter()
                .any(|entry| (!mail || entry.port == Some(port)) && entry.contains(&target)))
    }

    fn targets(&self) -> Result<Vec<Target>> {
        let Self::Allow { allow } = self else {
            return Ok(Vec::new());
        };
        if allow.len() > 4096 {
            return Err(AlienError::new(ErrorData::SandboxEgressPolicyTooLarge {
                limit: "4096 targets".to_string(),
            }));
        }
        let targets = allow
            .iter()
            .map(|target| Target::parse(target))
            .collect::<Result<Vec<_>>>()?;
        // Valid targets are ASCII without JSON escape characters. Include object/array syntax,
        // two quotes per target and commas to measure the exact canonical JSON byte length.
        let canonical_bytes = 12 - usize::from(!targets.is_empty())
            + targets
                .iter()
                .map(|target| target.canonical().len() + 3)
                .sum::<usize>();
        if canonical_bytes > 256 * 1024 {
            return Err(AlienError::new(ErrorData::SandboxEgressPolicyTooLarge {
                limit: "256 KiB of canonical JSON".to_string(),
            }));
        }
        Ok(targets)
    }
}

#[derive(Debug)]
struct Target {
    host: Host,
    port: Option<u16>,
}

#[derive(Debug)]
enum Host {
    Name {
        name: String,
        wildcard: bool,
    },
    Network(Ipv4Net),
    /// A service the stack links to the sandbox, by resource id. It never matches a host or
    /// an address: only the gateway's declared links resolve it.
    Link(String),
}

/// Prefix of a policy entry naming a linked service rather than a destination.
pub const LINK_TARGET_PREFIX: &str = "link:";

fn invalid(target: &str, reason: &str) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::SandboxEgressInvalid {
        target: target.to_string(),
        reason: reason.to_string(),
    })
}

impl Target {
    fn parse(target: &str) -> Result<Self> {
        if let Some(id) = target.strip_prefix(LINK_TARGET_PREFIX) {
            // The ports are the link's declared ports; a policy cannot name others.
            crate::stack_authoring::validate_resource_id(id).map_err(|reason| {
                invalid(
                    target,
                    &format!("expected link:<resource-id> with no port; the resource id {reason}"),
                )
            })?;
            return Ok(Self {
                host: Host::Link(id.to_string()),
                port: None,
            });
        }
        let (host, port) = match target.rsplit_once(':') {
            Some((host, port)) => {
                if port.is_empty() || !port.bytes().all(|c| c.is_ascii_digit()) {
                    return Err(invalid(
                        target,
                        "port must be an integer between 1 and 65535",
                    ));
                }
                let port: u16 =
                    port.parse()
                        .into_alien_error()
                        .context(ErrorData::SandboxEgressInvalid {
                            target: target.to_string(),
                            reason: "port must be between 1 and 65535".to_string(),
                        })?;
                if port == 0 {
                    return Err(invalid(target, "port must be between 1 and 65535"));
                }
                (host, Some(port))
            }
            None => (target, None),
        };
        let host = host.strip_suffix('.').unwrap_or(host);
        let network = if host.contains('/') {
            Some(
                host.parse::<Ipv4Net>()
                    .into_alien_error()
                    .context(ErrorData::SandboxEgressInvalid {
                        target: target.to_string(),
                        reason: "expected an IPv4 CIDR".to_string(),
                    })?
                    .trunc(),
            )
        } else {
            host.parse::<Ipv4Addr>().ok().map(Ipv4Net::from)
        };
        if let Some(network) = network {
            // Test intersection, not just the first address: a broad CIDR can include private IPs.
            if DENIED_RANGES.iter().any(|&(address, prefix)| {
                let denied = Ipv4Net::new_assert(Ipv4Addr::from(address), prefix);
                denied.contains(&network) || network.contains(&denied)
            }) {
                return Err(invalid(
                    target,
                    "private, link-local and special-use IPv4 ranges are forbidden",
                ));
            }
            return Ok(Self {
                host: Host::Network(network),
                port,
            });
        }
        let (name, wildcard) = match host.strip_prefix("*.") {
            Some(name) => (name, true),
            None => (host, false),
        };
        let name = idna::domain_to_ascii_strict(name)
            .into_alien_error()
            .context(ErrorData::SandboxEgressInvalid {
                target: target.to_string(),
                reason: "expected a DNS hostname".to_string(),
            })?
            .to_ascii_lowercase();
        if name.len() > 253
            || !name.contains('.')
            || name.split('.').any(|label| {
                label.is_empty()
                    || label.len() > 63
                    || label.starts_with('-')
                    || label.ends_with('-')
                    || !label
                        .bytes()
                        .all(|c| c.is_ascii_alphanumeric() || c == b'-')
            })
            || name
                .rsplit('.')
                .next()
                .is_some_and(|label| label.bytes().all(|c| c.is_ascii_digit()))
        {
            return Err(invalid(
                target,
                "expected a hostname, *.hostname, IPv4 literal or IPv4 CIDR",
            ));
        }
        if psl::domain_str(&name).is_none() {
            return Err(invalid(
                target,
                "public suffixes cannot be allowed as destinations",
            ));
        }
        Ok(Self {
            host: Host::Name { name, wildcard },
            port,
        })
    }

    fn canonical(&self) -> String {
        let host = match &self.host {
            Host::Name { name, wildcard } => format!("{}{name}", if *wildcard { "*." } else { "" }),
            Host::Network(network) if network.prefix_len() == 32 => network.addr().to_string(),
            Host::Network(network) => network.to_string(),
            Host::Link(id) => return format!("{LINK_TARGET_PREFIX}{id}"),
        };
        match self.port {
            Some(port) => format!("{host}:{port}"),
            None => host,
        }
    }

    fn contains(&self, target: &Self) -> bool {
        if self.port.is_some() && self.port != target.port {
            return false;
        }
        match (&self.host, &target.host) {
            (Host::Network(parent), Host::Network(child)) => parent.contains(child),
            (
                Host::Name {
                    name: parent,
                    wildcard: parent_wildcard,
                },
                Host::Name {
                    name: child,
                    wildcard: child_wildcard,
                },
            ) => {
                if *parent_wildcard {
                    child == parent
                        || child
                            .strip_suffix(parent)
                            .is_some_and(|prefix| prefix.ends_with('.') && prefix.len() > 1)
                } else {
                    !child_wildcard && child == parent
                }
            }
            _ => false,
        }
    }
}

/// Whether an IPv4 address is public unicast, excluding metadata and special-use ranges.
pub fn is_public_ipv4(ip: Ipv4Addr) -> bool {
    !non_public_ipv4_ranges().any(|range| range.contains(&ip))
}

/// The IPv4 ranges `is_public_ipv4` refuses, for enforcement points that match ranges
/// rather than single addresses, such as a NetworkPolicy `ipBlock`.
pub fn non_public_ipv4_ranges() -> impl Iterator<Item = Ipv4Net> {
    DENIED_RANGES
        .iter()
        .map(|&(address, prefix)| Ipv4Net::new_assert(Ipv4Addr::from(address), prefix))
}

// Includes shared address space, metadata endpoints and non-unicast/reserved ranges.
const DENIED_RANGES: &[(u32, u8)] = &[
    (0x00000000, 8),
    (0x0a000000, 8),
    (0x64400000, 10),
    (0x7f000000, 8),
    (0xa9fe0000, 16),
    (0xac100000, 12),
    (0xc0a80000, 16),
    (0xc0000000, 24),
    (0xc0000200, 24),
    (0xc6120000, 15),
    (0xc6336400, 24),
    (0xcb007100, 24),
    (0xe0000000, 3),
    (0xa83f8110, 32),
];

#[cfg(test)]
mod tests;