1use crate::error::{ErrorData, Result};
11use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
12use crate::resources::sandbox_image_permissions;
13pub use crate::resources::sandbox_image_permissions::{
14 tmpfs_size_bytes, PrivateEndpointPlacement, PrivateNetworkEndpoints, SandboxImageConnection,
15 SandboxImageMount, SandboxImageMountType, SandboxImagePermissions,
16};
17use crate::resources::ToolchainConfig;
18use crate::Platform;
19use alien_error::AlienError;
20use bon::Builder;
21use serde::{Deserialize, Serialize};
22use sha2::{Digest, Sha256};
23use std::any::Any;
24use std::fmt::Debug;
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
29#[serde(rename_all = "camelCase", tag = "type")]
30pub enum SandboxCode {
31 #[serde(rename_all = "camelCase")]
33 Image {
34 image: String,
38 #[serde(default, skip_serializing_if = "Option::is_none")]
43 #[cfg_attr(feature = "openapi", schema(ignore))]
44 bundled_from: Option<String>,
45 },
46 #[serde(rename_all = "camelCase")]
52 Source {
53 src: String,
55 toolchain: ToolchainConfig,
57 },
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
67#[serde(rename_all = "camelCase", deny_unknown_fields)]
68pub struct SandboxLimits {
69 pub cpu: String,
71 pub memory: String,
73 pub disk: String,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub max_processes: Option<u32>,
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct MicrovmTier {
91 pub baseline_memory_mib: i64,
93 pub peak_memory_mib: i64,
95 pub peak_vcpu: u32,
97 pub max_disk_mib: i64,
99}
100
101const AWS_MAX_LIFETIME_SECONDS: u32 = 28_800;
105
106const KUBERNETES_MAX_LIFETIME_SECONDS: u32 = i32::MAX as u32;
109
110const GCP_MAX_DISK_BYTES: u128 = 10 * 1024 * 1024 * 1024;
113
114const AZURE_CPU_STEP_MILLICORES: i64 = 250;
117const AZURE_MAX_CPU_MILLICORES: i64 = 16_000;
118const AZURE_MEMORY_MIB_PER_CORE: i64 = 2 * 1024;
119const AZURE_DISK_MIB_PER_CORE: i64 = 20 * 1024;
120
121const MICROVM_TIERS: &[MicrovmTier] = &[
122 MicrovmTier {
123 baseline_memory_mib: 512,
124 peak_memory_mib: 2048,
125 peak_vcpu: 1,
126 max_disk_mib: 8192,
127 },
128 MicrovmTier {
129 baseline_memory_mib: 1024,
130 peak_memory_mib: 4096,
131 peak_vcpu: 2,
132 max_disk_mib: 8192,
133 },
134 MicrovmTier {
135 baseline_memory_mib: 2048,
136 peak_memory_mib: 8192,
137 peak_vcpu: 4,
138 max_disk_mib: 8192,
139 },
140 MicrovmTier {
141 baseline_memory_mib: 4096,
142 peak_memory_mib: 16384,
143 peak_vcpu: 8,
144 max_disk_mib: 16384,
145 },
146 MicrovmTier {
147 baseline_memory_mib: 8192,
148 peak_memory_mib: 32768,
149 peak_vcpu: 16,
150 max_disk_mib: 32768,
151 },
152];
153
154pub use super::sandbox_policy::{is_public_ipv4, non_public_ipv4_ranges, EgressPolicy};
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum SandboxEgress {
159 None,
160 Internet,
161 Allow,
163 AllowDomains {
165 domains: Vec<String>,
166 },
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
171#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
172#[serde(tag = "mode", rename_all = "camelCase", deny_unknown_fields)]
173pub enum LegacySandboxEgress {
174 Deny,
176 Allow,
179 AllowDomains { domains: Vec<String> },
182}
183
184#[derive(Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186enum SandboxEgressMode {
187 None,
188 Internet,
189}
190
191#[derive(Serialize, Deserialize)]
192#[serde(untagged)]
193enum SandboxEgressInput {
194 Mode(SandboxEgressMode),
195 Legacy(LegacySandboxEgress),
196}
197
198impl Serialize for SandboxEgress {
199 fn serialize<S: serde::Serializer>(
200 &self,
201 serializer: S,
202 ) -> std::result::Result<S::Ok, S::Error> {
203 match self {
204 Self::None => serializer.serialize_str("none"),
205 Self::Internet => serializer.serialize_str("internet"),
206 Self::Allow => LegacySandboxEgress::Allow.serialize(serializer),
207 Self::AllowDomains { domains } => LegacySandboxEgress::AllowDomains {
208 domains: domains.clone(),
209 }
210 .serialize(serializer),
211 }
212 }
213}
214
215impl<'de> Deserialize<'de> for SandboxEgress {
216 fn deserialize<D: serde::Deserializer<'de>>(
217 deserializer: D,
218 ) -> std::result::Result<Self, D::Error> {
219 Ok(match SandboxEgressInput::deserialize(deserializer)? {
220 SandboxEgressInput::Mode(SandboxEgressMode::None)
221 | SandboxEgressInput::Legacy(LegacySandboxEgress::Deny) => Self::None,
222 SandboxEgressInput::Mode(SandboxEgressMode::Internet) => Self::Internet,
223 SandboxEgressInput::Legacy(LegacySandboxEgress::Allow) => Self::Allow,
224 SandboxEgressInput::Legacy(LegacySandboxEgress::AllowDomains { domains }) => {
225 Self::AllowDomains { domains }
226 }
227 })
228 }
229}
230
231#[cfg(feature = "openapi")]
232impl utoipa::PartialSchema for SandboxEgress {
233 fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
234 use utoipa::openapi::schema::{ObjectBuilder, OneOfBuilder, Type};
235 OneOfBuilder::new()
236 .item(
237 ObjectBuilder::new()
238 .schema_type(Type::String)
239 .enum_values(Some(["none", "internet"])),
240 )
241 .item(LegacySandboxEgress::schema())
242 .into()
243 }
244}
245#[cfg(feature = "openapi")]
246impl utoipa::ToSchema for SandboxEgress {}
247
248impl SandboxEgress {
249 #[allow(non_upper_case_globals)]
251 #[deprecated(note = "use SandboxEgress::None")]
252 pub const Deny: Self = Self::None;
253
254 pub fn internet_access_switch(&self) -> Option<bool> {
259 match self {
260 Self::None | Self::Internet => Some(false),
261 Self::Allow => Some(true),
262 Self::AllowDomains { .. } => None,
263 }
264 }
265}
266
267pub const GCP_NO_GATEWAY_POLICY: &str = "this Google Cloud sandbox has no egress gateway, so it \
271takes no per-sandbox outbound policy: declare `internet` (and re-run setup) to use per-sandbox \
272host rules, or `none` to block all outbound traffic";
273
274pub const SANDBOX_EXPIRY_LABEL: &str = "alienExpiresAtMs";
276
277pub const SANDBOX_REQUEST_KEY_LABEL: &str = "alienRequestKey";
279
280pub const SANDBOX_REQUEST_KEY_MAX_LEN: usize = 64;
282
283pub fn is_valid_request_key(value: &str) -> bool {
286 !value.is_empty()
287 && value.len() <= SANDBOX_REQUEST_KEY_MAX_LEN
288 && value
289 .bytes()
290 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
291}
292
293pub fn is_valid_sandbox_expiry(value: &str) -> bool {
295 value.parse::<u64>().is_ok_and(|ms| ms > 0)
296}
297
298pub const AZURE_GATEWAY_MAX_LIFETIME_SECONDS: u32 = 24 * 60 * 60;
300
301#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
306#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
307#[serde(rename_all = "camelCase", deny_unknown_fields)]
308pub struct SandboxLifecyclePolicy {
309 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub max_lifetime_seconds: Option<u32>,
317 #[serde(alias = "idleSuspendSeconds", skip_serializing_if = "Option::is_none")]
321 pub idle_pause_seconds: Option<u32>,
322 #[serde(default, skip_serializing_if = "Option::is_none")]
327 pub on_pause: Option<Vec<String>>,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub on_resume: Option<Vec<String>>,
332}
333
334pub const GCP_PREVIEW_IS_COMMAND_ACCESS: &str = "On Google Cloud, preview access equals command access; port-scoped preview sharing is not available.";
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
345#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
346#[serde(rename_all = "camelCase", deny_unknown_fields)]
347pub struct SandboxCapabilities {
348 pub files: bool,
350 pub reconnect: bool,
352 pub jobs: bool,
355 pub interactive_commands: bool,
358 pub preview: bool,
360 pub pause_resume: bool,
362 pub snapshot: bool,
364 pub domain_egress_rules: bool,
366 pub egress_deny: bool,
369 pub enforced_limits: bool,
371 pub process_limit: bool,
373 pub sandbox_lifetime: bool,
375 pub supervisor_pid_namespace: bool,
381 pub supervisor_isolation: bool,
388}
389
390impl SandboxCapabilities {
391 pub fn for_platform(platform: Platform) -> Result<Self> {
397 match platform {
398 Platform::Aws => Ok(Self {
399 files: true,
400 reconnect: true,
401 jobs: true,
402 interactive_commands: true,
405 preview: true,
406 pause_resume: true,
407 snapshot: false,
408 domain_egress_rules: false,
409 egress_deny: true,
412 enforced_limits: true,
413 process_limit: false,
415 sandbox_lifetime: true,
418 supervisor_pid_namespace: false,
423 supervisor_isolation: true,
426 }),
427 Platform::Azure => Ok(Self::azure()),
428 Platform::Gcp => Ok(Self::gcp_agent_platform()),
429 Platform::Kubernetes => Ok(Self {
430 files: true,
431 reconnect: true,
432 jobs: true,
433 interactive_commands: true,
438 preview: true,
444 pause_resume: false,
447 snapshot: false,
449 domain_egress_rules: false,
450 egress_deny: true,
451 enforced_limits: true,
452 process_limit: false,
457 sandbox_lifetime: true,
463 supervisor_pid_namespace: false,
467 supervisor_isolation: true,
473 }),
474 Platform::Local => Ok(Self {
475 files: true,
476 reconnect: true,
477 jobs: false,
479 interactive_commands: true,
482 preview: true,
483 pause_resume: false,
484 snapshot: false,
485 domain_egress_rules: false,
486 egress_deny: true,
487 enforced_limits: true,
488 process_limit: true,
490 sandbox_lifetime: true,
492 supervisor_pid_namespace: false,
495 supervisor_isolation: true,
499 }),
500 Platform::Machines | Platform::Test => {
501 Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
502 platform: platform.to_string(),
503 }))
504 }
505 }
506 }
507
508 pub fn azure() -> Self {
510 Self {
511 files: true,
512 reconnect: true,
513 jobs: true,
516 interactive_commands: true,
520 preview: true,
527 pause_resume: true,
528 snapshot: false,
532 domain_egress_rules: true,
533 egress_deny: true,
534 enforced_limits: true,
538 process_limit: false,
539 sandbox_lifetime: true,
544 supervisor_pid_namespace: false,
546 supervisor_isolation: false,
549 }
550 }
551
552 pub fn gcp_agent_platform() -> Self {
554 Self {
555 files: true,
557 reconnect: true,
561 jobs: true,
562 interactive_commands: false,
565 preview: true,
571 pause_resume: true,
577 snapshot: false,
580 domain_egress_rules: false,
582 egress_deny: true,
585 enforced_limits: true,
589 process_limit: false,
591 sandbox_lifetime: true,
593 supervisor_pid_namespace: false,
595 supervisor_isolation: false,
598 }
599 }
600
601 pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
603 let available = match capability {
604 SandboxCapability::Files => self.files,
605 SandboxCapability::Reconnect => self.reconnect,
606 SandboxCapability::Jobs => self.jobs,
607 SandboxCapability::InteractiveCommands => self.interactive_commands,
608 SandboxCapability::Preview => self.preview,
609 SandboxCapability::PauseResume => self.pause_resume,
610 SandboxCapability::Snapshot => self.snapshot,
611 SandboxCapability::DomainEgressRules => self.domain_egress_rules,
612 SandboxCapability::EgressDeny => self.egress_deny,
613 SandboxCapability::EnforcedLimits => self.enforced_limits,
614 SandboxCapability::ProcessLimit => self.process_limit,
615 SandboxCapability::SandboxLifetime => self.sandbox_lifetime,
616 SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
617 SandboxCapability::SupervisorIsolation => self.supervisor_isolation,
618 };
619
620 if available {
621 return Ok(());
622 }
623
624 Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
625 capability: capability.as_str().to_string(),
626 platform: platform.to_string(),
627 }))
628 }
629}
630
631#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
633#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
634#[serde(rename_all = "camelCase")]
635pub enum SandboxCapability {
636 Files,
638 Reconnect,
640 Jobs,
642 InteractiveCommands,
644 Preview,
646 PauseResume,
648 Snapshot,
650 DomainEgressRules,
652 EgressDeny,
654 EnforcedLimits,
656 ProcessLimit,
658 SandboxLifetime,
660 SupervisorPidNamespace,
662 SupervisorIsolation,
664}
665
666impl SandboxCapability {
667 pub fn as_str(&self) -> &'static str {
669 match self {
670 Self::Files => "files",
671 Self::Reconnect => "reconnect",
672 Self::Jobs => "jobs",
673 Self::InteractiveCommands => "interactiveCommands",
674 Self::Preview => "preview",
675 Self::PauseResume => "pauseResume",
676 Self::Snapshot => "snapshot",
677 Self::DomainEgressRules => "domainEgressRules",
678 Self::EgressDeny => "egressDeny",
679 Self::EnforcedLimits => "enforcedLimits",
680 Self::ProcessLimit => "processLimit",
681 Self::SandboxLifetime => "sandboxLifetime",
682 Self::SupervisorPidNamespace => "supervisorPidNamespace",
683 Self::SupervisorIsolation => "supervisorIsolation",
684 }
685 }
686}
687
688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
690#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
691#[serde(rename_all = "camelCase", deny_unknown_fields)]
692pub struct SandboxPrivilegedSupervisor {
693 pub command_uid: u32,
695}
696
697#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
699#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
700#[serde(rename_all = "camelCase", deny_unknown_fields)]
701#[builder(start_fn = new)]
702pub struct Sandbox {
703 #[builder(start_fn)]
706 pub id: String,
707 #[builder(field)]
710 #[serde(default, skip_serializing_if = "Vec::is_empty")]
711 #[cfg_attr(feature = "openapi", schema(ignore))]
712 pub links: Vec<ResourceRef>,
713 #[builder(field)]
718 #[serde(default, skip_serializing_if = "Vec::is_empty")]
719 pub gateway_links: Vec<ResourceRef>,
720 pub code: SandboxCode,
722 #[builder(skip)]
725 #[serde(default, skip_serializing_if = "Option::is_none")]
726 #[cfg_attr(feature = "openapi", schema(ignore))]
727 pub image_user: Option<u32>,
728 #[serde(skip_serializing_if = "Option::is_none")]
732 pub private_base_image: Option<String>,
733 #[serde(skip_serializing_if = "Option::is_none")]
739 pub limits: Option<SandboxLimits>,
740 pub egress: SandboxEgress,
742 #[serde(default, skip_serializing_if = "Option::is_none")]
744 pub default_policy: Option<EgressPolicy>,
745 #[builder(skip)]
749 #[serde(default, skip_serializing_if = "Option::is_none")]
750 pub privileged_supervisor: Option<SandboxPrivilegedSupervisor>,
751 #[serde(default, skip_serializing_if = "Option::is_none")]
755 pub image_permissions: Option<SandboxImagePermissions>,
756 #[serde(alias = "session")]
761 pub lifecycle: SandboxLifecyclePolicy,
762 #[builder(default)]
766 #[serde(default, skip_serializing_if = "Vec::is_empty")]
767 pub preview_ports: Vec<u16>,
768}
769
770impl<S: sandbox_builder::State> SandboxBuilder<S> {
771 pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
774 where
775 for<'a> &'a R: Into<ResourceRef>,
776 {
777 let resource_ref: ResourceRef = resource.into();
778 if !self.gateway_links.contains(&resource_ref) {
779 self.gateway_links.push(resource_ref);
780 }
781 self
782 }
783}
784
785pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
790 !targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
791}
792
793pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
799 stack.resources().any(|(_, entry)| {
800 entry
801 .config
802 .downcast_ref::<Sandbox>()
803 .is_some_and(|sandbox| crate::sandbox_egress::sandbox_needs_connector(stack, sandbox))
804 })
805}
806
807impl Sandbox {
808 pub fn needs_gcp_edge_signer(&self) -> bool {
812 !self.preview_ports.is_empty() || self.egress == SandboxEgress::Internet
813 }
814
815 pub(crate) fn setup_digest_value(&self) -> serde_json::Value {
816 match &self.egress {
817 SandboxEgress::None => serde_json::json!({"mode":"deny"}),
818 value => serde_json::to_value(value).expect("egress serializes"),
819 }
820 }
821
822 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
824
825 pub fn id(&self) -> &str {
827 &self.id
828 }
829
830 pub fn cloud_egress(&self) -> &SandboxEgress {
833 if self.privileged_supervisor.is_some() && self.egress != SandboxEgress::Internet {
834 &SandboxEgress::Allow
835 } else {
836 &self.egress
837 }
838 }
839
840 pub fn supervisor_environment(&self) -> std::collections::BTreeMap<String, String> {
842 let mut env = std::collections::BTreeMap::new();
843 if let Some(supervisor) = &self.privileged_supervisor {
844 env.insert(
845 "ALIEN_SANDBOX_EXPECTED_EXEC_UID".to_string(),
846 supervisor.command_uid.to_string(),
847 );
848 env.insert(
849 "ALIEN_SANDBOX_EGRESS".to_string(),
850 if self.egress == SandboxEgress::None {
852 r#"{"mode":"deny"}"#.to_string()
853 } else {
854 serde_json::to_string(&self.egress).expect("egress serializes")
855 },
856 );
857 }
858 env
859 }
860
861 pub fn resolved_limits(&self) -> SandboxLimits {
867 self.limits.clone().unwrap_or_else(default_limits)
868 }
869
870 pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
875 if let Some(policy) = &self.default_policy {
876 if self.egress != SandboxEgress::Internet {
877 return Err(AlienError::new(ErrorData::SandboxEgressInvalid {
878 target: "defaultPolicy".into(),
879 reason: "defaultPolicy requires the new internet declaration".into(),
880 }));
881 }
882 policy.validate()?;
883 }
884 if self.image_user == Some(0) && platform == Platform::Local {
885 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
886 capability: "root image USER: this backend does not yet separate bounded root boot from non-root exec; use a non-root image USER".into(),
887 platform: platform.to_string(),
888 }));
889 }
890 if self.image_user == Some(0)
894 && platform == Platform::Kubernetes
895 && !matches!(self.egress, SandboxEgress::Internet | SandboxEgress::None)
896 {
897 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
898 capability: "root image USER with this egress mode: a root image on Kubernetes needs egress `internet` or `none`, because `allow` and `allowDomains` have no enforcement outside the pod".into(),
899 platform: platform.to_string(),
900 }));
901 }
902 let mut capabilities = SandboxCapabilities::for_platform(platform)?;
903 self.validate_image_permissions(platform)?;
904 if let Some(supervisor) = &self.privileged_supervisor {
905 if platform != Platform::Aws {
906 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
907 capability: "privilegedSupervisor".to_string(),
908 platform: platform.to_string(),
909 }));
910 }
911 if supervisor.command_uid == 0 || supervisor.command_uid == u32::MAX {
912 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
913 resource_id: self.id.clone(),
914 field: "privilegedSupervisor.commandUid".to_string(),
915 value: supervisor.command_uid.to_string(),
916 reason: "must be a non-root Linux uid other than the invalid uid sentinel"
917 .to_string(),
918 }));
919 }
920 if let SandboxEgress::AllowDomains { domains } = &self.egress {
921 for domain in domains {
922 let hostname = domain.strip_suffix('.').unwrap_or(domain);
923 if hostname.len() > 253
924 || !hostname.split('.').all(|label| {
925 !label.is_empty()
926 && label.len() <= 63
927 && label
928 .bytes()
929 .all(|c| c.is_ascii_alphanumeric() || c == b'-')
930 && !label.starts_with('-')
931 && !label.ends_with('-')
932 })
933 {
934 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
935 resource_id: self.id.clone(), field: "egress.domains".to_string(), value: domain.clone(),
936 reason: "privileged supervisor allowlists require exact DNS hostnames; wildcards are unsupported".to_string(),
937 }));
938 }
939 }
940 }
941 capabilities.domain_egress_rules = true;
942 }
943
944 if matches!(&self.code, SandboxCode::Source { .. })
949 && !matches!(
950 platform,
951 Platform::Aws | Platform::Azure | Platform::Gcp | Platform::Kubernetes
952 )
953 {
954 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
955 resource_id: self.id.clone(),
956 field: "code".to_string(),
957 value: "source".to_string(),
958 reason: format!(
959 "no sandbox backend builds an image from source on {platform}; give \
960 code.image a prebuilt reference"
961 ),
962 }));
963 }
964
965 if self.private_base_image.is_some() && platform != Platform::Aws {
968 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
969 capability: "privateBaseImage".to_string(),
970 platform: platform.to_string(),
971 }));
972 }
973
974 if platform == Platform::Azure && matches!(&self.code, SandboxCode::Image { .. }) {
977 self.azure_image()?;
978 }
979
980 if let Some(seconds) = self.lifecycle.max_lifetime_seconds {
983 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
985
986 if seconds == 0 {
987 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
988 resource_id: self.id.clone(),
989 field: "maxLifetimeSeconds".to_string(),
990 value: "0".to_string(),
991 reason: "a sandbox must be allowed to run for at least 1 second".to_string(),
992 }));
993 }
994
995 let ceiling = match platform {
1000 Platform::Aws => Some((AWS_MAX_LIFETIME_SECONDS, "AWS runs a MicroVM for")),
1001 Platform::Kubernetes => {
1002 Some((KUBERNETES_MAX_LIFETIME_SECONDS, "Kubernetes runs a pod for"))
1003 }
1004 Platform::Gcp => None,
1007 Platform::Azure | Platform::Local | Platform::Machines | Platform::Test => None,
1010 };
1011 if let Some((max, runs_for)) = ceiling {
1012 if seconds > max {
1013 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1014 resource_id: self.id.clone(),
1015 field: "maxLifetimeSeconds".to_string(),
1016 value: seconds.to_string(),
1017 reason: format!("{runs_for} between 1 and {max} seconds"),
1018 }));
1019 }
1020 }
1021 }
1022
1023 let Some(limits) = self.limits.as_ref() else {
1024 return self.validate_capabilities(&capabilities, platform);
1026 };
1027
1028 validate_quantity(&self.id, "cpu", &limits.cpu)?;
1029 validate_quantity(&self.id, "memory", &limits.memory)?;
1030 validate_quantity(&self.id, "disk", &limits.disk)?;
1031
1032 if let Some(max_processes) = limits.max_processes {
1033 if max_processes == 0 {
1034 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1035 resource_id: self.id.clone(),
1036 field: "maxProcesses".to_string(),
1037 value: "0".to_string(),
1038 reason: "a sandbox that may run no processes cannot run code".to_string(),
1039 }));
1040 }
1041 capabilities.require(SandboxCapability::ProcessLimit, platform)?;
1042 }
1043
1044 capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
1047
1048 if platform == Platform::Azure {
1049 self.azure_sandbox_limits()?;
1050 }
1051
1052 if platform == Platform::Gcp {
1053 self.gcp_sandbox_limits()?;
1054 }
1055
1056 if platform == Platform::Aws {
1057 self.microvm_tier()?;
1060 }
1061
1062 self.validate_capabilities(&capabilities, platform)
1063 }
1064
1065 pub fn declares_image_permissions(&self) -> bool {
1068 self.image_permissions.is_some()
1069 || self.lifecycle.on_pause.is_some()
1070 || self.lifecycle.on_resume.is_some()
1071 }
1072
1073 fn validate_image_permissions(&self, platform: Platform) -> Result<()> {
1077 if let Some(permissions) = &self.image_permissions {
1078 sandbox_image_permissions::require_image_permissions_platform(
1079 "imagePermissions",
1080 platform,
1081 )?;
1082 permissions.validate(&self.id)?;
1083 }
1084 for (field, argv) in [
1085 ("onPause", &self.lifecycle.on_pause),
1086 ("onResume", &self.lifecycle.on_resume),
1087 ] {
1088 if let Some(argv) = argv {
1089 sandbox_image_permissions::require_image_permissions_platform(field, platform)?;
1090 sandbox_image_permissions::validate_lifecycle_argv(
1091 &self.id,
1092 field,
1093 argv,
1094 self.image_permissions
1095 .as_ref()
1096 .map(|permissions| &permissions.mounts[..])
1097 .unwrap_or_default(),
1098 )?;
1099 }
1100 }
1101 if self.declares_image_permissions() && self.privileged_supervisor.is_some() {
1102 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1103 resource_id: self.id.clone(),
1104 field: "imagePermissions".to_string(),
1105 value: "privilegedSupervisor".to_string(),
1106 reason: "image permissions and lifecycle steps need the root image boot, not the \
1107 released privileged supervisor"
1108 .to_string(),
1109 }));
1110 }
1111 if self.declares_image_permissions()
1114 && !matches!(self.egress, SandboxEgress::Internet | SandboxEgress::None)
1115 {
1116 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1117 resource_id: self.id.clone(),
1118 field: "egress".to_string(),
1119 value: match self.egress {
1120 SandboxEgress::Allow => "allow",
1121 _ => "allowDomains",
1122 }
1123 .to_string(),
1124 reason: "image permissions and lifecycle steps need egress `internet` or `none`"
1125 .to_string(),
1126 }));
1127 }
1128 if self.declares_image_permissions() && self.image_user.is_some_and(|uid| uid != 0) {
1129 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1130 resource_id: self.id.clone(),
1131 field: "imagePermissions".to_string(),
1132 value: "image USER".to_string(),
1133 reason: "image permissions and lifecycle steps need an image whose command \
1134 starts as root (USER root or no USER)"
1135 .to_string(),
1136 }));
1137 }
1138 Ok(())
1139 }
1140
1141 pub fn azure_image(&self) -> Result<AzureSandboxImage<'_>> {
1145 let SandboxCode::Image { image, .. } = &self.code else {
1146 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1147 resource_id: self.id.clone(),
1148 field: "code".to_string(),
1149 value: "source".to_string(),
1150 reason: "the sandbox still has unbuilt source code. Run 'alien build' first"
1151 .to_string(),
1152 }));
1153 };
1154
1155 classify_azure_sandbox_image(image).ok_or_else(|| {
1156 let image = image.trim();
1157 AlienError::new(ErrorData::SandboxLimitInvalid {
1158 resource_id: self.id.clone(),
1159 field: "code.image".to_string(),
1160 value: image.to_string(),
1161 reason: if image.is_empty() {
1162 "a sandbox has to name an image".to_string()
1163 } else {
1164 "Azure creates a sandbox from a catalog name such as 'ubuntu' or from a \
1165 registry image such as 'docker.io/library/python:3.14-slim'"
1166 .to_string()
1167 },
1168 })
1169 })
1170 }
1171
1172 pub fn gcp_sandbox_limits(&self) -> Result<()> {
1175 let Some(limits) = self.limits.as_ref() else {
1176 return Ok(());
1177 };
1178 let over_cap =
1179 quantity_exceeds_bytes(&limits.disk, GCP_MAX_DISK_BYTES).ok_or_else(|| {
1180 AlienError::new(ErrorData::SandboxLimitInvalid {
1181 resource_id: self.id.clone(),
1182 field: "disk".to_string(),
1183 value: limits.disk.clone(),
1184 reason: "expected a size such as 8Gi".to_string(),
1185 })
1186 })?;
1187 if over_cap {
1188 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1189 resource_id: self.id.clone(),
1190 field: "disk".to_string(),
1191 value: limits.disk.clone(),
1192 reason: "GCP Agent Platform caps a sandbox's ephemeral storage at 10Gi; declare \
1193 10Gi or less"
1194 .to_string(),
1195 }));
1196 }
1197 Ok(())
1198 }
1199
1200 pub fn azure_sandbox_limits(&self) -> Result<()> {
1204 let Some(limits) = self.limits.as_ref() else {
1205 return Ok(());
1208 };
1209
1210 let refused = |field: &str, value: &str, reason: &str| {
1211 AlienError::new(ErrorData::SandboxLimitInvalid {
1212 resource_id: self.id.clone(),
1213 field: field.to_string(),
1214 value: value.to_string(),
1215 reason: reason.to_string(),
1216 })
1217 };
1218
1219 let cpu_millicores = millicores(&limits.cpu)
1220 .ok_or_else(|| refused("cpu", &limits.cpu, "expected cores or millicores"))?;
1221
1222 if cpu_millicores % AZURE_CPU_STEP_MILLICORES != 0
1226 || !(AZURE_CPU_STEP_MILLICORES..=AZURE_MAX_CPU_MILLICORES).contains(&cpu_millicores)
1227 {
1228 return Err(refused(
1229 "cpu",
1230 &limits.cpu,
1231 "Azure allocates cpu in steps of 250m from 250m to 16000m",
1232 ));
1233 }
1234
1235 let memory_ceiling_mib = cpu_millicores * AZURE_MEMORY_MIB_PER_CORE / 1000;
1237 let disk_ceiling_mib = cpu_millicores * AZURE_DISK_MIB_PER_CORE / 1000;
1238
1239 let memory_mib = quantity_mib(&limits.memory)
1240 .ok_or_else(|| refused("memory", &limits.memory, "Azure sizes memory in whole MiB"))?;
1241 if memory_mib > memory_ceiling_mib {
1242 return Err(refused(
1243 "memory",
1244 &limits.memory,
1245 &format!(
1246 "Azure allows at most 2Gi of memory per core, or {memory_ceiling_mib}Mi \
1247 at the declared cpu"
1248 ),
1249 ));
1250 }
1251
1252 let disk_mib = quantity_mib(&limits.disk)
1253 .ok_or_else(|| refused("disk", &limits.disk, "Azure sizes disk in whole MiB"))?;
1254 if disk_mib > disk_ceiling_mib {
1255 return Err(refused(
1256 "disk",
1257 &limits.disk,
1258 &format!(
1259 "Azure allows at most 20Gi of disk per core, or {disk_ceiling_mib}Mi at \
1260 the declared cpu"
1261 ),
1262 ));
1263 }
1264
1265 Ok(())
1266 }
1267
1268 pub fn microvm_tier(&self) -> Result<MicrovmTier> {
1275 let Some(limits) = self.limits.as_ref() else {
1276 return Ok(MICROVM_TIERS[2]);
1280 };
1281
1282 let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
1283 AlienError::new(ErrorData::SandboxLimitInvalid {
1284 resource_id: self.id.clone(),
1285 field: "memory".to_string(),
1286 value: limits.memory.clone(),
1287 reason: "AWS sizes a MicroVM in whole MiB".to_string(),
1288 })
1289 })?;
1290 let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
1291 AlienError::new(ErrorData::SandboxLimitInvalid {
1292 resource_id: self.id.clone(),
1293 field: "disk".to_string(),
1294 value: limits.disk.clone(),
1295 reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
1296 })
1297 })?;
1298 let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
1299 AlienError::new(ErrorData::SandboxLimitInvalid {
1300 resource_id: self.id.clone(),
1301 field: "cpu".to_string(),
1302 value: limits.cpu.clone(),
1303 reason: "expected cores or millicores".to_string(),
1304 })
1305 })?;
1306
1307 let sized = |tier: &&MicrovmTier| {
1312 tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
1313 };
1314
1315 let tier = MICROVM_TIERS
1316 .iter()
1317 .rev()
1318 .find(sized)
1319 .copied()
1320 .ok_or_else(|| {
1321 AlienError::new(ErrorData::SandboxLimitInvalid {
1322 resource_id: self.id.clone(),
1323 field: "memory".to_string(),
1324 value: limits.memory.clone(),
1325 reason: format!(
1326 "a Lambda MicroVM bursts to four times its baseline, so the smallest \
1327 ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
1328 disk fit no size",
1329 limits.memory, limits.disk
1330 ),
1331 })
1332 })?;
1333
1334 let required_millicores = i64::from(tier.peak_vcpu) * 1000;
1335 if cpu_millicores < required_millicores {
1336 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1337 resource_id: self.id.clone(),
1338 field: "cpu".to_string(),
1339 value: limits.cpu.clone(),
1340 reason: format!(
1341 "AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
1342 reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
1343 limits.memory, tier.peak_vcpu, tier.peak_vcpu
1344 ),
1345 }));
1346 }
1347
1348 Ok(tier)
1349 }
1350
1351 fn validate_capabilities(
1353 &self,
1354 capabilities: &SandboxCapabilities,
1355 platform: Platform,
1356 ) -> Result<()> {
1357 if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
1358 capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
1359 }
1360
1361 if let SandboxEgress::AllowDomains { domains } = &self.egress {
1367 if domains.is_empty() {
1368 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1369 resource_id: self.id.clone(),
1370 field: "egress.domains".to_string(),
1371 value: "[]".to_string(),
1372 reason: "an allowlist naming no domain denies everything; declare \
1373 egress: deny if that is what was meant"
1374 .to_string(),
1375 }));
1376 }
1377 }
1378
1379 if matches!(self.egress, SandboxEgress::None) {
1380 capabilities.require(SandboxCapability::EgressDeny, platform)?;
1381 }
1382
1383 if platform == Platform::Gcp
1386 && self
1387 .preview_ports
1388 .contains(&crate::sandbox_image::GCP_AGENT_PLATFORM.port)
1389 {
1390 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1391 resource_id: self.id.clone(),
1392 field: "previewPorts".to_string(),
1393 value: crate::sandbox_image::GCP_AGENT_PLATFORM.port.to_string(),
1394 reason: "that port is the Alien agent's own on GCP Agent Platform; choose \
1395 another port for the workload"
1396 .to_string(),
1397 }));
1398 }
1399
1400 if !self.preview_ports.is_empty() {
1401 capabilities.require(SandboxCapability::Preview, platform)?;
1402 if platform == Platform::Azure
1403 && matches!(self.azure_image(), Ok(AzureSandboxImage::Catalog(_)))
1404 {
1405 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1406 capability:
1407 "preview (a catalog image runs without the Alien agent that issues \
1408 the capability; build the sandbox from source)"
1409 .to_string(),
1410 platform: platform.to_string(),
1411 }));
1412 }
1413 }
1414
1415 if self.lifecycle.idle_pause_seconds.is_some() {
1416 if platform == Platform::Gcp {
1419 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1420 capability: "idle pause policy: the GCP Agent Platform backend has no idle policy and Alien does not watch for idleness there; remove the idle policy and pause the sandbox explicitly".to_string(),
1421 platform: platform.to_string(),
1422 }));
1423 }
1424 capabilities.require(SandboxCapability::PauseResume, platform)?;
1425 }
1426
1427 if self.lifecycle.max_lifetime_seconds.is_some() {
1428 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
1429 }
1430
1431 Ok(())
1432 }
1433}
1434
1435fn default_limits() -> SandboxLimits {
1440 SandboxLimits {
1441 cpu: "1".to_string(),
1442 memory: "2Gi".to_string(),
1443 disk: "8Gi".to_string(),
1444 max_processes: None,
1445 }
1446}
1447
1448fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
1450 let invalid = |reason: &str| {
1451 AlienError::new(ErrorData::SandboxLimitInvalid {
1452 resource_id: resource_id.to_string(),
1453 field: field.to_string(),
1454 value: value.to_string(),
1455 reason: reason.to_string(),
1456 })
1457 };
1458
1459 let digits_end = value
1460 .find(|c: char| !c.is_ascii_digit() && c != '.')
1461 .unwrap_or(value.len());
1462 let (number, suffix) = value.split_at(digits_end);
1463
1464 let parsed: f64 = number
1465 .parse()
1466 .map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
1467
1468 if parsed <= 0.0 {
1469 return Err(invalid("must be greater than zero"));
1470 }
1471
1472 const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
1473 if !SUFFIXES.contains(&suffix) {
1474 return Err(invalid(
1475 "unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
1476 ));
1477 }
1478
1479 Ok(())
1480}
1481
1482fn split_quantity(value: &str) -> Option<(f64, &str)> {
1484 let trimmed = value.trim();
1485 let digits_end = trimmed
1486 .find(|c: char| !c.is_ascii_digit() && c != '.')
1487 .unwrap_or(trimmed.len());
1488 let (number, suffix) = trimmed.split_at(digits_end);
1489 number.parse().ok().map(|number| (number, suffix))
1490}
1491
1492pub fn quantity_mib(value: &str) -> Option<i64> {
1498 let (number, suffix) = split_quantity(value)?;
1499 let bytes = match suffix {
1500 "" => number,
1501 "k" => number * 1e3,
1502 "M" => number * 1e6,
1503 "G" => number * 1e9,
1504 "T" => number * 1e12,
1505 "Ki" => number * 1024.0,
1506 "Mi" => number * 1024.0 * 1024.0,
1507 "Gi" => number * 1024.0 * 1024.0 * 1024.0,
1508 "Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
1509 _ => return None,
1511 };
1512 Some((bytes / (1024.0 * 1024.0)) as i64)
1513}
1514
1515fn quantity_exceeds_bytes(value: &str, cap_bytes: u128) -> Option<bool> {
1518 let trimmed = value.trim();
1519 let digits_end = trimmed
1520 .find(|c: char| !c.is_ascii_digit() && c != '.')
1521 .unwrap_or(trimmed.len());
1522 let (number, suffix) = trimmed.split_at(digits_end);
1523 let unit: u128 = match suffix {
1524 "" => 1,
1525 "k" => 1_000,
1526 "M" => 1_000_000,
1527 "G" => 1_000_000_000,
1528 "T" => 1_000_000_000_000,
1529 "Ki" => 1 << 10,
1530 "Mi" => 1 << 20,
1531 "Gi" => 1 << 30,
1532 "Ti" => 1 << 40,
1533 _ => return None,
1534 };
1535 let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
1536 if (whole.is_empty() && fraction.is_empty()) || fraction.contains('.') {
1537 return None;
1538 }
1539 let digits = format!("{whole}{fraction}");
1540 let scale = 10u128.checked_pow(u32::try_from(fraction.len()).ok()?)?;
1541 let mantissa: u128 = digits.parse().ok()?;
1542 Some(mantissa.checked_mul(unit)? > cap_bytes.checked_mul(scale)?)
1544}
1545
1546pub fn millicores(value: &str) -> Option<i64> {
1548 let (number, suffix) = split_quantity(value)?;
1549 match suffix {
1550 "" => Some((number * 1000.0) as i64),
1551 "m" => Some(number as i64),
1552 _ => None,
1553 }
1554}
1555
1556#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1558#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1559#[serde(rename_all = "camelCase")]
1560pub struct SandboxOutputs {
1561 pub parent_name: String,
1563 #[serde(skip_serializing_if = "Option::is_none")]
1565 pub identifier: Option<String>,
1566 #[serde(skip_serializing_if = "Option::is_none")]
1568 pub endpoint: Option<String>,
1569}
1570
1571impl ResourceOutputsDefinition for SandboxOutputs {
1572 fn get_resource_type(&self) -> ResourceType {
1573 Sandbox::RESOURCE_TYPE
1574 }
1575
1576 fn as_any(&self) -> &dyn Any {
1577 self
1578 }
1579
1580 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
1581 Box::new(self.clone())
1582 }
1583
1584 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
1585 other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
1586 }
1587
1588 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1589 serde_json::to_value(self)
1590 }
1591}
1592
1593impl ResourceDefinition for Sandbox {
1594 fn get_resource_type(&self) -> ResourceType {
1595 Self::RESOURCE_TYPE
1596 }
1597
1598 fn id(&self) -> &str {
1599 &self.id
1600 }
1601
1602 fn replace_after_failed_create_is_safe(&self) -> bool {
1603 false
1606 }
1607
1608 fn get_dependencies(&self) -> Vec<ResourceRef> {
1611 self.image_permissions
1612 .iter()
1613 .flat_map(|permissions| &permissions.connections)
1614 .map(|connection| connection.to.clone())
1615 .collect()
1616 }
1617
1618 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1619 let new_sandbox = new_config
1620 .as_any()
1621 .downcast_ref::<Sandbox>()
1622 .ok_or_else(|| {
1623 AlienError::new(ErrorData::UnexpectedResourceType {
1624 resource_id: self.id.clone(),
1625 expected: Self::RESOURCE_TYPE,
1626 actual: new_config.get_resource_type(),
1627 })
1628 })?;
1629
1630 if self.id != new_sandbox.id {
1631 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1632 resource_id: self.id.clone(),
1633 reason: "the 'id' field is immutable".to_string(),
1634 }));
1635 }
1636
1637 Ok(())
1638 }
1639
1640 fn as_any(&self) -> &dyn Any {
1641 self
1642 }
1643
1644 fn as_any_mut(&mut self) -> &mut dyn Any {
1645 self
1646 }
1647
1648 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1649 Box::new(self.clone())
1650 }
1651
1652 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1653 other.as_any().downcast_ref::<Sandbox>() == Some(self)
1654 }
1655
1656 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1657 serde_json::to_value(self)
1658 }
1659}
1660
1661#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1663pub enum AzureSandboxImage<'a> {
1664 Catalog(&'a str),
1666 Registry(&'a str),
1669}
1670
1671impl<'a> AzureSandboxImage<'a> {
1672 pub fn as_str(&self) -> &'a str {
1674 match self {
1675 Self::Catalog(value) | Self::Registry(value) => value,
1676 }
1677 }
1678}
1679
1680pub const AZURE_DISK_IMAGE_LABEL: &str = "alienImage";
1682
1683pub fn classify_azure_sandbox_image(image: &str) -> Option<AzureSandboxImage<'_>> {
1687 let image = image.trim();
1688 if image.is_empty() {
1689 return None;
1690 }
1691 if image
1692 .chars()
1693 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1694 {
1695 return Some(AzureSandboxImage::Catalog(image));
1696 }
1697 (image.contains(|c| matches!(c, '/' | ':' | '@')) && OCI_REFERENCE.is_match(image))
1698 .then_some(AzureSandboxImage::Registry(image))
1699}
1700
1701pub fn azure_disk_image_label(reference: &str) -> String {
1704 let digest = format!("{:x}", Sha256::digest(reference.trim().as_bytes()));
1705 digest[..32].to_string()
1706}
1707
1708static OCI_REFERENCE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1710 let domain_component = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
1711 let domain = format!(r"{domain_component}(?:\.{domain_component})*(?::[0-9]+)?");
1712 let path_component = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
1713 let name = format!(r"(?:{domain}/)?{path_component}(?:/{path_component})*");
1714 let tag = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}";
1715 let digest = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
1716 regex::Regex::new(&format!(r"^{name}(?::{tag})?(?:@{digest})?$"))
1717 .expect("the OCI reference grammar compiles")
1718});
1719
1720pub const BUNDLE_REGION_TOKEN: &str = "{region}";
1725
1726#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1728pub enum BundleUri<'a> {
1729 Literal(&'a str),
1731 Regional { before: &'a str, after: &'a str },
1734}
1735
1736pub fn stable_bundle_key_prefix(key: &str) -> Option<&str> {
1740 let (above_file, _) = key.rsplit_once('/')?;
1741 let (above_version, _) = above_file.rsplit_once('/')?;
1742 Some(above_version)
1743}
1744
1745pub fn parse_bundle_uri(uri: &str) -> std::result::Result<BundleUri<'_>, String> {
1751 let path = uri
1752 .strip_prefix("s3://")
1753 .ok_or_else(|| format!("'{uri}' is not an s3:// URI"))?;
1754 let (bucket, key) = path
1755 .split_once('/')
1756 .ok_or_else(|| format!("'{uri}' names a bucket with no object key"))?;
1757
1758 if path.contains('*') || path.contains('?') {
1762 return Err(format!(
1763 "'{uri}' carries an IAM wildcard; the bundle's path is interpolated into the build \
1764 role's grant, so '*' and '?' would widen it past the bundle"
1765 ));
1766 }
1767
1768 if key.contains('{') || key.contains('}') {
1769 return Err(format!(
1770 "'{uri}' places a token in the object key; {BUNDLE_REGION_TOKEN} is accepted in the \
1771 bucket name alone"
1772 ));
1773 }
1774
1775 let Some((before, after)) = bucket.split_once(BUNDLE_REGION_TOKEN) else {
1776 if bucket.contains('{') || bucket.contains('}') {
1777 return Err(format!(
1778 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the \
1779 only one"
1780 ));
1781 }
1782 return Ok(BundleUri::Literal(uri));
1783 };
1784
1785 if after.contains(BUNDLE_REGION_TOKEN) {
1786 return Err(format!("'{uri}' repeats {BUNDLE_REGION_TOKEN}"));
1787 }
1788 if before.contains('{') || before.contains('}') || after.contains('{') || after.contains('}') {
1789 return Err(format!(
1790 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the only one"
1791 ));
1792 }
1793
1794 Ok(BundleUri::Regional {
1795 before: &uri[.."s3://".len() + before.len()],
1796 after: &uri["s3://".len() + before.len() + BUNDLE_REGION_TOKEN.len()..],
1797 })
1798}
1799
1800#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1802pub enum EcrImageRegion<'a> {
1803 Literal(&'a str),
1805 Deployment,
1807}
1808
1809#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1811pub struct EcrImageRepository<'a> {
1812 pub account_id: &'a str,
1813 pub region: EcrImageRegion<'a>,
1814 pub repository: &'a str,
1816}
1817
1818impl EcrImageRepository<'_> {
1819 pub fn arn(&self, partition: &str, region: &str) -> String {
1822 let region = match self.region {
1823 EcrImageRegion::Literal(region) => region,
1824 EcrImageRegion::Deployment => region,
1825 };
1826 format!(
1827 "arn:{partition}:ecr:{region}:{}:repository/{}",
1828 self.account_id, self.repository
1829 )
1830 }
1831}
1832
1833pub fn parse_ecr_image_repository(
1839 image: &str,
1840) -> std::result::Result<EcrImageRepository<'_>, String> {
1841 let refuse = |reason: &str| format!("privateBaseImage '{image}' {reason}");
1842 let (host, path) = image
1843 .split_once('/')
1844 .ok_or_else(|| refuse("names no repository"))?;
1845 let (account_id, rest) = host.split_once(".dkr.ecr.").ok_or_else(|| {
1846 refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)")
1847 })?;
1848 let region = rest
1850 .strip_suffix(".amazonaws.com.cn")
1851 .or_else(|| rest.strip_suffix(".amazonaws.com"))
1852 .ok_or_else(|| refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)"))?;
1853 if account_id.len() != 12 || !account_id.bytes().all(|b| b.is_ascii_digit()) {
1854 return Err(refuse("names no 12-digit account in its registry host"));
1855 }
1856 let region = if region == BUNDLE_REGION_TOKEN {
1857 EcrImageRegion::Deployment
1858 } else if !region.is_empty()
1859 && region
1860 .bytes()
1861 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1862 {
1863 EcrImageRegion::Literal(region)
1864 } else {
1865 return Err(refuse(&format!(
1866 "names no region in its registry host; give one or {BUNDLE_REGION_TOKEN}"
1867 )));
1868 };
1869
1870 let repository = match path.split_once('@') {
1871 Some((repository, _digest)) => repository,
1872 None => match path.rsplit_once('/') {
1873 Some((parent, last)) => match last.split_once(':') {
1874 Some((name, _tag)) => &path[..parent.len() + 1 + name.len()],
1875 None => path,
1876 },
1877 None => path.split_once(':').map_or(path, |(name, _tag)| name),
1878 },
1879 };
1880 let valid_segment = |segment: &str| {
1881 !segment.is_empty()
1882 && segment.bytes().all(|b| {
1883 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
1884 })
1885 };
1886 if !repository.split('/').all(valid_segment) {
1887 return Err(refuse(
1888 "names a repository outside ECR's grammar (lowercase letters, digits, '.', '_', '-', and '/' between them)",
1889 ));
1890 }
1891 Ok(EcrImageRepository {
1892 account_id,
1893 region,
1894 repository,
1895 })
1896}
1897
1898#[cfg(test)]
1899mod tests {
1900 use super::*;
1901
1902 #[test]
1903 fn private_database_setup_accepts_the_default_network() {
1904 for lifecycle in [
1905 crate::ResourceLifecycle::Frozen,
1906 crate::ResourceLifecycle::Live,
1907 ] {
1908 let stack = crate::Stack::new("database".to_string())
1909 .add(
1910 crate::Postgres::new("metadata".to_string()).build(),
1911 lifecycle,
1912 )
1913 .build();
1914 assert!(!restricts_network_mode(&stack, false));
1915 assert!(!restricts_network_mode(&stack, true));
1916 }
1917 assert!(!restricts_network_mode(
1918 &crate::Stack::new("empty".to_string()).build(),
1919 false,
1920 ));
1921 }
1922
1923 fn repository_key(image: &str) -> String {
1926 match parse_ecr_image_repository(image) {
1927 Ok(parsed) => {
1928 let host = image.split_once('/').map_or(image, |(host, _)| host);
1929 format!("{host}/{}", parsed.repository)
1930 }
1931 Err(_) => image.to_string(),
1932 }
1933 }
1934
1935 #[test]
1936 fn a_private_base_image_names_one_repository() {
1937 let vectors: serde_json::Value = serde_json::from_str(include_str!(
1938 "../../tests/fixtures/ecr-image-repository-parity.json"
1939 ))
1940 .expect("the ECR repository vectors must be JSON");
1941 let field = |case: &serde_json::Value, name: &str| {
1942 case[name]
1943 .as_str()
1944 .unwrap_or_else(|| panic!("vector must carry {name}: {case}"))
1945 .to_string()
1946 };
1947
1948 for case in vectors["accepted"].as_array().expect("accepted vectors") {
1949 let image = field(case, "image");
1950 let region = field(case, "region");
1951 let region = if region == BUNDLE_REGION_TOKEN {
1952 EcrImageRegion::Deployment
1953 } else {
1954 EcrImageRegion::Literal(®ion)
1955 };
1956 assert_eq!(
1957 parse_ecr_image_repository(&image),
1958 Ok(EcrImageRepository {
1959 account_id: &field(case, "accountId"),
1960 region,
1961 repository: &field(case, "repository"),
1962 }),
1963 "{image}"
1964 );
1965 assert_eq!(
1966 repository_key(&image),
1967 field(case, "repositoryKey"),
1968 "{image}"
1969 );
1970 }
1971
1972 for case in vectors["refused"].as_array().expect("refused vectors") {
1973 let image = field(case, "image");
1974 assert!(
1975 parse_ecr_image_repository(&image).is_err(),
1976 "{image} must be refused"
1977 );
1978 assert_eq!(
1979 repository_key(&image),
1980 field(case, "repositoryKey"),
1981 "{image}"
1982 );
1983 }
1984 }
1985
1986 #[test]
1987 fn a_repository_arn_takes_the_deployment_region_only_where_the_host_leaves_it() {
1988 let regional =
1989 parse_ecr_image_repository("123456789012.dkr.ecr.{region}.amazonaws.com/team/base:1")
1990 .expect("parses");
1991 let pinned =
1992 parse_ecr_image_repository("123456789012.dkr.ecr.eu-west-1.amazonaws.com/team/base:1")
1993 .expect("parses");
1994 assert_eq!(
1995 regional.arn("aws-us-gov", "us-gov-west-1"),
1996 "arn:aws-us-gov:ecr:us-gov-west-1:123456789012:repository/team/base"
1997 );
1998 assert_eq!(
1999 pinned.arn("aws", "us-east-1"),
2000 "arn:aws:ecr:eu-west-1:123456789012:repository/team/base"
2001 );
2002 }
2003
2004 #[test]
2007 fn a_uri_carrying_an_iam_wildcard_is_refused() {
2008 for uri in [
2009 "s3://acme/team-*/v1/bundle.zip",
2010 "s3://acme/sandbox-bundle/f00d/bundle?.zip",
2011 "s3://acme-*/sandbox-bundle/f00d/bundle.zip",
2012 ] {
2013 let error = parse_bundle_uri(uri).expect_err("a wildcard must be refused");
2014 assert!(error.contains("IAM wildcard"), "for {uri}: {error}");
2015 }
2016
2017 parse_bundle_uri("s3://acme/sandbox-bundle/f00d/bundle.zip")
2018 .expect("an ordinary key still parses");
2019 }
2020
2021 #[test]
2025 fn a_grantable_prefix_ends_above_the_segment_that_moves() {
2026 assert_eq!(
2027 stable_bundle_key_prefix("sandbox-bundle/f00dcafe/bundle.zip"),
2028 Some("sandbox-bundle")
2029 );
2030 assert_eq!(
2031 stable_bundle_key_prefix("artifacts/team-a/sandbox/f00dcafe/bundle.zip"),
2032 Some("artifacts/team-a/sandbox"),
2033 "a deeper key narrows the prefix, it never widens to the first segment"
2034 );
2035
2036 assert_eq!(stable_bundle_key_prefix("agents/bundle.zip"), None);
2039 assert_eq!(stable_bundle_key_prefix("bundle.zip"), None);
2040 }
2041
2042 fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
2043 Sandbox::new("agent-sbx".to_string())
2044 .code(SandboxCode::Image {
2045 image: "ubuntu".to_string(),
2046 bundled_from: None,
2047 })
2048 .limits(SandboxLimits {
2049 cpu: "1".to_string(),
2050 memory: "2Gi".to_string(),
2051 disk: "10Gi".to_string(),
2052 max_processes: None,
2053 })
2054 .egress(egress)
2055 .lifecycle(SandboxLifecyclePolicy {
2056 max_lifetime_seconds: None,
2057 idle_pause_seconds: None,
2058 ..Default::default()
2059 })
2060 .preview_ports(preview_ports)
2061 .build()
2062 }
2063
2064 #[test]
2067 fn gcp_takes_internet_and_a_default_policy_through_the_gateway() {
2068 sandbox_with(SandboxEgress::Internet, vec![])
2069 .validate_for_platform(Platform::Gcp)
2070 .unwrap();
2071 sandbox_with(SandboxEgress::None, vec![])
2072 .validate_for_platform(Platform::Gcp)
2073 .unwrap();
2074 for policy in [
2075 EgressPolicy::Allow {
2076 allow: vec!["api.example.com".into()],
2077 },
2078 EgressPolicy::Internet,
2079 ] {
2080 let mut declared = sandbox_with(SandboxEgress::Internet, vec![]);
2081 declared.default_policy = Some(policy);
2082 declared
2083 .validate_for_platform(Platform::Gcp)
2084 .expect("the gateway enforces a default policy on GCP as on every cloud");
2085 }
2086 }
2087
2088 #[test]
2091 fn gcp_refuses_an_idle_pause_policy_at_plan_time_and_still_takes_a_lifetime() {
2092 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
2093 Sandbox::new("sbx".to_string())
2094 .code(SandboxCode::Image {
2095 image: "ubuntu".to_string(),
2096 bundled_from: None,
2097 })
2098 .egress(SandboxEgress::None)
2099 .lifecycle(lifecycle)
2100 .build()
2101 .validate_for_platform(Platform::Gcp)
2102 };
2103 let refused = with_policy(SandboxLifecyclePolicy {
2104 max_lifetime_seconds: None,
2105 idle_pause_seconds: Some(900),
2106 ..Default::default()
2107 })
2108 .expect_err("no idle policy exists on GCP");
2109 assert_eq!(refused.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2110 assert!(refused.message.contains("idle"), "{}", refused.message);
2111 with_policy(SandboxLifecyclePolicy {
2112 max_lifetime_seconds: Some(3600),
2113 idle_pause_seconds: None,
2114 ..Default::default()
2115 })
2116 .expect("a lifetime is a TTL on GCP");
2117 }
2118
2119 #[test]
2120 fn gcp_accepts_preview_ports_but_not_the_agents_own() {
2121 sandbox_with(SandboxEgress::Deny, vec![8080, 8081, 8090])
2122 .validate_for_platform(Platform::Gcp)
2123 .expect("preview ports are served on GCP, as owner access");
2124 let error = sandbox_with(SandboxEgress::Deny, vec![8080, 8971])
2125 .validate_for_platform(Platform::Gcp)
2126 .expect_err("the agent's own port is not a workload port");
2127 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "{error}");
2128 assert!(error.to_string().contains("8971"), "{error}");
2129 sandbox_with(SandboxEgress::Deny, vec![])
2130 .validate_for_platform(Platform::Gcp)
2131 .expect("a sandbox without preview ports is unaffected");
2132 }
2133
2134 #[test]
2135 fn a_uri_without_a_token_is_carried_whole() {
2136 assert_eq!(
2137 parse_bundle_uri("s3://acme-artifacts-us-east-2/agents/bundle.zip"),
2138 Ok(BundleUri::Literal(
2139 "s3://acme-artifacts-us-east-2/agents/bundle.zip"
2140 ))
2141 );
2142 }
2143
2144 #[test]
2147 fn a_regional_uri_splits_either_side_of_the_token() {
2148 let BundleUri::Regional { before, after } =
2149 parse_bundle_uri("s3://acme-artifacts-{region}/agents/bundle.zip")
2150 .expect("the token is accepted in the bucket")
2151 else {
2152 panic!("a bucket-position token must split");
2153 };
2154
2155 assert_eq!(before, "s3://acme-artifacts-");
2156 assert_eq!(after, "/agents/bundle.zip");
2157 assert_eq!(
2158 format!("{before}us-east-2{after}"),
2159 "s3://acme-artifacts-us-east-2/agents/bundle.zip",
2160 "the halves must rejoin to the URI the vendor meant"
2161 );
2162 }
2163
2164 #[test]
2167 fn a_token_this_build_cannot_resolve_is_refused() {
2168 for uri in [
2169 "s3://acme-artifacts-{regio}/bundle.zip",
2170 "s3://acme-artifacts/{region}/bundle.zip",
2171 "s3://acme-artifacts-{region}-{region}/bundle.zip",
2172 "s3://acme-artifacts/bundle-{version}.zip",
2173 "s3://acme}-artifacts-{region}/bundle.zip",
2174 "s3://acme{-artifacts-{region}/bundle.zip",
2175 ] {
2176 assert!(
2177 parse_bundle_uri(uri).is_err(),
2178 "'{uri}' must be refused before it can reach an image build"
2179 );
2180 }
2181 }
2182
2183 #[test]
2184 fn resource_type_is_stable() {
2185 assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
2186 }
2187
2188 #[test]
2189 fn capability_sets_are_per_platform() {
2190 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2191 assert!(
2192 gcp.reconnect,
2193 "generation from the container boot id makes a sandbox reachable across processes"
2194 );
2195 assert!(gcp.preview, "preview is offered as owner access");
2196 assert!(gcp.enforced_limits);
2197
2198 let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
2199 assert!(azure.files, "every backend moves files");
2200 assert!(gcp.files);
2201 assert!(azure.domain_egress_rules);
2204 assert!(azure.egress_deny);
2205 assert!(azure.enforced_limits);
2208 assert!(azure.pause_resume);
2209 assert!(!azure.snapshot);
2211 assert!(
2212 azure.preview,
2213 "the in-sandbox agent issues a port-scoped capability"
2214 );
2215
2216 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2217 assert!(!aws.snapshot, "AWS has no user-callable sandbox snapshot");
2218 assert!(aws.pause_resume);
2219
2220 let k8s =
2221 SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
2222 assert!(
2223 k8s.preview,
2224 "an in-cluster caller previews through the agent route"
2225 );
2226 }
2227
2228 #[test]
2237 fn supervisor_isolation_is_per_platform() {
2238 let value = |platform| {
2239 SandboxCapabilities::for_platform(platform)
2240 .expect("supported")
2241 .supervisor_isolation
2242 };
2243
2244 assert!(
2245 value(Platform::Aws),
2246 "root agent setuids the command to 60000"
2247 );
2248 assert!(
2249 value(Platform::Local),
2250 "the supervisor is on the host, outside the container"
2251 );
2252 assert!(
2253 value(Platform::Kubernetes),
2254 "root boot splits the command off the supervisor"
2255 );
2256 assert!(!value(Platform::Azure), "no Alien process runs the command");
2257 assert!(
2258 !value(Platform::Gcp),
2259 "no separate supervisor identity runs the command"
2260 );
2261 }
2262
2263 #[test]
2267 fn supervisor_isolation_separates_aws_from_a_subprocess_backend() {
2268 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2269 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2270
2271 assert_eq!(
2272 aws.supervisor_pid_namespace, gcp.supervisor_pid_namespace,
2273 "the older axis cannot tell them apart"
2274 );
2275 assert!(
2276 aws.supervisor_isolation,
2277 "AWS setuids the command off the supervisor"
2278 );
2279 assert!(
2280 !gcp.supervisor_isolation,
2281 "the command runs under no separate supervisor identity"
2282 );
2283 }
2284
2285 #[test]
2290 fn gcp_agent_platform_row_matches_measured_backend() {
2291 let row = SandboxCapabilities::gcp_agent_platform();
2292
2293 assert!(row.files, "agent file ops move over the sandbox envelope");
2294 assert!(
2295 row.reconnect,
2296 "generation is derived from the container boot id, so a sandbox is reachable across \
2297 processes"
2298 );
2299 assert!(
2300 row.preview,
2301 "preview is owner access: the edge credential is the caller's execute right"
2302 );
2303 assert!(
2304 row.pause_resume,
2305 "pause and resume keep memory, and a resume that finds a new container is an error"
2306 );
2307 assert!(
2308 !row.snapshot,
2309 "the create path never sends a snapshot, so none is reachable through the trait"
2310 );
2311 assert!(
2312 !row.domain_egress_rules,
2313 "VPC and DNS peering is not a hostname allowlist"
2314 );
2315 assert!(
2316 row.egress_deny,
2317 "a declared deny blocks TCP, the metadata server and DNS on the default placement"
2318 );
2319 assert!(
2320 row.enforced_limits,
2321 "ceilings are enforced, by terminating the sandbox on breach"
2322 );
2323 assert!(!row.process_limit, "no process-count ceiling is observed");
2324 assert!(row.sandbox_lifetime, "ttl maps to a sandbox expireTime");
2325 assert!(!row.supervisor_pid_namespace, "no PID-namespace isolation");
2326 assert!(
2327 !row.supervisor_isolation,
2328 "the command is not run under a separate supervisor identity"
2329 );
2330
2331 let live = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2333 assert_eq!(
2334 live, row,
2335 "the Platform::Gcp arm is the Agent Platform capability row"
2336 );
2337 }
2338
2339 #[test]
2340 fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
2341 let error = SandboxCapabilities::for_platform(Platform::Machines)
2342 .expect_err("Machines has no sandbox backend");
2343 assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
2344 }
2345
2346 #[test]
2347 fn unsupported_capability_names_platform_and_capability() {
2348 let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
2349 let error = capabilities
2350 .require(SandboxCapability::Snapshot, Platform::Gcp)
2351 .expect_err("GCP has no snapshot");
2352
2353 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2354 let rendered = error.to_string();
2355 assert!(
2356 rendered.contains("snapshot"),
2357 "names the capability: {rendered}"
2358 );
2359 assert!(rendered.contains("gcp"), "names the platform: {rendered}");
2360 }
2361
2362 #[test]
2366 fn a_hostname_allowlist_is_refused_everywhere_it_would_be_approximated() {
2367 let sandbox = sandbox_with(
2368 SandboxEgress::AllowDomains {
2369 domains: vec!["example.com".to_string()],
2370 },
2371 vec![],
2372 );
2373
2374 for platform in [
2375 Platform::Aws,
2376 Platform::Gcp,
2377 Platform::Kubernetes,
2378 Platform::Local,
2379 ] {
2380 let error = sandbox
2381 .validate_for_platform(platform)
2382 .expect_err("only Azure expresses a hostname allowlist");
2383 assert_eq!(
2384 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2385 "on {platform:?}"
2386 );
2387 }
2388
2389 assert!(
2390 SandboxCapabilities::for_platform(Platform::Azure)
2391 .expect("supported")
2392 .domain_egress_rules,
2393 "Azure's egress policy matches on host pattern"
2394 );
2395 }
2396
2397 #[test]
2400 fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
2401 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2402
2403 assert!(
2406 SandboxCapabilities::for_platform(Platform::Gcp)
2407 .expect("supported")
2408 .egress_deny
2409 );
2410
2411 for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
2412 sandbox
2413 .validate_for_platform(platform)
2414 .expect("deny is enforced here");
2415 }
2416
2417 let egress_only = Sandbox::new("sbx".to_string())
2419 .code(SandboxCode::Image {
2420 image: "alpine".to_string(),
2421 bundled_from: None,
2422 })
2423 .egress(SandboxEgress::None)
2424 .lifecycle(SandboxLifecyclePolicy {
2425 max_lifetime_seconds: None,
2426 idle_pause_seconds: None,
2427 ..Default::default()
2428 })
2429 .build();
2430
2431 egress_only
2432 .validate_for_platform(Platform::Azure)
2433 .expect("Azure creates the sandbox under a Deny policy with full inspection");
2434 }
2435
2436 #[test]
2440 fn a_sandbox_declaring_no_ceilings_takes_the_platforms_own() {
2441 let undeclared = Sandbox::new("sbx".to_string())
2442 .code(SandboxCode::Image {
2443 image: "alpine".to_string(),
2444 bundled_from: None,
2445 })
2446 .egress(SandboxEgress::None)
2447 .lifecycle(SandboxLifecyclePolicy {
2448 max_lifetime_seconds: None,
2449 idle_pause_seconds: None,
2450 ..Default::default()
2451 })
2452 .build();
2453
2454 undeclared
2455 .validate_for_platform(Platform::Azure)
2456 .expect("a sandbox naming no ceilings takes the platform's own");
2457
2458 assert_eq!(undeclared.resolved_limits().cpu, "1");
2460 }
2461
2462 #[test]
2466 fn azure_sizes_follow_the_rule_the_data_plane_states() {
2467 let sized = |cpu: &str, memory: &str, disk: &str| {
2468 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2469 let limits = sandbox
2470 .limits
2471 .as_mut()
2472 .expect("the fixture declares limits");
2473 limits.cpu = cpu.to_string();
2474 limits.memory = memory.to_string();
2475 limits.disk = disk.to_string();
2476 sandbox.validate_for_platform(Platform::Azure)
2477 };
2478
2479 sized("250m", "512Mi", "5120Mi").expect("the smallest step the data plane accepts");
2480 sized("4000m", "8192Mi", "40960Mi").expect("cpu, memory and disk are all honoured");
2481 sized("16000m", "32Gi", "320Gi").expect("the top of the range");
2482
2483 let off_step = sized("333m", "512Mi", "5120Mi").expect_err("333m is not a step of 250m");
2485 assert_eq!(off_step.code, "SANDBOX_LIMIT_INVALID", "{off_step}");
2486 assert!(off_step.to_string().contains("cpu"), "{off_step}");
2487
2488 let too_big = sized("32000m", "64Gi", "640Gi").expect_err("32 cores is over the ceiling");
2489 assert_eq!(too_big.code, "SANDBOX_LIMIT_INVALID", "{too_big}");
2490
2491 sized("1000m", "2Gi", "20Gi").expect("2Gi is exactly one core's worth");
2494 let over_memory = sized("250m", "2Gi", "5120Mi").expect_err("2Gi needs a full core");
2495 assert_eq!(over_memory.code, "SANDBOX_LIMIT_INVALID", "{over_memory}");
2496 assert!(over_memory.to_string().contains("memory"), "{over_memory}");
2497
2498 let over_disk = sized("250m", "512Mi", "20Gi").expect_err("20Gi needs a full core");
2499 assert!(over_disk.to_string().contains("disk"), "{over_disk}");
2500 }
2501
2502 #[test]
2505 fn kubernetes_root_image_needs_gateway_or_no_egress() {
2506 let root = |egress| {
2507 let mut sandbox = sandbox_with(egress, vec![]);
2508 sandbox.image_user = Some(0);
2509 sandbox
2510 };
2511 for egress in [SandboxEgress::Internet, SandboxEgress::None] {
2512 root(egress)
2513 .validate_for_platform(Platform::Kubernetes)
2514 .expect("root boot is allowed with an external egress boundary");
2515 }
2516 for egress in [
2517 SandboxEgress::Allow,
2518 SandboxEgress::AllowDomains {
2519 domains: vec!["example.com".to_string()],
2520 },
2521 ] {
2522 let error = root(egress)
2523 .validate_for_platform(Platform::Kubernetes)
2524 .expect_err("a root image under unenforced egress is refused");
2525 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2526 assert!(error.to_string().contains("root image USER"), "{error}");
2527 }
2528 root(SandboxEgress::Internet)
2529 .validate_for_platform(Platform::Local)
2530 .expect_err("Local still refuses a root image");
2531 }
2532
2533 #[test]
2534 fn preview_ports_require_the_preview_capability() {
2535 let sandbox = sandbox_with(SandboxEgress::None, vec![8080]);
2536
2537 sandbox
2538 .validate_for_platform(Platform::Aws)
2539 .expect("AWS mints a port-scoped JWE");
2540
2541 sandbox
2542 .validate_for_platform(Platform::Kubernetes)
2543 .expect("Kubernetes serves preview to in-cluster callers through the agent");
2544
2545 sandbox
2546 .validate_for_platform(Platform::Gcp)
2547 .expect("GCP serves preview to callers that already hold execute");
2548 }
2549
2550 #[test]
2552 fn azure_preview_needs_an_image_that_carries_the_agent() {
2553 let catalog = sandbox_with(SandboxEgress::None, vec![8080]);
2554 let error = catalog
2555 .validate_for_platform(Platform::Azure)
2556 .expect_err("a catalog image has no agent to issue a capability");
2557 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2558
2559 let mut registry = sandbox_with(SandboxEgress::None, vec![8080]);
2560 registry.code = SandboxCode::Image {
2561 image: "registry.example.com/workload/sandbox:1".to_string(),
2562 bundled_from: None,
2563 };
2564 registry
2565 .validate_for_platform(Platform::Azure)
2566 .expect("a registry image is built with the agent");
2567 }
2568
2569 #[test]
2573 fn a_private_base_image_is_refused_off_aws() {
2574 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2575 sandbox.code = SandboxCode::Image {
2576 image: "s3://acme-artifacts/agents/bundle.zip".to_string(),
2577 bundled_from: None,
2578 };
2579 sandbox.private_base_image =
2580 Some("123456789012.dkr.ecr.{region}.amazonaws.com/acme:tag".to_string());
2581
2582 sandbox
2583 .validate_for_platform(Platform::Aws)
2584 .expect("AWS builds its image from a bundle, so a base image sits behind code.image");
2585
2586 for platform in [
2587 Platform::Gcp,
2588 Platform::Azure,
2589 Platform::Kubernetes,
2590 Platform::Local,
2591 ] {
2592 let error = sandbox
2593 .validate_for_platform(platform)
2594 .expect_err("a backend that builds no image must refuse a base image for one");
2595 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2596 assert!(
2597 error.to_string().contains("privateBaseImage"),
2598 "the refusal must name the field the user declared: {error}"
2599 );
2600 }
2601 }
2602
2603 #[test]
2607 fn gcp_refuses_a_disk_above_its_cap_and_accepts_the_cap() {
2608 let with_disk = |disk: &str| {
2609 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2610 sandbox
2611 .limits
2612 .as_mut()
2613 .expect("the fixture declares limits")
2614 .disk = disk.to_string();
2615 sandbox
2616 };
2617
2618 let error = with_disk("20Gi")
2619 .validate_for_platform(Platform::Gcp)
2620 .expect_err("20Gi is above the Agent Platform cap");
2621 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2622 let rendered = error.to_string();
2623 assert!(rendered.contains("disk"), "names the field: {rendered}");
2624 assert!(rendered.contains("10Gi"), "names the cap: {rendered}");
2625
2626 with_disk("10Gi")
2627 .validate_for_platform(Platform::Gcp)
2628 .expect("the cap itself is allowed");
2629 with_disk("10240Mi")
2630 .validate_for_platform(Platform::Gcp)
2631 .expect("the cap in MiB is allowed");
2632 for over in ["10240.5Mi", "10241Mi", "10.0000001Gi"] {
2633 with_disk(over)
2634 .validate_for_platform(Platform::Gcp)
2635 .expect_err(&format!("{over} is above the cap and must not round down"));
2636 }
2637 with_disk("8Gi")
2638 .validate_for_platform(Platform::Gcp)
2639 .expect("the default disk is allowed");
2640 with_disk("20Gi")
2641 .validate_for_platform(Platform::Kubernetes)
2642 .expect("the cap is Agent Platform's, not every backend's");
2643 }
2644
2645 #[test]
2646 fn gcp_accepts_a_sandbox_declaring_enforced_limits() {
2647 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2648 sandbox
2649 .limits
2650 .as_mut()
2651 .expect("the fixture declares limits")
2652 .disk = "10Gi".to_string();
2653 sandbox
2654 .validate_for_platform(Platform::Gcp)
2655 .expect("Agent Platform enforces declared ceilings, by terminating on breach");
2656 }
2657
2658 #[test]
2659 fn invalid_quantities_are_rejected_with_the_offending_field() {
2660 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2661 sandbox
2662 .limits
2663 .as_mut()
2664 .expect("the fixture declares limits")
2665 .memory = "2Gb".to_string();
2666
2667 let error = sandbox
2668 .validate_for_platform(Platform::Aws)
2669 .expect_err("Gb is not a valid suffix");
2670 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2671 assert!(error.to_string().contains("memory"));
2672
2673 sandbox
2674 .limits
2675 .as_mut()
2676 .expect("the fixture declares limits")
2677 .memory = "2Gi".to_string();
2678 sandbox
2679 .limits
2680 .as_mut()
2681 .expect("the fixture declares limits")
2682 .cpu = "0".to_string();
2683 let error = sandbox
2684 .validate_for_platform(Platform::Aws)
2685 .expect_err("zero cpu is not a ceiling");
2686 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2687 }
2688
2689 #[test]
2690 fn zero_max_processes_is_rejected() {
2691 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2692 sandbox
2693 .limits
2694 .as_mut()
2695 .expect("the fixture declares limits")
2696 .max_processes = Some(0);
2697
2698 let error = sandbox
2699 .validate_for_platform(Platform::Local)
2700 .expect_err("a sandbox must be able to run at least one process");
2701 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2702 assert!(error.to_string().contains("maxProcesses"));
2703 }
2704
2705 #[test]
2709 fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
2710 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2711 sandbox
2712 .limits
2713 .as_mut()
2714 .expect("the fixture declares limits")
2715 .max_processes = Some(256);
2716
2717 sandbox
2718 .validate_for_platform(Platform::Local)
2719 .expect("Docker takes a pids limit");
2720
2721 for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
2722 let error = sandbox
2723 .validate_for_platform(platform)
2724 .expect_err("a process ceiling nothing applies must be refused");
2725 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2726 }
2727 }
2728
2729 #[test]
2734 fn a_lifetime_aws_would_reject_is_refused_while_planning() {
2735 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2736 let mut without_limits = with_limits.clone();
2737 without_limits.limits = None;
2738
2739 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2740 for seconds in [28_801, 30_000, 100_000] {
2741 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2742 let error = sandbox
2743 .validate_for_platform(Platform::Aws)
2744 .expect_err("a lifetime above what AWS runs is refused");
2745 assert_eq!(
2746 error.code, "SANDBOX_LIMIT_INVALID",
2747 "{seconds}s {declared} limits"
2748 );
2749
2750 sandbox
2752 .validate_for_platform(Platform::Kubernetes)
2753 .expect("Kubernetes takes an activeDeadlineSeconds above 28,800");
2754 }
2755
2756 sandbox.lifecycle.max_lifetime_seconds = Some(28_800);
2757 sandbox
2758 .validate_for_platform(Platform::Aws)
2759 .expect("the ceiling itself is allowed");
2760 }
2761 }
2762
2763 #[test]
2767 fn a_zero_lifetime_is_refused_while_planning() {
2768 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2769 let mut without_limits = with_limits.clone();
2770 without_limits.limits = None;
2771
2772 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2773 sandbox.lifecycle.max_lifetime_seconds = Some(0);
2774 for platform in [
2775 Platform::Aws,
2776 Platform::Kubernetes,
2777 Platform::Gcp,
2778 Platform::Azure,
2779 Platform::Local,
2780 ] {
2781 let error = sandbox
2782 .validate_for_platform(platform)
2783 .expect_err("a zero lifetime is refused");
2784 assert_eq!(
2785 error.code, "SANDBOX_LIMIT_INVALID",
2786 "{platform} {declared} limits"
2787 );
2788 assert!(
2789 error.to_string().contains("maxLifetimeSeconds"),
2790 "{platform} {declared} limits"
2791 );
2792 }
2793
2794 sandbox.lifecycle.max_lifetime_seconds = Some(1);
2795 sandbox
2796 .validate_for_platform(Platform::Kubernetes)
2797 .expect("one second is the API server's floor");
2798 }
2799 }
2800
2801 #[test]
2805 fn a_lifetime_kubernetes_would_reject_is_refused_while_planning() {
2806 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2807 let mut without_limits = with_limits.clone();
2808 without_limits.limits = None;
2809
2810 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2811 for seconds in [2_147_483_648, u32::MAX] {
2812 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2813 let error = sandbox
2814 .validate_for_platform(Platform::Kubernetes)
2815 .expect_err("a lifetime above what the API server takes is refused");
2816 assert_eq!(
2817 error.code, "SANDBOX_LIMIT_INVALID",
2818 "{seconds}s {declared} limits"
2819 );
2820 assert!(
2821 error.to_string().contains("maxLifetimeSeconds"),
2822 "{seconds}s {declared} limits"
2823 );
2824 }
2825
2826 sandbox.lifecycle.max_lifetime_seconds = Some(2_147_483_647);
2827 sandbox
2828 .validate_for_platform(Platform::Kubernetes)
2829 .expect("the ceiling itself is allowed");
2830 }
2831 }
2832
2833 #[test]
2836 fn an_image_azure_cannot_pull_is_refused_while_planning() {
2837 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2838 sandbox.limits = None;
2841
2842 for image in ["ubuntu@sha256:abc", "", " ", "ubuntu latest", "ubuntu?x"] {
2844 sandbox.code = SandboxCode::Image {
2845 image: image.to_string(),
2846 bundled_from: None,
2847 };
2848 let error = sandbox
2849 .validate_for_platform(Platform::Azure)
2850 .expect_err("an image Azure has nowhere to put is refused");
2851 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "image '{image}'");
2852 }
2853
2854 for image in ["ubuntu", "ubuntu-22.04", "debian_slim"] {
2855 sandbox.code = SandboxCode::Image {
2856 image: image.to_string(),
2857 bundled_from: None,
2858 };
2859 sandbox
2860 .validate_for_platform(Platform::Azure)
2861 .unwrap_or_else(|error| panic!("'{image}' is a catalog name: {error}"));
2862 }
2863
2864 for image in [
2865 "ubuntu:24.04",
2866 "ghcr.io/myorg/sandbox:latest",
2867 "docker.io/library/python:3.14-slim",
2868 "localhost:5000/team/agent@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d",
2869 ] {
2870 sandbox.code = SandboxCode::Image {
2871 image: image.to_string(),
2872 bundled_from: None,
2873 };
2874 sandbox
2875 .validate_for_platform(Platform::Azure)
2876 .unwrap_or_else(|error| panic!("'{image}' is a registry image: {error}"));
2877 }
2878
2879 sandbox.code = SandboxCode::Image {
2881 image: " ubuntu ".to_string(),
2882 bundled_from: None,
2883 };
2884 assert_eq!(
2885 sandbox
2886 .azure_image()
2887 .expect("a padded name is still a name"),
2888 AzureSandboxImage::Catalog("ubuntu")
2889 );
2890 }
2891
2892 #[test]
2896 fn every_value_the_catalog_allowlist_accepted_is_still_a_catalog_name() {
2897 const ALPHABET: &[u8] =
2898 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
2899
2900 let assert_catalog = |value: &str| {
2901 assert_eq!(
2902 classify_azure_sandbox_image(value),
2903 Some(AzureSandboxImage::Catalog(value.trim())),
2904 "'{value}'"
2905 );
2906 };
2907
2908 for a in ALPHABET {
2909 assert_catalog(&String::from_utf8(vec![*a]).unwrap());
2910 for b in ALPHABET {
2911 assert_catalog(&String::from_utf8(vec![*a, *b]).unwrap());
2912 for c in ALPHABET {
2913 assert_catalog(&String::from_utf8(vec![*a, *b, *c]).unwrap());
2914 }
2915 }
2916 }
2917
2918 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
2919 let mut next = || {
2920 state ^= state << 13;
2921 state ^= state >> 7;
2922 state ^= state << 17;
2923 state
2924 };
2925 for _ in 0..20_000 {
2926 let len = 4 + (next() % 60) as usize;
2927 let mut value: String = (0..len)
2928 .map(|_| ALPHABET[(next() % ALPHABET.len() as u64) as usize] as char)
2929 .collect();
2930 if next() % 4 == 0 {
2931 value = format!(" {value}\t");
2932 }
2933 assert_catalog(&value);
2934 }
2935 }
2936
2937 #[test]
2940 fn the_disk_image_label_is_stable_and_label_safe() {
2941 let label = azure_disk_image_label("docker.io/library/python:3.14-slim");
2942 assert_eq!(
2943 label,
2944 azure_disk_image_label(" docker.io/library/python:3.14-slim ")
2945 );
2946 assert_ne!(
2947 label,
2948 azure_disk_image_label("docker.io/library/python:3.13-slim")
2949 );
2950 assert_eq!(label.len(), 32);
2951 assert!(label.chars().all(|c| c.is_ascii_hexdigit()), "{label}");
2952 }
2953
2954 #[test]
2958 fn a_sandbox_deadline_is_accepted_only_where_the_platform_applies_it() {
2959 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2960 sandbox.lifecycle.max_lifetime_seconds = Some(3600);
2961
2962 sandbox
2963 .validate_for_platform(Platform::Kubernetes)
2964 .expect("the kubelet enforces activeDeadlineSeconds");
2965 sandbox
2966 .validate_for_platform(Platform::Aws)
2967 .expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
2968
2969 sandbox.validate_for_platform(Platform::Azure).expect(
2970 "the binding stamps a deadline label and the controller's reaper deletes by it",
2971 );
2972 sandbox
2973 .validate_for_platform(Platform::Local)
2974 .expect("the local sandbox route ends a session at its lifetime");
2975 }
2976
2977 #[test]
2981 fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
2982 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2983 let tier = sandbox
2984 .microvm_tier()
2985 .expect("2Gi/1cpu/20Gi is satisfiable");
2986
2987 assert_eq!(
2988 tier.peak_memory_mib, 2048,
2989 "the peak is the declared ceiling"
2990 );
2991 assert_eq!(
2992 tier.baseline_memory_mib, 512,
2993 "which is a quarter of it as the baseline"
2994 );
2995 assert!(tier.max_disk_mib <= 20 * 1024);
2996 }
2997
2998 #[test]
3002 fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
3003 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
3004 {
3005 let limits = sandbox
3006 .limits
3007 .as_mut()
3008 .expect("the fixture declares limits");
3009 limits.cpu = "1".to_string();
3010 limits.memory = "8Gi".to_string();
3011 }
3012
3013 let error = sandbox
3014 .microvm_tier()
3015 .expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
3016 assert!(
3017 error.to_string().contains("4 vCPU"),
3018 "the refusal must say what the memory ceiling implies: {error}"
3019 );
3020
3021 sandbox
3022 .limits
3023 .as_mut()
3024 .expect("the fixture declares limits")
3025 .cpu = "4".to_string();
3026 let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
3027 assert_eq!(tier.peak_memory_mib, 8192);
3028 }
3029
3030 #[test]
3033 fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
3034 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
3035 sandbox
3036 .limits
3037 .as_mut()
3038 .expect("the fixture declares limits")
3039 .memory = "1Gi".to_string();
3040
3041 let error = sandbox
3042 .validate_for_platform(Platform::Aws)
3043 .expect_err("no MicroVM size peaks at or below 1Gi");
3044 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3045 assert!(
3046 error.to_string().contains("2Gi"),
3047 "the refusal must say what the smallest holdable ceiling is: {error}"
3048 );
3049 }
3050
3051 #[test]
3054 fn source_code_is_refused_where_no_backend_builds_it() {
3055 let sandbox = Sandbox::new("agent".to_string())
3056 .code(SandboxCode::Source {
3057 src: "./sandbox".to_string(),
3058 toolchain: ToolchainConfig::Docker {
3059 dockerfile: None,
3060 build_args: None,
3061 target: None,
3062 },
3063 })
3064 .egress(SandboxEgress::None)
3065 .lifecycle(SandboxLifecyclePolicy {
3066 max_lifetime_seconds: None,
3067 idle_pause_seconds: None,
3068 ..Default::default()
3069 })
3070 .build();
3071
3072 sandbox
3073 .validate_for_platform(Platform::Aws)
3074 .expect("an AWS sandbox base image is built by `alien build`");
3075 sandbox
3076 .validate_for_platform(Platform::Azure)
3077 .expect("an Azure sandbox base image is built by `alien build`");
3078 sandbox
3079 .validate_for_platform(Platform::Gcp)
3080 .expect("a GCP sandbox base image is built by `alien build`");
3081 sandbox
3082 .validate_for_platform(Platform::Kubernetes)
3083 .expect("a Kubernetes sandbox base image is built by `alien build`");
3084
3085 for platform in [Platform::Local] {
3086 let error = sandbox
3087 .validate_for_platform(platform)
3088 .expect_err("no backend builds a sandbox image from source here");
3089 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3090 assert!(
3091 error.to_string().contains("code.image"),
3092 "the refusal must say what to write instead: {error}"
3093 );
3094 assert!(
3095 error.to_string().contains(&platform.to_string()),
3096 "the refusal must name the platform that cannot build it: {error}"
3097 );
3098 }
3099 }
3100
3101 #[test]
3104 fn every_accepted_unit_converts_rather_than_falling_back() {
3105 assert_eq!(quantity_mib("2Gi"), Some(2048));
3106 assert_eq!(quantity_mib("512Mi"), Some(512));
3107 assert_eq!(quantity_mib("4G"), Some(3814));
3108 assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
3109 assert_eq!(millicores("1"), Some(1000));
3110 assert_eq!(millicores("500m"), Some(500));
3111 }
3112
3113 #[test]
3114 fn privileged_supervisor_fixes_identity_and_requires_an_enforceable_backend() {
3115 let mut sandbox = sandbox_with(
3116 SandboxEgress::AllowDomains {
3117 domains: vec!["example.com".to_string()],
3118 },
3119 vec![],
3120 );
3121 sandbox.privileged_supervisor = Some(SandboxPrivilegedSupervisor { command_uid: 60001 });
3122 sandbox
3123 .validate_for_platform(Platform::Aws)
3124 .expect("AWS can enforce the policy in the agent");
3125 assert_eq!(sandbox.cloud_egress(), &SandboxEgress::Allow);
3126 assert_eq!(
3127 sandbox.supervisor_environment()["ALIEN_SANDBOX_EXPECTED_EXEC_UID"],
3128 "60001"
3129 );
3130 for platform in [
3131 Platform::Local,
3132 Platform::Kubernetes,
3133 Platform::Azure,
3134 Platform::Gcp,
3135 ] {
3136 let error = sandbox
3137 .validate_for_platform(platform)
3138 .expect_err("cannot grant a privilege boundary the backend lacks");
3139 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
3140 assert!(error.message.contains("privilegedSupervisor"));
3141 }
3142 for uid in [0, u32::MAX] {
3143 sandbox.privileged_supervisor.as_mut().unwrap().command_uid = uid;
3144 let error = sandbox
3145 .validate_for_platform(Platform::Aws)
3146 .expect_err("invalid uid must fail at plan time");
3147 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3148 }
3149 }
3150
3151 #[test]
3152 fn unknown_fields_are_rejected() {
3153 let json = r#"{
3154 "id": "sbx",
3155 "code": {"type": "image", "image": "ubuntu:24.04"},
3156 "limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
3157 "egress": {"mode": "deny"},
3158 "lifecycle": {},
3159 "unexpected": true
3160 }"#;
3161
3162 serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
3163 }
3164
3165 #[test]
3166 fn serialization_roundtrips() {
3167 let sandbox = sandbox_with(
3168 SandboxEgress::AllowDomains {
3169 domains: vec!["example.com".to_string()],
3170 },
3171 vec![8080, 9090],
3172 );
3173
3174 let json = serde_json::to_string(&sandbox).expect("serializes");
3175 let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
3176 assert_eq!(sandbox, restored);
3177 }
3178
3179 #[test]
3180 fn id_is_immutable_across_updates() {
3181 let original = sandbox_with(SandboxEgress::None, vec![]);
3182 let renamed = Sandbox::new("other".to_string())
3183 .code(SandboxCode::Image {
3184 image: "ubuntu".to_string(),
3185 bundled_from: None,
3186 })
3187 .limits(
3188 original
3189 .limits
3190 .clone()
3191 .expect("the fixture declares limits"),
3192 )
3193 .egress(SandboxEgress::None)
3194 .lifecycle(SandboxLifecyclePolicy {
3195 max_lifetime_seconds: None,
3196 idle_pause_seconds: None,
3197 ..Default::default()
3198 })
3199 .build();
3200
3201 original
3202 .validate_update(&original.clone())
3203 .expect("an unchanged config is a valid update");
3204 original
3205 .validate_update(&renamed)
3206 .expect_err("renaming a sandbox is not an update");
3207 }
3208
3209 #[test]
3213 fn azure_takes_an_idle_policy_and_a_lifetime_ceiling() {
3214 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
3215 Sandbox::new("sbx".to_string())
3216 .code(SandboxCode::Image {
3217 image: "ubuntu".to_string(),
3218 bundled_from: None,
3219 })
3220 .egress(SandboxEgress::Allow)
3221 .lifecycle(lifecycle)
3222 .build()
3223 .validate_for_platform(Platform::Azure)
3224 };
3225
3226 with_policy(SandboxLifecyclePolicy {
3227 max_lifetime_seconds: None,
3228 idle_pause_seconds: Some(900),
3229 ..Default::default()
3230 })
3231 .expect("Azure pauses a sandbox on idle");
3232
3233 with_policy(SandboxLifecyclePolicy {
3234 max_lifetime_seconds: Some(3600),
3235 idle_pause_seconds: None,
3236 ..Default::default()
3237 })
3238 .expect("the reaper enforces a wall-clock ceiling");
3239 }
3240
3241 #[test]
3247 fn an_allowlist_with_no_domains_is_refused() {
3248 let declared = |domains: Vec<String>| {
3249 Sandbox::new("sbx".to_string())
3250 .code(SandboxCode::Image {
3251 image: "ubuntu".to_string(),
3252 bundled_from: None,
3253 })
3254 .egress(SandboxEgress::AllowDomains { domains })
3255 .lifecycle(SandboxLifecyclePolicy {
3256 max_lifetime_seconds: None,
3257 idle_pause_seconds: None,
3258 ..Default::default()
3259 })
3260 .build()
3261 .validate_for_platform(Platform::Azure)
3262 };
3263
3264 let error = declared(vec![]).expect_err("an empty allowlist must be refused");
3265 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3266
3267 declared(vec!["api.example.com".to_string()])
3268 .expect("a named domain is what an allowlist is for");
3269 }
3270
3271 #[test]
3274 fn internet_access_switch_maps_only_the_two_expressible_modes() {
3275 assert_eq!(SandboxEgress::Allow.internet_access_switch(), Some(true));
3276 assert_eq!(SandboxEgress::None.internet_access_switch(), Some(false));
3277 assert_eq!(
3278 SandboxEgress::Internet.internet_access_switch(),
3279 Some(false),
3280 "internet leaves only through the gateway, never the cloud's open switch"
3281 );
3282 assert_eq!(
3283 SandboxEgress::AllowDomains {
3284 domains: vec!["api.example.com".to_string()]
3285 }
3286 .internet_access_switch(),
3287 None,
3288 "a host list has no boolean and must not be approximated"
3289 );
3290 }
3291
3292 #[test]
3296 fn stack_state_written_before_the_lifecycle_rename_still_reads() {
3297 let stored: crate::StackResourceState = serde_json::from_value(serde_json::json!({
3298 "type": "sandbox",
3299 "config": {
3300 "id": "sandbox",
3301 "code": {
3302 "type": "image",
3303 "image": "s3://example-bundles/analysis/v1/bundle.zip"
3304 },
3305 "type": "sandbox",
3306 "egress": { "mode": "allow" },
3307 "session": { "maxLifetimeSeconds": 28800, "idleSuspendSeconds": 600 }
3308 },
3309 "status": "running",
3310 "outputs": {
3311 "type": "sandbox",
3312 "identifier": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox",
3313 "parentName": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox"
3314 },
3315 "lifecycle": "frozen",
3316 "dependencies": [
3317 { "id": "management", "type": "remote-stack-management" },
3318 { "id": "access", "type": "resource-access" }
3319 ],
3320 "controllerPlatform": "aws"
3321 }))
3322 .expect("a stack state written before the rename must still deserialize");
3323
3324 let expected = Sandbox::new("sandbox".to_string())
3325 .code(SandboxCode::Image {
3326 image: "s3://example-bundles/analysis/v1/bundle.zip".to_string(),
3327 bundled_from: None,
3328 })
3329 .egress(SandboxEgress::Allow)
3330 .lifecycle(SandboxLifecyclePolicy {
3331 max_lifetime_seconds: Some(28_800),
3332 idle_pause_seconds: Some(600),
3333 ..Default::default()
3334 })
3335 .build();
3336 assert_eq!(stored.config.downcast_ref::<Sandbox>(), Some(&expected));
3337
3338 let rewritten = serde_json::to_value(&stored.config).expect("the sandbox serializes");
3339 assert_eq!(
3340 rewritten["lifecycle"],
3341 serde_json::json!({ "maxLifetimeSeconds": 28800, "idlePauseSeconds": 600 }),
3342 "the next write stores the current names"
3343 );
3344 assert!(rewritten.get("session").is_none());
3345 }
3346}
3347
3348#[cfg(test)]
3349mod label_format_tests {
3350 use super::*;
3351
3352 #[test]
3353 fn request_keys_are_bounded_and_safe() {
3354 for good in ["a", "A-z_9", &"x".repeat(64)] {
3355 assert!(is_valid_request_key(good), "{good}");
3356 }
3357 for bad in ["", "a b", "a/b", "a.b", "é", &"x".repeat(65)] {
3358 assert!(!is_valid_request_key(bad), "{bad}");
3359 }
3360 }
3361
3362 #[test]
3363 fn expiry_is_a_positive_integer() {
3364 assert!(is_valid_sandbox_expiry("1700000000000"));
3365 for bad in ["", "0", "-1", "1.5", "never", "+5 "] {
3366 assert!(!is_valid_sandbox_expiry(bad), "{bad}");
3367 }
3368 }
3369}