use crate::error::{ErrorData, Result};
use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
use crate::resources::ToolchainConfig;
use crate::Platform;
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt::Debug;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum SandboxCode {
#[serde(rename_all = "camelCase")]
Image {
image: String,
},
#[serde(rename_all = "camelCase")]
Source {
src: String,
toolchain: ToolchainConfig,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SandboxLimits {
pub cpu: String,
pub memory: String,
pub disk: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_processes: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MicrovmTier {
pub baseline_memory_mib: i64,
pub peak_memory_mib: i64,
pub peak_vcpu: u32,
pub max_disk_mib: i64,
}
const AWS_MAX_SESSION_LIFETIME_SECONDS: u32 = 28_800;
const MICROVM_TIERS: &[MicrovmTier] = &[
MicrovmTier {
baseline_memory_mib: 512,
peak_memory_mib: 2048,
peak_vcpu: 1,
max_disk_mib: 8192,
},
MicrovmTier {
baseline_memory_mib: 1024,
peak_memory_mib: 4096,
peak_vcpu: 2,
max_disk_mib: 8192,
},
MicrovmTier {
baseline_memory_mib: 2048,
peak_memory_mib: 8192,
peak_vcpu: 4,
max_disk_mib: 8192,
},
MicrovmTier {
baseline_memory_mib: 4096,
peak_memory_mib: 16384,
peak_vcpu: 8,
max_disk_mib: 16384,
},
MicrovmTier {
baseline_memory_mib: 8192,
peak_memory_mib: 32768,
peak_vcpu: 16,
max_disk_mib: 32768,
},
];
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "mode")]
pub enum SandboxEgress {
Deny,
Allow,
#[serde(rename_all = "camelCase")]
AllowDomains {
domains: Vec<String>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SandboxSessionPolicy {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_lifetime_seconds: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub idle_suspend_seconds: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SandboxCapabilities {
pub files: bool,
pub reconnect: bool,
pub preview: bool,
pub suspend_resume: bool,
pub snapshot: bool,
pub domain_egress_rules: bool,
pub egress_deny: bool,
pub enforced_limits: bool,
pub process_limit: bool,
pub session_lifetime: bool,
pub supervisor_pid_namespace: bool,
}
impl SandboxCapabilities {
pub fn for_platform(platform: Platform) -> Result<Self> {
match platform {
Platform::Aws => Ok(Self {
files: true,
reconnect: true,
preview: true,
suspend_resume: true,
snapshot: false,
domain_egress_rules: false,
egress_deny: true,
enforced_limits: true,
process_limit: false,
session_lifetime: true,
supervisor_pid_namespace: false,
}),
Platform::Azure => Ok(Self {
files: false,
reconnect: true,
preview: false,
suspend_resume: false,
snapshot: false,
domain_egress_rules: false,
egress_deny: false,
enforced_limits: false,
process_limit: false,
session_lifetime: false,
supervisor_pid_namespace: false,
}),
Platform::Gcp => Ok(Self {
files: true,
reconnect: false,
preview: false,
suspend_resume: false,
snapshot: false,
domain_egress_rules: false,
egress_deny: true,
enforced_limits: false,
process_limit: false,
session_lifetime: false,
supervisor_pid_namespace: false,
}),
Platform::Kubernetes => Ok(Self {
files: true,
reconnect: true,
preview: false,
suspend_resume: false,
snapshot: false,
domain_egress_rules: false,
egress_deny: true,
enforced_limits: true,
process_limit: false,
session_lifetime: true,
supervisor_pid_namespace: false,
}),
Platform::Local => Ok(Self {
files: true,
reconnect: true,
preview: true,
suspend_resume: false,
snapshot: false,
domain_egress_rules: false,
egress_deny: true,
enforced_limits: true,
process_limit: true,
session_lifetime: false,
supervisor_pid_namespace: false,
}),
Platform::Machines | Platform::Test => {
Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
platform: platform.to_string(),
}))
}
}
}
pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
let available = match capability {
SandboxCapability::Files => self.files,
SandboxCapability::Reconnect => self.reconnect,
SandboxCapability::Preview => self.preview,
SandboxCapability::SuspendResume => self.suspend_resume,
SandboxCapability::Snapshot => self.snapshot,
SandboxCapability::DomainEgressRules => self.domain_egress_rules,
SandboxCapability::EgressDeny => self.egress_deny,
SandboxCapability::EnforcedLimits => self.enforced_limits,
SandboxCapability::ProcessLimit => self.process_limit,
SandboxCapability::SessionLifetime => self.session_lifetime,
SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
};
if available {
return Ok(());
}
Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
capability: capability.as_str().to_string(),
platform: platform.to_string(),
}))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum SandboxCapability {
Files,
Reconnect,
Preview,
SuspendResume,
Snapshot,
DomainEgressRules,
EgressDeny,
EnforcedLimits,
ProcessLimit,
SessionLifetime,
SupervisorPidNamespace,
}
impl SandboxCapability {
pub fn as_str(&self) -> &'static str {
match self {
Self::Files => "files",
Self::Reconnect => "reconnect",
Self::Preview => "preview",
Self::SuspendResume => "suspendResume",
Self::Snapshot => "snapshot",
Self::DomainEgressRules => "domainEgressRules",
Self::EgressDeny => "egressDeny",
Self::EnforcedLimits => "enforcedLimits",
Self::ProcessLimit => "processLimit",
Self::SessionLifetime => "sessionLifetime",
Self::SupervisorPidNamespace => "supervisorPidNamespace",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct Sandbox {
#[builder(start_fn)]
pub id: String,
pub code: SandboxCode,
#[serde(skip_serializing_if = "Option::is_none")]
pub limits: Option<SandboxLimits>,
pub egress: SandboxEgress,
pub session: SandboxSessionPolicy,
#[builder(default)]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub preview_ports: Vec<u16>,
}
pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
!targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
}
pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
stack.resources().any(|(_resource_id, resource)| {
resource
.config
.downcast_ref::<Sandbox>()
.is_some_and(|sandbox| !matches!(sandbox.egress, SandboxEgress::Allow))
})
}
impl Sandbox {
pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
pub fn id(&self) -> &str {
&self.id
}
pub fn resolved_limits(&self) -> SandboxLimits {
self.limits.clone().unwrap_or_else(default_limits)
}
pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
let capabilities = SandboxCapabilities::for_platform(platform)?;
if let SandboxCode::Source { .. } = &self.code {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "code".to_string(),
value: "source".to_string(),
reason: "no sandbox backend builds an image from source yet; give code.image a \
prebuilt reference"
.to_string(),
}));
}
let Some(limits) = self.limits.as_ref() else {
return self.validate_capabilities(&capabilities, platform);
};
validate_quantity(&self.id, "cpu", &limits.cpu)?;
validate_quantity(&self.id, "memory", &limits.memory)?;
validate_quantity(&self.id, "disk", &limits.disk)?;
if let Some(max_processes) = limits.max_processes {
if max_processes == 0 {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "maxProcesses".to_string(),
value: "0".to_string(),
reason: "a sandbox that may run no processes cannot run code".to_string(),
}));
}
capabilities.require(SandboxCapability::ProcessLimit, platform)?;
}
capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
if platform == Platform::Aws {
self.microvm_tier()?;
if let Some(seconds) = self.session.max_lifetime_seconds {
if !(1..=AWS_MAX_SESSION_LIFETIME_SECONDS).contains(&seconds) {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "maxLifetimeSeconds".to_string(),
value: seconds.to_string(),
reason: format!(
"AWS runs a MicroVM for between 1 and \
{AWS_MAX_SESSION_LIFETIME_SECONDS} seconds"
),
}));
}
}
}
self.validate_capabilities(&capabilities, platform)
}
pub fn microvm_tier(&self) -> Result<MicrovmTier> {
let Some(limits) = self.limits.as_ref() else {
return Ok(MICROVM_TIERS[2]);
};
let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "memory".to_string(),
value: limits.memory.clone(),
reason: "AWS sizes a MicroVM in whole MiB".to_string(),
})
})?;
let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "disk".to_string(),
value: limits.disk.clone(),
reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
})
})?;
let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "cpu".to_string(),
value: limits.cpu.clone(),
reason: "expected cores or millicores".to_string(),
})
})?;
let sized = |tier: &&MicrovmTier| {
tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
};
let tier = MICROVM_TIERS
.iter()
.rev()
.find(sized)
.copied()
.ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "memory".to_string(),
value: limits.memory.clone(),
reason: format!(
"a Lambda MicroVM bursts to four times its baseline, so the smallest \
ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
disk fit no size",
limits.memory, limits.disk
),
})
})?;
let required_millicores = i64::from(tier.peak_vcpu) * 1000;
if cpu_millicores < required_millicores {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "cpu".to_string(),
value: limits.cpu.clone(),
reason: format!(
"AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
limits.memory, tier.peak_vcpu, tier.peak_vcpu
),
}));
}
Ok(tier)
}
fn validate_capabilities(
&self,
capabilities: &SandboxCapabilities,
platform: Platform,
) -> Result<()> {
if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
}
if matches!(self.egress, SandboxEgress::Deny) {
capabilities.require(SandboxCapability::EgressDeny, platform)?;
}
if !self.preview_ports.is_empty() {
capabilities.require(SandboxCapability::Preview, platform)?;
}
if self.session.idle_suspend_seconds.is_some() {
capabilities.require(SandboxCapability::SuspendResume, platform)?;
}
if self.session.max_lifetime_seconds.is_some() {
capabilities.require(SandboxCapability::SessionLifetime, platform)?;
}
Ok(())
}
}
fn default_limits() -> SandboxLimits {
SandboxLimits {
cpu: "1".to_string(),
memory: "2Gi".to_string(),
disk: "8Gi".to_string(),
max_processes: None,
}
}
fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
let invalid = |reason: &str| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: resource_id.to_string(),
field: field.to_string(),
value: value.to_string(),
reason: reason.to_string(),
})
};
let digits_end = value
.find(|c: char| !c.is_ascii_digit() && c != '.')
.unwrap_or(value.len());
let (number, suffix) = value.split_at(digits_end);
let parsed: f64 = number
.parse()
.map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
if parsed <= 0.0 {
return Err(invalid("must be greater than zero"));
}
const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
if !SUFFIXES.contains(&suffix) {
return Err(invalid(
"unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
));
}
Ok(())
}
fn split_quantity(value: &str) -> Option<(f64, &str)> {
let trimmed = value.trim();
let digits_end = trimmed
.find(|c: char| !c.is_ascii_digit() && c != '.')
.unwrap_or(trimmed.len());
let (number, suffix) = trimmed.split_at(digits_end);
number.parse().ok().map(|number| (number, suffix))
}
pub fn quantity_mib(value: &str) -> Option<i64> {
let (number, suffix) = split_quantity(value)?;
let bytes = match suffix {
"" => number,
"k" => number * 1e3,
"M" => number * 1e6,
"G" => number * 1e9,
"T" => number * 1e12,
"Ki" => number * 1024.0,
"Mi" => number * 1024.0 * 1024.0,
"Gi" => number * 1024.0 * 1024.0 * 1024.0,
"Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
_ => return None,
};
Some((bytes / (1024.0 * 1024.0)) as i64)
}
pub fn millicores(value: &str) -> Option<i64> {
let (number, suffix) = split_quantity(value)?;
match suffix {
"" => Some((number * 1000.0) as i64),
"m" => Some(number as i64),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct SandboxOutputs {
pub parent_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
}
impl ResourceOutputsDefinition for SandboxOutputs {
fn get_resource_type(&self) -> ResourceType {
Sandbox::RESOURCE_TYPE
}
fn as_any(&self) -> &dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
Box::new(self.clone())
}
fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
impl ResourceDefinition for Sandbox {
fn get_resource_type(&self) -> ResourceType {
Self::RESOURCE_TYPE
}
fn id(&self) -> &str {
&self.id
}
fn get_dependencies(&self) -> Vec<ResourceRef> {
Vec::new()
}
fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
let new_sandbox = new_config
.as_any()
.downcast_ref::<Sandbox>()
.ok_or_else(|| {
AlienError::new(ErrorData::UnexpectedResourceType {
resource_id: self.id.clone(),
expected: Self::RESOURCE_TYPE,
actual: new_config.get_resource_type(),
})
})?;
if self.id != new_sandbox.id {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'id' field is immutable".to_string(),
}));
}
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceDefinition> {
Box::new(self.clone())
}
fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
other.as_any().downcast_ref::<Sandbox>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
Sandbox::new("agent-sbx".to_string())
.code(SandboxCode::Image {
image: "ubuntu:24.04".to_string(),
})
.limits(SandboxLimits {
cpu: "1".to_string(),
memory: "2Gi".to_string(),
disk: "20Gi".to_string(),
max_processes: None,
})
.egress(egress)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.preview_ports(preview_ports)
.build()
}
#[test]
fn resource_type_is_stable() {
assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
}
#[test]
fn capability_sets_are_per_platform() {
let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
assert!(
!gcp.reconnect,
"a GCP session id is scoped to one instance, so reconnect is absent"
);
assert!(!gcp.preview);
assert!(!gcp.enforced_limits);
let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
assert!(!azure.files, "the Azure data plane has no file transfer");
assert!(gcp.files, "every other backend moves files");
assert!(!azure.domain_egress_rules);
assert!(!azure.egress_deny);
assert!(!azure.enforced_limits);
assert!(!azure.snapshot);
assert!(!azure.preview);
assert!(!azure.suspend_resume);
let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
assert!(!aws.snapshot, "AWS has no user-callable session snapshot");
assert!(aws.suspend_resume);
let k8s =
SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
assert!(
!k8s.preview,
"the session-scoped ingress gateway does not exist yet"
);
}
#[test]
fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
let error = SandboxCapabilities::for_platform(Platform::Machines)
.expect_err("Machines has no sandbox backend");
assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
}
#[test]
fn unsupported_capability_names_platform_and_capability() {
let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
let error = capabilities
.require(SandboxCapability::Preview, Platform::Gcp)
.expect_err("GCP has no preview");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
let rendered = error.to_string();
assert!(
rendered.contains("preview"),
"names the capability: {rendered}"
);
assert!(rendered.contains("gcp"), "names the platform: {rendered}");
}
#[test]
fn a_hostname_allowlist_is_refused_on_every_backend() {
let sandbox = sandbox_with(
SandboxEgress::AllowDomains {
domains: vec!["example.com".to_string()],
},
vec![],
);
for platform in [
Platform::Aws,
Platform::Azure,
Platform::Gcp,
Platform::Kubernetes,
Platform::Local,
] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("no backend expresses a hostname allowlist");
assert_eq!(
error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
"on {platform:?}"
);
}
}
#[test]
fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
let sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
assert!(
SandboxCapabilities::for_platform(Platform::Gcp)
.expect("supported")
.egress_deny
);
for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
sandbox
.validate_for_platform(platform)
.expect("deny is enforced here");
}
let egress_only = Sandbox::new("sbx".to_string())
.code(SandboxCode::Image {
image: "alpine:3.20".to_string(),
})
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
let error = egress_only
.validate_for_platform(Platform::Azure)
.expect_err("the Azure data plane takes no egress policy, so deny cannot be kept");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
assert!(
error.message.contains("egressDeny"),
"names the capability: {}",
error.message
);
}
#[test]
fn a_platform_that_cannot_enforce_limits_still_takes_a_sandbox_without_them() {
let declared = sandbox_with(SandboxEgress::Deny, Vec::new());
declared
.validate_for_platform(Platform::Gcp)
.expect_err("declaring ceilings GCP cannot enforce is rejected");
let undeclared = Sandbox::new("sbx".to_string())
.code(SandboxCode::Image {
image: "alpine:3.20".to_string(),
})
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
undeclared
.validate_for_platform(Platform::Gcp)
.expect("a sandbox naming no ceilings takes the platform's own");
assert_eq!(undeclared.resolved_limits().cpu, "1");
}
#[test]
fn preview_ports_require_the_preview_capability() {
let sandbox = sandbox_with(SandboxEgress::Deny, vec![8080]);
sandbox
.validate_for_platform(Platform::Aws)
.expect("AWS mints a port-scoped JWE");
let error = sandbox
.validate_for_platform(Platform::Kubernetes)
.expect_err("Kubernetes preview is deferred");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
}
#[test]
fn gcp_rejects_a_sandbox_declaring_enforced_limits() {
let sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
let error = sandbox
.validate_for_platform(Platform::Gcp)
.expect_err("GCP cannot enforce ceilings on a subprocess sandbox");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
}
#[test]
fn invalid_quantities_are_rejected_with_the_offending_field() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.memory = "2Gb".to_string();
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("Gb is not a valid suffix");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(error.to_string().contains("memory"));
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.memory = "2Gi".to_string();
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.cpu = "0".to_string();
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("zero cpu is not a ceiling");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
}
#[test]
fn zero_max_processes_is_rejected() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.max_processes = Some(0);
let error = sandbox
.validate_for_platform(Platform::Local)
.expect_err("a sandbox must be able to run at least one process");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(error.to_string().contains("maxProcesses"));
}
#[test]
fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.max_processes = Some(256);
sandbox
.validate_for_platform(Platform::Local)
.expect("Docker takes a pids limit");
for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("a process ceiling nothing applies must be refused");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
}
}
#[test]
fn a_lifetime_aws_would_reject_is_refused_while_planning() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
for seconds in [0, 28_801, 100_000] {
sandbox.session.max_lifetime_seconds = Some(seconds);
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("a lifetime outside what AWS runs is refused");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "{seconds}s");
sandbox
.validate_for_platform(Platform::Kubernetes)
.expect("the kubelet takes any activeDeadlineSeconds");
}
sandbox.session.max_lifetime_seconds = Some(28_800);
sandbox
.validate_for_platform(Platform::Aws)
.expect("the ceiling itself is allowed");
}
#[test]
fn a_session_deadline_is_accepted_only_where_the_platform_applies_it() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox.session.max_lifetime_seconds = Some(3600);
sandbox
.validate_for_platform(Platform::Kubernetes)
.expect("the kubelet enforces activeDeadlineSeconds");
sandbox
.validate_for_platform(Platform::Aws)
.expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
for platform in [Platform::Azure, Platform::Local] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("a deadline nothing applies must be refused");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
}
}
#[test]
fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
let sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
let tier = sandbox
.microvm_tier()
.expect("2Gi/1cpu/20Gi is satisfiable");
assert_eq!(
tier.peak_memory_mib, 2048,
"the peak is the declared ceiling"
);
assert_eq!(
tier.baseline_memory_mib, 512,
"which is a quarter of it as the baseline"
);
assert!(tier.max_disk_mib <= 20 * 1024);
}
#[test]
fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
{
let limits = sandbox
.limits
.as_mut()
.expect("the fixture declares limits");
limits.cpu = "1".to_string();
limits.memory = "8Gi".to_string();
}
let error = sandbox
.microvm_tier()
.expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
assert!(
error.to_string().contains("4 vCPU"),
"the refusal must say what the memory ceiling implies: {error}"
);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.cpu = "4".to_string();
let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
assert_eq!(tier.peak_memory_mib, 8192);
}
#[test]
fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.memory = "1Gi".to_string();
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("no MicroVM size peaks at or below 1Gi");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(
error.to_string().contains("2Gi"),
"the refusal must say what the smallest holdable ceiling is: {error}"
);
}
#[test]
fn source_code_is_refused_everywhere_rather_than_producing_a_broken_manifest() {
let sandbox = Sandbox::new("agent".to_string())
.code(SandboxCode::Source {
src: "./sandbox".to_string(),
toolchain: ToolchainConfig::Docker {
dockerfile: None,
build_args: None,
target: None,
},
})
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
for platform in [
Platform::Aws,
Platform::Azure,
Platform::Gcp,
Platform::Kubernetes,
Platform::Local,
] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("no backend builds a sandbox image from source");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(
error.to_string().contains("code.image"),
"the refusal must say what to write instead: {error}"
);
}
}
#[test]
fn every_accepted_unit_converts_rather_than_falling_back() {
assert_eq!(quantity_mib("2Gi"), Some(2048));
assert_eq!(quantity_mib("512Mi"), Some(512));
assert_eq!(quantity_mib("4G"), Some(3814));
assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
assert_eq!(millicores("1"), Some(1000));
assert_eq!(millicores("500m"), Some(500));
}
#[test]
fn unknown_fields_are_rejected() {
let json = r#"{
"id": "sbx",
"code": {"type": "image", "image": "ubuntu:24.04"},
"limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
"egress": {"mode": "deny"},
"session": {},
"unexpected": true
}"#;
serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
}
#[test]
fn serialization_roundtrips() {
let sandbox = sandbox_with(
SandboxEgress::AllowDomains {
domains: vec!["example.com".to_string()],
},
vec![8080, 9090],
);
let json = serde_json::to_string(&sandbox).expect("serializes");
let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
assert_eq!(sandbox, restored);
}
#[test]
fn id_is_immutable_across_updates() {
let original = sandbox_with(SandboxEgress::Deny, vec![]);
let renamed = Sandbox::new("other".to_string())
.code(SandboxCode::Image {
image: "ubuntu:24.04".to_string(),
})
.limits(
original
.limits
.clone()
.expect("the fixture declares limits"),
)
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
original
.validate_update(&original.clone())
.expect("an unchanged config is a valid update");
original
.validate_update(&renamed)
.expect_err("renaming a sandbox is not an update");
}
}