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