1use crate::error::{ErrorData, Result};
11use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
12use crate::resources::ToolchainConfig;
13use crate::Platform;
14use alien_error::AlienError;
15use bon::Builder;
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18use std::any::Any;
19use std::fmt::Debug;
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
24#[serde(rename_all = "camelCase", tag = "type")]
25pub enum SandboxCode {
26 #[serde(rename_all = "camelCase")]
28 Image {
29 image: String,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
38 #[cfg_attr(feature = "openapi", schema(ignore))]
39 bundled_from: Option<String>,
40 },
41 #[serde(rename_all = "camelCase")]
47 Source {
48 src: String,
50 toolchain: ToolchainConfig,
52 },
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
62#[serde(rename_all = "camelCase", deny_unknown_fields)]
63pub struct SandboxLimits {
64 pub cpu: String,
66 pub memory: String,
68 pub disk: String,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub max_processes: Option<u32>,
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct MicrovmTier {
86 pub baseline_memory_mib: i64,
88 pub peak_memory_mib: i64,
90 pub peak_vcpu: u32,
92 pub max_disk_mib: i64,
94}
95
96const AWS_MAX_LIFETIME_SECONDS: u32 = 28_800;
100
101const KUBERNETES_MAX_LIFETIME_SECONDS: u32 = i32::MAX as u32;
104
105const GCP_MAX_DISK_BYTES: u128 = 10 * 1024 * 1024 * 1024;
108
109const AZURE_CPU_STEP_MILLICORES: i64 = 250;
112const AZURE_MAX_CPU_MILLICORES: i64 = 16_000;
113const AZURE_MEMORY_MIB_PER_CORE: i64 = 2 * 1024;
114const AZURE_DISK_MIB_PER_CORE: i64 = 20 * 1024;
115
116const MICROVM_TIERS: &[MicrovmTier] = &[
117 MicrovmTier {
118 baseline_memory_mib: 512,
119 peak_memory_mib: 2048,
120 peak_vcpu: 1,
121 max_disk_mib: 8192,
122 },
123 MicrovmTier {
124 baseline_memory_mib: 1024,
125 peak_memory_mib: 4096,
126 peak_vcpu: 2,
127 max_disk_mib: 8192,
128 },
129 MicrovmTier {
130 baseline_memory_mib: 2048,
131 peak_memory_mib: 8192,
132 peak_vcpu: 4,
133 max_disk_mib: 8192,
134 },
135 MicrovmTier {
136 baseline_memory_mib: 4096,
137 peak_memory_mib: 16384,
138 peak_vcpu: 8,
139 max_disk_mib: 16384,
140 },
141 MicrovmTier {
142 baseline_memory_mib: 8192,
143 peak_memory_mib: 32768,
144 peak_vcpu: 16,
145 max_disk_mib: 32768,
146 },
147];
148
149pub use super::sandbox_policy::{is_public_ipv4, non_public_ipv4_ranges, EgressPolicy};
150
151#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum SandboxEgress {
154 None,
155 Internet,
156 Allow,
158 AllowDomains {
160 domains: Vec<String>,
161 },
162}
163
164#[derive(Debug, Clone, Serialize, Deserialize)]
166#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
167#[serde(tag = "mode", rename_all = "camelCase", deny_unknown_fields)]
168pub enum LegacySandboxEgress {
169 Deny,
171 Allow,
174 AllowDomains { domains: Vec<String> },
177}
178
179#[derive(Serialize, Deserialize)]
180#[serde(rename_all = "camelCase")]
181enum SandboxEgressMode {
182 None,
183 Internet,
184}
185
186#[derive(Serialize, Deserialize)]
187#[serde(untagged)]
188enum SandboxEgressInput {
189 Mode(SandboxEgressMode),
190 Legacy(LegacySandboxEgress),
191}
192
193impl Serialize for SandboxEgress {
194 fn serialize<S: serde::Serializer>(
195 &self,
196 serializer: S,
197 ) -> std::result::Result<S::Ok, S::Error> {
198 match self {
199 Self::None => serializer.serialize_str("none"),
200 Self::Internet => serializer.serialize_str("internet"),
201 Self::Allow => LegacySandboxEgress::Allow.serialize(serializer),
202 Self::AllowDomains { domains } => LegacySandboxEgress::AllowDomains {
203 domains: domains.clone(),
204 }
205 .serialize(serializer),
206 }
207 }
208}
209
210impl<'de> Deserialize<'de> for SandboxEgress {
211 fn deserialize<D: serde::Deserializer<'de>>(
212 deserializer: D,
213 ) -> std::result::Result<Self, D::Error> {
214 Ok(match SandboxEgressInput::deserialize(deserializer)? {
215 SandboxEgressInput::Mode(SandboxEgressMode::None)
216 | SandboxEgressInput::Legacy(LegacySandboxEgress::Deny) => Self::None,
217 SandboxEgressInput::Mode(SandboxEgressMode::Internet) => Self::Internet,
218 SandboxEgressInput::Legacy(LegacySandboxEgress::Allow) => Self::Allow,
219 SandboxEgressInput::Legacy(LegacySandboxEgress::AllowDomains { domains }) => {
220 Self::AllowDomains { domains }
221 }
222 })
223 }
224}
225
226#[cfg(feature = "openapi")]
227impl utoipa::PartialSchema for SandboxEgress {
228 fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
229 use utoipa::openapi::schema::{ObjectBuilder, OneOfBuilder, Type};
230 OneOfBuilder::new()
231 .item(
232 ObjectBuilder::new()
233 .schema_type(Type::String)
234 .enum_values(Some(["none", "internet"])),
235 )
236 .item(LegacySandboxEgress::schema())
237 .into()
238 }
239}
240#[cfg(feature = "openapi")]
241impl utoipa::ToSchema for SandboxEgress {}
242
243impl SandboxEgress {
244 #[allow(non_upper_case_globals)]
246 #[deprecated(note = "use SandboxEgress::None")]
247 pub const Deny: Self = Self::None;
248
249 pub fn internet_access_switch(&self) -> Option<bool> {
251 match self {
252 Self::None => Some(false),
253 Self::Internet | Self::Allow => Some(true),
254 Self::AllowDomains { .. } => None,
255 }
256 }
257}
258
259pub const SANDBOX_EXPIRY_LABEL: &str = "alienExpiresAtMs";
261
262pub const SANDBOX_REQUEST_KEY_LABEL: &str = "alienRequestKey";
264
265pub const SANDBOX_REQUEST_KEY_MAX_LEN: usize = 64;
267
268pub fn is_valid_request_key(value: &str) -> bool {
271 !value.is_empty()
272 && value.len() <= SANDBOX_REQUEST_KEY_MAX_LEN
273 && value
274 .bytes()
275 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
276}
277
278pub fn is_valid_sandbox_expiry(value: &str) -> bool {
280 value.parse::<u64>().is_ok_and(|ms| ms > 0)
281}
282
283pub const AZURE_GATEWAY_MAX_LIFETIME_SECONDS: u32 = 24 * 60 * 60;
285
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
292#[serde(rename_all = "camelCase", deny_unknown_fields)]
293pub struct SandboxLifecyclePolicy {
294 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub max_lifetime_seconds: Option<u32>,
302 #[serde(alias = "idleSuspendSeconds", skip_serializing_if = "Option::is_none")]
306 pub idle_pause_seconds: Option<u32>,
307}
308
309pub const GCP_PREVIEW_IS_COMMAND_ACCESS: &str = "On Google Cloud, preview access equals command access; port-scoped preview sharing is not available.";
313
314#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
320#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
321#[serde(rename_all = "camelCase", deny_unknown_fields)]
322pub struct SandboxCapabilities {
323 pub files: bool,
325 pub reconnect: bool,
327 pub jobs: bool,
330 pub interactive_commands: bool,
333 pub preview: bool,
335 pub pause_resume: bool,
337 pub snapshot: bool,
339 pub domain_egress_rules: bool,
341 pub egress_deny: bool,
344 pub enforced_limits: bool,
346 pub process_limit: bool,
348 pub sandbox_lifetime: bool,
350 pub supervisor_pid_namespace: bool,
356 pub supervisor_isolation: bool,
363}
364
365impl SandboxCapabilities {
366 pub fn for_platform(platform: Platform) -> Result<Self> {
372 match platform {
373 Platform::Aws => Ok(Self {
374 files: true,
375 reconnect: true,
376 jobs: true,
377 interactive_commands: true,
380 preview: true,
381 pause_resume: true,
382 snapshot: false,
383 domain_egress_rules: false,
384 egress_deny: true,
387 enforced_limits: true,
388 process_limit: false,
390 sandbox_lifetime: true,
393 supervisor_pid_namespace: false,
398 supervisor_isolation: true,
401 }),
402 Platform::Azure => Ok(Self::azure()),
403 Platform::Gcp => Ok(Self::gcp_agent_platform()),
404 Platform::Kubernetes => Ok(Self {
405 files: true,
406 reconnect: true,
407 jobs: true,
408 interactive_commands: true,
413 preview: true,
419 pause_resume: false,
422 snapshot: false,
424 domain_egress_rules: false,
425 egress_deny: true,
426 enforced_limits: true,
427 process_limit: false,
432 sandbox_lifetime: true,
438 supervisor_pid_namespace: false,
442 supervisor_isolation: true,
448 }),
449 Platform::Local => Ok(Self {
450 files: true,
451 reconnect: true,
452 jobs: false,
454 interactive_commands: true,
457 preview: true,
458 pause_resume: false,
459 snapshot: false,
460 domain_egress_rules: false,
461 egress_deny: true,
462 enforced_limits: true,
463 process_limit: true,
465 sandbox_lifetime: false,
466 supervisor_pid_namespace: false,
469 supervisor_isolation: true,
473 }),
474 Platform::Machines | Platform::Test => {
475 Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
476 platform: platform.to_string(),
477 }))
478 }
479 }
480 }
481
482 pub fn azure() -> Self {
484 Self {
485 files: true,
486 reconnect: true,
487 jobs: true,
490 interactive_commands: true,
494 preview: true,
501 pause_resume: true,
502 snapshot: false,
506 domain_egress_rules: true,
507 egress_deny: true,
508 enforced_limits: true,
512 process_limit: false,
513 sandbox_lifetime: true,
518 supervisor_pid_namespace: false,
520 supervisor_isolation: false,
523 }
524 }
525
526 pub fn gcp_agent_platform() -> Self {
528 Self {
529 files: true,
531 reconnect: true,
535 jobs: true,
536 interactive_commands: false,
539 preview: true,
545 pause_resume: false,
548 snapshot: false,
551 domain_egress_rules: false,
553 egress_deny: true,
556 enforced_limits: true,
560 process_limit: false,
562 sandbox_lifetime: true,
564 supervisor_pid_namespace: false,
566 supervisor_isolation: false,
569 }
570 }
571
572 pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
574 let available = match capability {
575 SandboxCapability::Files => self.files,
576 SandboxCapability::Reconnect => self.reconnect,
577 SandboxCapability::Jobs => self.jobs,
578 SandboxCapability::InteractiveCommands => self.interactive_commands,
579 SandboxCapability::Preview => self.preview,
580 SandboxCapability::PauseResume => self.pause_resume,
581 SandboxCapability::Snapshot => self.snapshot,
582 SandboxCapability::DomainEgressRules => self.domain_egress_rules,
583 SandboxCapability::EgressDeny => self.egress_deny,
584 SandboxCapability::EnforcedLimits => self.enforced_limits,
585 SandboxCapability::ProcessLimit => self.process_limit,
586 SandboxCapability::SandboxLifetime => self.sandbox_lifetime,
587 SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
588 SandboxCapability::SupervisorIsolation => self.supervisor_isolation,
589 };
590
591 if available {
592 return Ok(());
593 }
594
595 Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
596 capability: capability.as_str().to_string(),
597 platform: platform.to_string(),
598 }))
599 }
600}
601
602#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
604#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
605#[serde(rename_all = "camelCase")]
606pub enum SandboxCapability {
607 Files,
609 Reconnect,
611 Jobs,
613 InteractiveCommands,
615 Preview,
617 PauseResume,
619 Snapshot,
621 DomainEgressRules,
623 EgressDeny,
625 EnforcedLimits,
627 ProcessLimit,
629 SandboxLifetime,
631 SupervisorPidNamespace,
633 SupervisorIsolation,
635}
636
637impl SandboxCapability {
638 pub fn as_str(&self) -> &'static str {
640 match self {
641 Self::Files => "files",
642 Self::Reconnect => "reconnect",
643 Self::Jobs => "jobs",
644 Self::InteractiveCommands => "interactiveCommands",
645 Self::Preview => "preview",
646 Self::PauseResume => "pauseResume",
647 Self::Snapshot => "snapshot",
648 Self::DomainEgressRules => "domainEgressRules",
649 Self::EgressDeny => "egressDeny",
650 Self::EnforcedLimits => "enforcedLimits",
651 Self::ProcessLimit => "processLimit",
652 Self::SandboxLifetime => "sandboxLifetime",
653 Self::SupervisorPidNamespace => "supervisorPidNamespace",
654 Self::SupervisorIsolation => "supervisorIsolation",
655 }
656 }
657}
658
659#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
661#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
662#[serde(rename_all = "camelCase", deny_unknown_fields)]
663pub struct SandboxPrivilegedSupervisor {
664 pub command_uid: u32,
666}
667
668#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
670#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
671#[serde(rename_all = "camelCase", deny_unknown_fields)]
672#[builder(start_fn = new)]
673pub struct Sandbox {
674 #[builder(start_fn)]
677 pub id: String,
678 #[builder(field)]
681 #[serde(default, skip_serializing_if = "Vec::is_empty")]
682 #[cfg_attr(feature = "openapi", schema(ignore))]
683 pub links: Vec<ResourceRef>,
684 pub code: SandboxCode,
686 #[builder(skip)]
689 #[serde(default, skip_serializing_if = "Option::is_none")]
690 #[cfg_attr(feature = "openapi", schema(ignore))]
691 pub image_user: Option<u32>,
692 #[serde(skip_serializing_if = "Option::is_none")]
696 pub private_base_image: Option<String>,
697 #[serde(skip_serializing_if = "Option::is_none")]
703 pub limits: Option<SandboxLimits>,
704 pub egress: SandboxEgress,
706 #[serde(default, skip_serializing_if = "Option::is_none")]
708 pub default_policy: Option<EgressPolicy>,
709 #[builder(skip)]
713 #[serde(default, skip_serializing_if = "Option::is_none")]
714 pub privileged_supervisor: Option<SandboxPrivilegedSupervisor>,
715 #[serde(alias = "session")]
720 pub lifecycle: SandboxLifecyclePolicy,
721 #[builder(default)]
725 #[serde(default, skip_serializing_if = "Vec::is_empty")]
726 pub preview_ports: Vec<u16>,
727}
728
729pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
734 !targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
735}
736
737pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
743 stack.resources().any(|(_, entry)| {
744 entry
745 .config
746 .downcast_ref::<Sandbox>()
747 .is_some_and(|sandbox| crate::sandbox_egress::sandbox_needs_connector(stack, sandbox))
748 })
749}
750
751impl Sandbox {
752 pub(crate) fn setup_digest_value(&self) -> serde_json::Value {
753 match &self.egress {
754 SandboxEgress::None => serde_json::json!({"mode":"deny"}),
755 value => serde_json::to_value(value).expect("egress serializes"),
756 }
757 }
758
759 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
761
762 pub fn id(&self) -> &str {
764 &self.id
765 }
766
767 pub fn cloud_egress(&self) -> &SandboxEgress {
770 if self.privileged_supervisor.is_some() && self.egress != SandboxEgress::Internet {
771 &SandboxEgress::Allow
772 } else {
773 &self.egress
774 }
775 }
776
777 pub fn supervisor_environment(&self) -> std::collections::BTreeMap<String, String> {
779 let mut env = std::collections::BTreeMap::new();
780 if let Some(supervisor) = &self.privileged_supervisor {
781 env.insert(
782 "ALIEN_SANDBOX_EXPECTED_EXEC_UID".to_string(),
783 supervisor.command_uid.to_string(),
784 );
785 env.insert(
786 "ALIEN_SANDBOX_EGRESS".to_string(),
787 if self.egress == SandboxEgress::None {
789 r#"{"mode":"deny"}"#.to_string()
790 } else {
791 serde_json::to_string(&self.egress).expect("egress serializes")
792 },
793 );
794 }
795 env
796 }
797
798 pub fn resolved_limits(&self) -> SandboxLimits {
804 self.limits.clone().unwrap_or_else(default_limits)
805 }
806
807 pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
812 if let Some(policy) = &self.default_policy {
813 if self.egress != SandboxEgress::Internet {
814 return Err(AlienError::new(ErrorData::SandboxEgressInvalid {
815 target: "defaultPolicy".into(),
816 reason: "defaultPolicy requires the new internet declaration".into(),
817 }));
818 }
819 policy.validate()?;
820 }
821 if self.image_user == Some(0) && platform == Platform::Local {
822 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
823 capability: "root image USER: this backend does not yet separate bounded root boot from non-root exec; use a non-root image USER".into(),
824 platform: platform.to_string(),
825 }));
826 }
827 if self.image_user == Some(0)
831 && platform == Platform::Kubernetes
832 && !matches!(self.egress, SandboxEgress::Internet | SandboxEgress::None)
833 {
834 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
835 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(),
836 platform: platform.to_string(),
837 }));
838 }
839 let mut capabilities = SandboxCapabilities::for_platform(platform)?;
840 if let Some(supervisor) = &self.privileged_supervisor {
841 if platform != Platform::Aws {
842 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
843 capability: "privilegedSupervisor".to_string(),
844 platform: platform.to_string(),
845 }));
846 }
847 if supervisor.command_uid == 0 || supervisor.command_uid == u32::MAX {
848 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
849 resource_id: self.id.clone(),
850 field: "privilegedSupervisor.commandUid".to_string(),
851 value: supervisor.command_uid.to_string(),
852 reason: "must be a non-root Linux uid other than the invalid uid sentinel"
853 .to_string(),
854 }));
855 }
856 if let SandboxEgress::AllowDomains { domains } = &self.egress {
857 for domain in domains {
858 let hostname = domain.strip_suffix('.').unwrap_or(domain);
859 if hostname.len() > 253
860 || !hostname.split('.').all(|label| {
861 !label.is_empty()
862 && label.len() <= 63
863 && label
864 .bytes()
865 .all(|c| c.is_ascii_alphanumeric() || c == b'-')
866 && !label.starts_with('-')
867 && !label.ends_with('-')
868 })
869 {
870 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
871 resource_id: self.id.clone(), field: "egress.domains".to_string(), value: domain.clone(),
872 reason: "privileged supervisor allowlists require exact DNS hostnames; wildcards are unsupported".to_string(),
873 }));
874 }
875 }
876 }
877 capabilities.domain_egress_rules = true;
878 }
879
880 if matches!(&self.code, SandboxCode::Source { .. })
885 && !matches!(
886 platform,
887 Platform::Aws | Platform::Azure | Platform::Gcp | Platform::Kubernetes
888 )
889 {
890 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
891 resource_id: self.id.clone(),
892 field: "code".to_string(),
893 value: "source".to_string(),
894 reason: format!(
895 "no sandbox backend builds an image from source on {platform}; give \
896 code.image a prebuilt reference"
897 ),
898 }));
899 }
900
901 if self.private_base_image.is_some() && platform != Platform::Aws {
904 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
905 capability: "privateBaseImage".to_string(),
906 platform: platform.to_string(),
907 }));
908 }
909
910 if platform == Platform::Azure && matches!(&self.code, SandboxCode::Image { .. }) {
913 self.azure_image()?;
914 }
915
916 if let Some(seconds) = self.lifecycle.max_lifetime_seconds {
919 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
921
922 if seconds == 0 {
923 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
924 resource_id: self.id.clone(),
925 field: "maxLifetimeSeconds".to_string(),
926 value: "0".to_string(),
927 reason: "a sandbox must be allowed to run for at least 1 second".to_string(),
928 }));
929 }
930
931 let ceiling = match platform {
936 Platform::Aws => Some((AWS_MAX_LIFETIME_SECONDS, "AWS runs a MicroVM for")),
937 Platform::Kubernetes => {
938 Some((KUBERNETES_MAX_LIFETIME_SECONDS, "Kubernetes runs a pod for"))
939 }
940 Platform::Gcp => None,
943 Platform::Azure | Platform::Local | Platform::Machines | Platform::Test => None,
946 };
947 if let Some((max, runs_for)) = ceiling {
948 if seconds > max {
949 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
950 resource_id: self.id.clone(),
951 field: "maxLifetimeSeconds".to_string(),
952 value: seconds.to_string(),
953 reason: format!("{runs_for} between 1 and {max} seconds"),
954 }));
955 }
956 }
957 }
958
959 let Some(limits) = self.limits.as_ref() else {
960 return self.validate_capabilities(&capabilities, platform);
962 };
963
964 validate_quantity(&self.id, "cpu", &limits.cpu)?;
965 validate_quantity(&self.id, "memory", &limits.memory)?;
966 validate_quantity(&self.id, "disk", &limits.disk)?;
967
968 if let Some(max_processes) = limits.max_processes {
969 if max_processes == 0 {
970 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
971 resource_id: self.id.clone(),
972 field: "maxProcesses".to_string(),
973 value: "0".to_string(),
974 reason: "a sandbox that may run no processes cannot run code".to_string(),
975 }));
976 }
977 capabilities.require(SandboxCapability::ProcessLimit, platform)?;
978 }
979
980 capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
983
984 if platform == Platform::Azure {
985 self.azure_sandbox_limits()?;
986 }
987
988 if platform == Platform::Gcp {
989 self.gcp_sandbox_limits()?;
990 }
991
992 if platform == Platform::Aws {
993 self.microvm_tier()?;
996 }
997
998 self.validate_capabilities(&capabilities, platform)
999 }
1000
1001 pub fn azure_image(&self) -> Result<AzureSandboxImage<'_>> {
1005 let SandboxCode::Image { image, .. } = &self.code else {
1006 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1007 resource_id: self.id.clone(),
1008 field: "code".to_string(),
1009 value: "source".to_string(),
1010 reason: "the sandbox still has unbuilt source code. Run 'alien build' first"
1011 .to_string(),
1012 }));
1013 };
1014
1015 classify_azure_sandbox_image(image).ok_or_else(|| {
1016 let image = image.trim();
1017 AlienError::new(ErrorData::SandboxLimitInvalid {
1018 resource_id: self.id.clone(),
1019 field: "code.image".to_string(),
1020 value: image.to_string(),
1021 reason: if image.is_empty() {
1022 "a sandbox has to name an image".to_string()
1023 } else {
1024 "Azure creates a sandbox from a catalog name such as 'ubuntu' or from a \
1025 registry image such as 'docker.io/library/python:3.14-slim'"
1026 .to_string()
1027 },
1028 })
1029 })
1030 }
1031
1032 pub fn gcp_sandbox_limits(&self) -> Result<()> {
1035 let Some(limits) = self.limits.as_ref() else {
1036 return Ok(());
1037 };
1038 let over_cap =
1039 quantity_exceeds_bytes(&limits.disk, GCP_MAX_DISK_BYTES).ok_or_else(|| {
1040 AlienError::new(ErrorData::SandboxLimitInvalid {
1041 resource_id: self.id.clone(),
1042 field: "disk".to_string(),
1043 value: limits.disk.clone(),
1044 reason: "expected a size such as 8Gi".to_string(),
1045 })
1046 })?;
1047 if over_cap {
1048 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1049 resource_id: self.id.clone(),
1050 field: "disk".to_string(),
1051 value: limits.disk.clone(),
1052 reason: "GCP Agent Platform caps a sandbox's ephemeral storage at 10Gi; declare \
1053 10Gi or less"
1054 .to_string(),
1055 }));
1056 }
1057 Ok(())
1058 }
1059
1060 pub fn azure_sandbox_limits(&self) -> Result<()> {
1064 let Some(limits) = self.limits.as_ref() else {
1065 return Ok(());
1068 };
1069
1070 let refused = |field: &str, value: &str, reason: &str| {
1071 AlienError::new(ErrorData::SandboxLimitInvalid {
1072 resource_id: self.id.clone(),
1073 field: field.to_string(),
1074 value: value.to_string(),
1075 reason: reason.to_string(),
1076 })
1077 };
1078
1079 let cpu_millicores = millicores(&limits.cpu)
1080 .ok_or_else(|| refused("cpu", &limits.cpu, "expected cores or millicores"))?;
1081
1082 if cpu_millicores % AZURE_CPU_STEP_MILLICORES != 0
1086 || !(AZURE_CPU_STEP_MILLICORES..=AZURE_MAX_CPU_MILLICORES).contains(&cpu_millicores)
1087 {
1088 return Err(refused(
1089 "cpu",
1090 &limits.cpu,
1091 "Azure allocates cpu in steps of 250m from 250m to 16000m",
1092 ));
1093 }
1094
1095 let memory_ceiling_mib = cpu_millicores * AZURE_MEMORY_MIB_PER_CORE / 1000;
1097 let disk_ceiling_mib = cpu_millicores * AZURE_DISK_MIB_PER_CORE / 1000;
1098
1099 let memory_mib = quantity_mib(&limits.memory)
1100 .ok_or_else(|| refused("memory", &limits.memory, "Azure sizes memory in whole MiB"))?;
1101 if memory_mib > memory_ceiling_mib {
1102 return Err(refused(
1103 "memory",
1104 &limits.memory,
1105 &format!(
1106 "Azure allows at most 2Gi of memory per core, or {memory_ceiling_mib}Mi \
1107 at the declared cpu"
1108 ),
1109 ));
1110 }
1111
1112 let disk_mib = quantity_mib(&limits.disk)
1113 .ok_or_else(|| refused("disk", &limits.disk, "Azure sizes disk in whole MiB"))?;
1114 if disk_mib > disk_ceiling_mib {
1115 return Err(refused(
1116 "disk",
1117 &limits.disk,
1118 &format!(
1119 "Azure allows at most 20Gi of disk per core, or {disk_ceiling_mib}Mi at \
1120 the declared cpu"
1121 ),
1122 ));
1123 }
1124
1125 Ok(())
1126 }
1127
1128 pub fn microvm_tier(&self) -> Result<MicrovmTier> {
1135 let Some(limits) = self.limits.as_ref() else {
1136 return Ok(MICROVM_TIERS[2]);
1140 };
1141
1142 let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
1143 AlienError::new(ErrorData::SandboxLimitInvalid {
1144 resource_id: self.id.clone(),
1145 field: "memory".to_string(),
1146 value: limits.memory.clone(),
1147 reason: "AWS sizes a MicroVM in whole MiB".to_string(),
1148 })
1149 })?;
1150 let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
1151 AlienError::new(ErrorData::SandboxLimitInvalid {
1152 resource_id: self.id.clone(),
1153 field: "disk".to_string(),
1154 value: limits.disk.clone(),
1155 reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
1156 })
1157 })?;
1158 let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
1159 AlienError::new(ErrorData::SandboxLimitInvalid {
1160 resource_id: self.id.clone(),
1161 field: "cpu".to_string(),
1162 value: limits.cpu.clone(),
1163 reason: "expected cores or millicores".to_string(),
1164 })
1165 })?;
1166
1167 let sized = |tier: &&MicrovmTier| {
1172 tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
1173 };
1174
1175 let tier = MICROVM_TIERS
1176 .iter()
1177 .rev()
1178 .find(sized)
1179 .copied()
1180 .ok_or_else(|| {
1181 AlienError::new(ErrorData::SandboxLimitInvalid {
1182 resource_id: self.id.clone(),
1183 field: "memory".to_string(),
1184 value: limits.memory.clone(),
1185 reason: format!(
1186 "a Lambda MicroVM bursts to four times its baseline, so the smallest \
1187 ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
1188 disk fit no size",
1189 limits.memory, limits.disk
1190 ),
1191 })
1192 })?;
1193
1194 let required_millicores = i64::from(tier.peak_vcpu) * 1000;
1195 if cpu_millicores < required_millicores {
1196 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1197 resource_id: self.id.clone(),
1198 field: "cpu".to_string(),
1199 value: limits.cpu.clone(),
1200 reason: format!(
1201 "AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
1202 reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
1203 limits.memory, tier.peak_vcpu, tier.peak_vcpu
1204 ),
1205 }));
1206 }
1207
1208 Ok(tier)
1209 }
1210
1211 fn validate_capabilities(
1213 &self,
1214 capabilities: &SandboxCapabilities,
1215 platform: Platform,
1216 ) -> Result<()> {
1217 if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
1218 capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
1219 }
1220
1221 if let SandboxEgress::AllowDomains { domains } = &self.egress {
1227 if domains.is_empty() {
1228 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1229 resource_id: self.id.clone(),
1230 field: "egress.domains".to_string(),
1231 value: "[]".to_string(),
1232 reason: "an allowlist naming no domain denies everything; declare \
1233 egress: deny if that is what was meant"
1234 .to_string(),
1235 }));
1236 }
1237 }
1238
1239 if matches!(self.egress, SandboxEgress::None) {
1240 capabilities.require(SandboxCapability::EgressDeny, platform)?;
1241 }
1242
1243 if platform == Platform::Gcp && matches!(self.egress, SandboxEgress::Internet) {
1251 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1252 capability: "egress internet: there is no enforcement point outside the guest on GCP Agent Platform without PSC-I or VPC Service Controls, so a host:port policy could not be enforced; declare egress none".to_string(),
1253 platform: platform.to_string(),
1254 }));
1255 }
1256
1257 if platform == Platform::Gcp
1260 && self
1261 .preview_ports
1262 .contains(&crate::sandbox_image::GCP_AGENT_PLATFORM.port)
1263 {
1264 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1265 resource_id: self.id.clone(),
1266 field: "previewPorts".to_string(),
1267 value: crate::sandbox_image::GCP_AGENT_PLATFORM.port.to_string(),
1268 reason: "that port is the Alien agent's own on GCP Agent Platform; choose \
1269 another port for the workload"
1270 .to_string(),
1271 }));
1272 }
1273
1274 if !self.preview_ports.is_empty() {
1275 capabilities.require(SandboxCapability::Preview, platform)?;
1276 if platform == Platform::Azure
1277 && matches!(self.azure_image(), Ok(AzureSandboxImage::Catalog(_)))
1278 {
1279 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1280 capability:
1281 "preview (a catalog image runs without the Alien agent that issues \
1282 the capability; build the sandbox from source)"
1283 .to_string(),
1284 platform: platform.to_string(),
1285 }));
1286 }
1287 }
1288
1289 if self.lifecycle.idle_pause_seconds.is_some() {
1290 if platform == Platform::Gcp {
1293 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1294 capability: "idle pause policy: the GCP Agent Platform backend has no idle policy and cannot keep a sandbox's state across a pause; remove the idle policy".to_string(),
1295 platform: platform.to_string(),
1296 }));
1297 }
1298 capabilities.require(SandboxCapability::PauseResume, platform)?;
1299 }
1300
1301 if self.lifecycle.max_lifetime_seconds.is_some() {
1302 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
1303 }
1304
1305 Ok(())
1306 }
1307}
1308
1309fn default_limits() -> SandboxLimits {
1314 SandboxLimits {
1315 cpu: "1".to_string(),
1316 memory: "2Gi".to_string(),
1317 disk: "8Gi".to_string(),
1318 max_processes: None,
1319 }
1320}
1321
1322fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
1324 let invalid = |reason: &str| {
1325 AlienError::new(ErrorData::SandboxLimitInvalid {
1326 resource_id: resource_id.to_string(),
1327 field: field.to_string(),
1328 value: value.to_string(),
1329 reason: reason.to_string(),
1330 })
1331 };
1332
1333 let digits_end = value
1334 .find(|c: char| !c.is_ascii_digit() && c != '.')
1335 .unwrap_or(value.len());
1336 let (number, suffix) = value.split_at(digits_end);
1337
1338 let parsed: f64 = number
1339 .parse()
1340 .map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
1341
1342 if parsed <= 0.0 {
1343 return Err(invalid("must be greater than zero"));
1344 }
1345
1346 const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
1347 if !SUFFIXES.contains(&suffix) {
1348 return Err(invalid(
1349 "unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
1350 ));
1351 }
1352
1353 Ok(())
1354}
1355
1356fn split_quantity(value: &str) -> Option<(f64, &str)> {
1358 let trimmed = value.trim();
1359 let digits_end = trimmed
1360 .find(|c: char| !c.is_ascii_digit() && c != '.')
1361 .unwrap_or(trimmed.len());
1362 let (number, suffix) = trimmed.split_at(digits_end);
1363 number.parse().ok().map(|number| (number, suffix))
1364}
1365
1366pub fn quantity_mib(value: &str) -> Option<i64> {
1372 let (number, suffix) = split_quantity(value)?;
1373 let bytes = match suffix {
1374 "" => number,
1375 "k" => number * 1e3,
1376 "M" => number * 1e6,
1377 "G" => number * 1e9,
1378 "T" => number * 1e12,
1379 "Ki" => number * 1024.0,
1380 "Mi" => number * 1024.0 * 1024.0,
1381 "Gi" => number * 1024.0 * 1024.0 * 1024.0,
1382 "Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
1383 _ => return None,
1385 };
1386 Some((bytes / (1024.0 * 1024.0)) as i64)
1387}
1388
1389fn quantity_exceeds_bytes(value: &str, cap_bytes: u128) -> Option<bool> {
1392 let trimmed = value.trim();
1393 let digits_end = trimmed
1394 .find(|c: char| !c.is_ascii_digit() && c != '.')
1395 .unwrap_or(trimmed.len());
1396 let (number, suffix) = trimmed.split_at(digits_end);
1397 let unit: u128 = match suffix {
1398 "" => 1,
1399 "k" => 1_000,
1400 "M" => 1_000_000,
1401 "G" => 1_000_000_000,
1402 "T" => 1_000_000_000_000,
1403 "Ki" => 1 << 10,
1404 "Mi" => 1 << 20,
1405 "Gi" => 1 << 30,
1406 "Ti" => 1 << 40,
1407 _ => return None,
1408 };
1409 let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
1410 if (whole.is_empty() && fraction.is_empty()) || fraction.contains('.') {
1411 return None;
1412 }
1413 let digits = format!("{whole}{fraction}");
1414 let scale = 10u128.checked_pow(u32::try_from(fraction.len()).ok()?)?;
1415 let mantissa: u128 = digits.parse().ok()?;
1416 Some(mantissa.checked_mul(unit)? > cap_bytes.checked_mul(scale)?)
1418}
1419
1420pub fn millicores(value: &str) -> Option<i64> {
1422 let (number, suffix) = split_quantity(value)?;
1423 match suffix {
1424 "" => Some((number * 1000.0) as i64),
1425 "m" => Some(number as i64),
1426 _ => None,
1427 }
1428}
1429
1430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1432#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1433#[serde(rename_all = "camelCase")]
1434pub struct SandboxOutputs {
1435 pub parent_name: String,
1437 #[serde(skip_serializing_if = "Option::is_none")]
1439 pub identifier: Option<String>,
1440 #[serde(skip_serializing_if = "Option::is_none")]
1442 pub endpoint: Option<String>,
1443}
1444
1445impl ResourceOutputsDefinition for SandboxOutputs {
1446 fn get_resource_type(&self) -> ResourceType {
1447 Sandbox::RESOURCE_TYPE
1448 }
1449
1450 fn as_any(&self) -> &dyn Any {
1451 self
1452 }
1453
1454 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
1455 Box::new(self.clone())
1456 }
1457
1458 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
1459 other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
1460 }
1461
1462 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1463 serde_json::to_value(self)
1464 }
1465}
1466
1467impl ResourceDefinition for Sandbox {
1468 fn get_resource_type(&self) -> ResourceType {
1469 Self::RESOURCE_TYPE
1470 }
1471
1472 fn id(&self) -> &str {
1473 &self.id
1474 }
1475
1476 fn replace_after_failed_create_is_safe(&self) -> bool {
1477 false
1480 }
1481
1482 fn get_dependencies(&self) -> Vec<ResourceRef> {
1483 Vec::new()
1484 }
1485
1486 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1487 let new_sandbox = new_config
1488 .as_any()
1489 .downcast_ref::<Sandbox>()
1490 .ok_or_else(|| {
1491 AlienError::new(ErrorData::UnexpectedResourceType {
1492 resource_id: self.id.clone(),
1493 expected: Self::RESOURCE_TYPE,
1494 actual: new_config.get_resource_type(),
1495 })
1496 })?;
1497
1498 if self.id != new_sandbox.id {
1499 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1500 resource_id: self.id.clone(),
1501 reason: "the 'id' field is immutable".to_string(),
1502 }));
1503 }
1504
1505 Ok(())
1506 }
1507
1508 fn as_any(&self) -> &dyn Any {
1509 self
1510 }
1511
1512 fn as_any_mut(&mut self) -> &mut dyn Any {
1513 self
1514 }
1515
1516 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1517 Box::new(self.clone())
1518 }
1519
1520 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1521 other.as_any().downcast_ref::<Sandbox>() == Some(self)
1522 }
1523
1524 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1525 serde_json::to_value(self)
1526 }
1527}
1528
1529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1531pub enum AzureSandboxImage<'a> {
1532 Catalog(&'a str),
1534 Registry(&'a str),
1537}
1538
1539impl<'a> AzureSandboxImage<'a> {
1540 pub fn as_str(&self) -> &'a str {
1542 match self {
1543 Self::Catalog(value) | Self::Registry(value) => value,
1544 }
1545 }
1546}
1547
1548pub const AZURE_DISK_IMAGE_LABEL: &str = "alienImage";
1550
1551pub fn classify_azure_sandbox_image(image: &str) -> Option<AzureSandboxImage<'_>> {
1555 let image = image.trim();
1556 if image.is_empty() {
1557 return None;
1558 }
1559 if image
1560 .chars()
1561 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1562 {
1563 return Some(AzureSandboxImage::Catalog(image));
1564 }
1565 (image.contains(|c| matches!(c, '/' | ':' | '@')) && OCI_REFERENCE.is_match(image))
1566 .then_some(AzureSandboxImage::Registry(image))
1567}
1568
1569pub fn azure_disk_image_label(reference: &str) -> String {
1572 let digest = format!("{:x}", Sha256::digest(reference.trim().as_bytes()));
1573 digest[..32].to_string()
1574}
1575
1576static OCI_REFERENCE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1578 let domain_component = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
1579 let domain = format!(r"{domain_component}(?:\.{domain_component})*(?::[0-9]+)?");
1580 let path_component = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
1581 let name = format!(r"(?:{domain}/)?{path_component}(?:/{path_component})*");
1582 let tag = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}";
1583 let digest = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
1584 regex::Regex::new(&format!(r"^{name}(?::{tag})?(?:@{digest})?$"))
1585 .expect("the OCI reference grammar compiles")
1586});
1587
1588pub const BUNDLE_REGION_TOKEN: &str = "{region}";
1593
1594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1596pub enum BundleUri<'a> {
1597 Literal(&'a str),
1599 Regional { before: &'a str, after: &'a str },
1602}
1603
1604pub fn stable_bundle_key_prefix(key: &str) -> Option<&str> {
1608 let (above_file, _) = key.rsplit_once('/')?;
1609 let (above_version, _) = above_file.rsplit_once('/')?;
1610 Some(above_version)
1611}
1612
1613pub fn parse_bundle_uri(uri: &str) -> std::result::Result<BundleUri<'_>, String> {
1619 let path = uri
1620 .strip_prefix("s3://")
1621 .ok_or_else(|| format!("'{uri}' is not an s3:// URI"))?;
1622 let (bucket, key) = path
1623 .split_once('/')
1624 .ok_or_else(|| format!("'{uri}' names a bucket with no object key"))?;
1625
1626 if path.contains('*') || path.contains('?') {
1630 return Err(format!(
1631 "'{uri}' carries an IAM wildcard; the bundle's path is interpolated into the build \
1632 role's grant, so '*' and '?' would widen it past the bundle"
1633 ));
1634 }
1635
1636 if key.contains('{') || key.contains('}') {
1637 return Err(format!(
1638 "'{uri}' places a token in the object key; {BUNDLE_REGION_TOKEN} is accepted in the \
1639 bucket name alone"
1640 ));
1641 }
1642
1643 let Some((before, after)) = bucket.split_once(BUNDLE_REGION_TOKEN) else {
1644 if bucket.contains('{') || bucket.contains('}') {
1645 return Err(format!(
1646 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the \
1647 only one"
1648 ));
1649 }
1650 return Ok(BundleUri::Literal(uri));
1651 };
1652
1653 if after.contains(BUNDLE_REGION_TOKEN) {
1654 return Err(format!("'{uri}' repeats {BUNDLE_REGION_TOKEN}"));
1655 }
1656 if before.contains('{') || before.contains('}') || after.contains('{') || after.contains('}') {
1657 return Err(format!(
1658 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the only one"
1659 ));
1660 }
1661
1662 Ok(BundleUri::Regional {
1663 before: &uri[.."s3://".len() + before.len()],
1664 after: &uri["s3://".len() + before.len() + BUNDLE_REGION_TOKEN.len()..],
1665 })
1666}
1667
1668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1670pub enum EcrImageRegion<'a> {
1671 Literal(&'a str),
1673 Deployment,
1675}
1676
1677#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1679pub struct EcrImageRepository<'a> {
1680 pub account_id: &'a str,
1681 pub region: EcrImageRegion<'a>,
1682 pub repository: &'a str,
1684}
1685
1686impl EcrImageRepository<'_> {
1687 pub fn arn(&self, partition: &str, region: &str) -> String {
1690 let region = match self.region {
1691 EcrImageRegion::Literal(region) => region,
1692 EcrImageRegion::Deployment => region,
1693 };
1694 format!(
1695 "arn:{partition}:ecr:{region}:{}:repository/{}",
1696 self.account_id, self.repository
1697 )
1698 }
1699}
1700
1701pub fn parse_ecr_image_repository(
1707 image: &str,
1708) -> std::result::Result<EcrImageRepository<'_>, String> {
1709 let refuse = |reason: &str| format!("privateBaseImage '{image}' {reason}");
1710 let (host, path) = image
1711 .split_once('/')
1712 .ok_or_else(|| refuse("names no repository"))?;
1713 let (account_id, rest) = host.split_once(".dkr.ecr.").ok_or_else(|| {
1714 refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)")
1715 })?;
1716 let region = rest
1718 .strip_suffix(".amazonaws.com.cn")
1719 .or_else(|| rest.strip_suffix(".amazonaws.com"))
1720 .ok_or_else(|| refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)"))?;
1721 if account_id.len() != 12 || !account_id.bytes().all(|b| b.is_ascii_digit()) {
1722 return Err(refuse("names no 12-digit account in its registry host"));
1723 }
1724 let region = if region == BUNDLE_REGION_TOKEN {
1725 EcrImageRegion::Deployment
1726 } else if !region.is_empty()
1727 && region
1728 .bytes()
1729 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1730 {
1731 EcrImageRegion::Literal(region)
1732 } else {
1733 return Err(refuse(&format!(
1734 "names no region in its registry host; give one or {BUNDLE_REGION_TOKEN}"
1735 )));
1736 };
1737
1738 let repository = match path.split_once('@') {
1739 Some((repository, _digest)) => repository,
1740 None => match path.rsplit_once('/') {
1741 Some((parent, last)) => match last.split_once(':') {
1742 Some((name, _tag)) => &path[..parent.len() + 1 + name.len()],
1743 None => path,
1744 },
1745 None => path.split_once(':').map_or(path, |(name, _tag)| name),
1746 },
1747 };
1748 let valid_segment = |segment: &str| {
1749 !segment.is_empty()
1750 && segment.bytes().all(|b| {
1751 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
1752 })
1753 };
1754 if !repository.split('/').all(valid_segment) {
1755 return Err(refuse(
1756 "names a repository outside ECR's grammar (lowercase letters, digits, '.', '_', '-', and '/' between them)",
1757 ));
1758 }
1759 Ok(EcrImageRepository {
1760 account_id,
1761 region,
1762 repository,
1763 })
1764}
1765
1766#[cfg(test)]
1767mod tests {
1768 use super::*;
1769
1770 #[test]
1771 fn private_database_setup_accepts_the_default_network() {
1772 for lifecycle in [
1773 crate::ResourceLifecycle::Frozen,
1774 crate::ResourceLifecycle::Live,
1775 ] {
1776 let stack = crate::Stack::new("database".to_string())
1777 .add(
1778 crate::Postgres::new("metadata".to_string()).build(),
1779 lifecycle,
1780 )
1781 .build();
1782 assert!(!restricts_network_mode(&stack, false));
1783 assert!(!restricts_network_mode(&stack, true));
1784 }
1785 assert!(!restricts_network_mode(
1786 &crate::Stack::new("empty".to_string()).build(),
1787 false,
1788 ));
1789 }
1790
1791 fn repository_key(image: &str) -> String {
1794 match parse_ecr_image_repository(image) {
1795 Ok(parsed) => {
1796 let host = image.split_once('/').map_or(image, |(host, _)| host);
1797 format!("{host}/{}", parsed.repository)
1798 }
1799 Err(_) => image.to_string(),
1800 }
1801 }
1802
1803 #[test]
1804 fn a_private_base_image_names_one_repository() {
1805 let vectors: serde_json::Value = serde_json::from_str(include_str!(
1806 "../../tests/fixtures/ecr-image-repository-parity.json"
1807 ))
1808 .expect("the ECR repository vectors must be JSON");
1809 let field = |case: &serde_json::Value, name: &str| {
1810 case[name]
1811 .as_str()
1812 .unwrap_or_else(|| panic!("vector must carry {name}: {case}"))
1813 .to_string()
1814 };
1815
1816 for case in vectors["accepted"].as_array().expect("accepted vectors") {
1817 let image = field(case, "image");
1818 let region = field(case, "region");
1819 let region = if region == BUNDLE_REGION_TOKEN {
1820 EcrImageRegion::Deployment
1821 } else {
1822 EcrImageRegion::Literal(®ion)
1823 };
1824 assert_eq!(
1825 parse_ecr_image_repository(&image),
1826 Ok(EcrImageRepository {
1827 account_id: &field(case, "accountId"),
1828 region,
1829 repository: &field(case, "repository"),
1830 }),
1831 "{image}"
1832 );
1833 assert_eq!(
1834 repository_key(&image),
1835 field(case, "repositoryKey"),
1836 "{image}"
1837 );
1838 }
1839
1840 for case in vectors["refused"].as_array().expect("refused vectors") {
1841 let image = field(case, "image");
1842 assert!(
1843 parse_ecr_image_repository(&image).is_err(),
1844 "{image} must be refused"
1845 );
1846 assert_eq!(
1847 repository_key(&image),
1848 field(case, "repositoryKey"),
1849 "{image}"
1850 );
1851 }
1852 }
1853
1854 #[test]
1855 fn a_repository_arn_takes_the_deployment_region_only_where_the_host_leaves_it() {
1856 let regional =
1857 parse_ecr_image_repository("123456789012.dkr.ecr.{region}.amazonaws.com/team/base:1")
1858 .expect("parses");
1859 let pinned =
1860 parse_ecr_image_repository("123456789012.dkr.ecr.eu-west-1.amazonaws.com/team/base:1")
1861 .expect("parses");
1862 assert_eq!(
1863 regional.arn("aws-us-gov", "us-gov-west-1"),
1864 "arn:aws-us-gov:ecr:us-gov-west-1:123456789012:repository/team/base"
1865 );
1866 assert_eq!(
1867 pinned.arn("aws", "us-east-1"),
1868 "arn:aws:ecr:eu-west-1:123456789012:repository/team/base"
1869 );
1870 }
1871
1872 #[test]
1875 fn a_uri_carrying_an_iam_wildcard_is_refused() {
1876 for uri in [
1877 "s3://acme/team-*/v1/bundle.zip",
1878 "s3://acme/sandbox-bundle/f00d/bundle?.zip",
1879 "s3://acme-*/sandbox-bundle/f00d/bundle.zip",
1880 ] {
1881 let error = parse_bundle_uri(uri).expect_err("a wildcard must be refused");
1882 assert!(error.contains("IAM wildcard"), "for {uri}: {error}");
1883 }
1884
1885 parse_bundle_uri("s3://acme/sandbox-bundle/f00d/bundle.zip")
1886 .expect("an ordinary key still parses");
1887 }
1888
1889 #[test]
1893 fn a_grantable_prefix_ends_above_the_segment_that_moves() {
1894 assert_eq!(
1895 stable_bundle_key_prefix("sandbox-bundle/f00dcafe/bundle.zip"),
1896 Some("sandbox-bundle")
1897 );
1898 assert_eq!(
1899 stable_bundle_key_prefix("artifacts/team-a/sandbox/f00dcafe/bundle.zip"),
1900 Some("artifacts/team-a/sandbox"),
1901 "a deeper key narrows the prefix, it never widens to the first segment"
1902 );
1903
1904 assert_eq!(stable_bundle_key_prefix("agents/bundle.zip"), None);
1907 assert_eq!(stable_bundle_key_prefix("bundle.zip"), None);
1908 }
1909
1910 fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
1911 Sandbox::new("agent-sbx".to_string())
1912 .code(SandboxCode::Image {
1913 image: "ubuntu".to_string(),
1914 bundled_from: None,
1915 })
1916 .limits(SandboxLimits {
1917 cpu: "1".to_string(),
1918 memory: "2Gi".to_string(),
1919 disk: "10Gi".to_string(),
1920 max_processes: None,
1921 })
1922 .egress(egress)
1923 .lifecycle(SandboxLifecyclePolicy {
1924 max_lifetime_seconds: None,
1925 idle_pause_seconds: None,
1926 })
1927 .preview_ports(preview_ports)
1928 .build()
1929 }
1930
1931 #[test]
1934 fn gcp_refuses_internet_egress_at_plan_time_and_still_takes_none() {
1935 let refused = sandbox_with(SandboxEgress::Internet, vec![])
1936 .validate_for_platform(Platform::Gcp)
1937 .unwrap_err();
1938 assert!(refused.to_string().contains("egress internet"), "{refused}");
1939 assert!(
1940 refused
1941 .to_string()
1942 .contains("no enforcement point outside the guest"),
1943 "{refused}"
1944 );
1945 sandbox_with(SandboxEgress::None, vec![])
1946 .validate_for_platform(Platform::Gcp)
1947 .unwrap();
1948 }
1949
1950 #[test]
1953 fn gcp_refuses_an_idle_pause_policy_at_plan_time_and_still_takes_a_lifetime() {
1954 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
1955 Sandbox::new("sbx".to_string())
1956 .code(SandboxCode::Image {
1957 image: "ubuntu".to_string(),
1958 bundled_from: None,
1959 })
1960 .egress(SandboxEgress::None)
1961 .lifecycle(lifecycle)
1962 .build()
1963 .validate_for_platform(Platform::Gcp)
1964 };
1965 let refused = with_policy(SandboxLifecyclePolicy {
1966 max_lifetime_seconds: None,
1967 idle_pause_seconds: Some(900),
1968 })
1969 .expect_err("no idle policy exists on GCP");
1970 assert_eq!(refused.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
1971 assert!(refused.message.contains("idle"), "{}", refused.message);
1972 with_policy(SandboxLifecyclePolicy {
1973 max_lifetime_seconds: Some(3600),
1974 idle_pause_seconds: None,
1975 })
1976 .expect("a lifetime is a TTL on GCP");
1977 }
1978
1979 #[test]
1980 fn gcp_accepts_preview_ports_but_not_the_agents_own() {
1981 sandbox_with(SandboxEgress::Deny, vec![8080, 8081, 8090])
1982 .validate_for_platform(Platform::Gcp)
1983 .expect("preview ports are served on GCP, as owner access");
1984 let error = sandbox_with(SandboxEgress::Deny, vec![8080, 8971])
1985 .validate_for_platform(Platform::Gcp)
1986 .expect_err("the agent's own port is not a workload port");
1987 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "{error}");
1988 assert!(error.to_string().contains("8971"), "{error}");
1989 sandbox_with(SandboxEgress::Deny, vec![])
1990 .validate_for_platform(Platform::Gcp)
1991 .expect("a sandbox without preview ports is unaffected");
1992 }
1993
1994 #[test]
1995 fn a_uri_without_a_token_is_carried_whole() {
1996 assert_eq!(
1997 parse_bundle_uri("s3://acme-artifacts-us-east-2/agents/bundle.zip"),
1998 Ok(BundleUri::Literal(
1999 "s3://acme-artifacts-us-east-2/agents/bundle.zip"
2000 ))
2001 );
2002 }
2003
2004 #[test]
2007 fn a_regional_uri_splits_either_side_of_the_token() {
2008 let BundleUri::Regional { before, after } =
2009 parse_bundle_uri("s3://acme-artifacts-{region}/agents/bundle.zip")
2010 .expect("the token is accepted in the bucket")
2011 else {
2012 panic!("a bucket-position token must split");
2013 };
2014
2015 assert_eq!(before, "s3://acme-artifacts-");
2016 assert_eq!(after, "/agents/bundle.zip");
2017 assert_eq!(
2018 format!("{before}us-east-2{after}"),
2019 "s3://acme-artifacts-us-east-2/agents/bundle.zip",
2020 "the halves must rejoin to the URI the vendor meant"
2021 );
2022 }
2023
2024 #[test]
2027 fn a_token_this_build_cannot_resolve_is_refused() {
2028 for uri in [
2029 "s3://acme-artifacts-{regio}/bundle.zip",
2030 "s3://acme-artifacts/{region}/bundle.zip",
2031 "s3://acme-artifacts-{region}-{region}/bundle.zip",
2032 "s3://acme-artifacts/bundle-{version}.zip",
2033 "s3://acme}-artifacts-{region}/bundle.zip",
2034 "s3://acme{-artifacts-{region}/bundle.zip",
2035 ] {
2036 assert!(
2037 parse_bundle_uri(uri).is_err(),
2038 "'{uri}' must be refused before it can reach an image build"
2039 );
2040 }
2041 }
2042
2043 #[test]
2044 fn resource_type_is_stable() {
2045 assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
2046 }
2047
2048 #[test]
2049 fn capability_sets_are_per_platform() {
2050 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2051 assert!(
2052 gcp.reconnect,
2053 "generation from the container boot id makes a sandbox reachable across processes"
2054 );
2055 assert!(gcp.preview, "preview is offered as owner access");
2056 assert!(gcp.enforced_limits);
2057
2058 let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
2059 assert!(azure.files, "every backend moves files");
2060 assert!(gcp.files);
2061 assert!(azure.domain_egress_rules);
2064 assert!(azure.egress_deny);
2065 assert!(azure.enforced_limits);
2068 assert!(azure.pause_resume);
2069 assert!(!azure.snapshot);
2071 assert!(
2072 azure.preview,
2073 "the in-sandbox agent issues a port-scoped capability"
2074 );
2075
2076 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2077 assert!(!aws.snapshot, "AWS has no user-callable sandbox snapshot");
2078 assert!(aws.pause_resume);
2079
2080 let k8s =
2081 SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
2082 assert!(
2083 k8s.preview,
2084 "an in-cluster caller previews through the agent route"
2085 );
2086 }
2087
2088 #[test]
2097 fn supervisor_isolation_is_per_platform() {
2098 let value = |platform| {
2099 SandboxCapabilities::for_platform(platform)
2100 .expect("supported")
2101 .supervisor_isolation
2102 };
2103
2104 assert!(
2105 value(Platform::Aws),
2106 "root agent setuids the command to 60000"
2107 );
2108 assert!(
2109 value(Platform::Local),
2110 "the supervisor is on the host, outside the container"
2111 );
2112 assert!(
2113 value(Platform::Kubernetes),
2114 "root boot splits the command off the supervisor"
2115 );
2116 assert!(!value(Platform::Azure), "no Alien process runs the command");
2117 assert!(
2118 !value(Platform::Gcp),
2119 "no separate supervisor identity runs the command"
2120 );
2121 }
2122
2123 #[test]
2127 fn supervisor_isolation_separates_aws_from_a_subprocess_backend() {
2128 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2129 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2130
2131 assert_eq!(
2132 aws.supervisor_pid_namespace, gcp.supervisor_pid_namespace,
2133 "the older axis cannot tell them apart"
2134 );
2135 assert!(
2136 aws.supervisor_isolation,
2137 "AWS setuids the command off the supervisor"
2138 );
2139 assert!(
2140 !gcp.supervisor_isolation,
2141 "the command runs under no separate supervisor identity"
2142 );
2143 }
2144
2145 #[test]
2150 fn gcp_agent_platform_row_matches_measured_backend() {
2151 let row = SandboxCapabilities::gcp_agent_platform();
2152
2153 assert!(row.files, "agent file ops move over the sandbox envelope");
2154 assert!(
2155 row.reconnect,
2156 "generation is derived from the container boot id, so a sandbox is reachable across \
2157 processes"
2158 );
2159 assert!(
2160 row.preview,
2161 "preview is owner access: the edge credential is the caller's execute right"
2162 );
2163 assert!(
2164 !row.pause_resume,
2165 ":resume can return a fresh container, so a pause keeps no state"
2166 );
2167 assert!(
2168 !row.snapshot,
2169 "the create path never sends a snapshot, so none is reachable through the trait"
2170 );
2171 assert!(
2172 !row.domain_egress_rules,
2173 "VPC and DNS peering is not a hostname allowlist"
2174 );
2175 assert!(
2176 row.egress_deny,
2177 "a declared deny blocks TCP, the metadata server and DNS on the default placement"
2178 );
2179 assert!(
2180 row.enforced_limits,
2181 "ceilings are enforced, by terminating the sandbox on breach"
2182 );
2183 assert!(!row.process_limit, "no process-count ceiling is observed");
2184 assert!(row.sandbox_lifetime, "ttl maps to a sandbox expireTime");
2185 assert!(!row.supervisor_pid_namespace, "no PID-namespace isolation");
2186 assert!(
2187 !row.supervisor_isolation,
2188 "the command is not run under a separate supervisor identity"
2189 );
2190
2191 let live = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2193 assert_eq!(
2194 live, row,
2195 "the Platform::Gcp arm is the Agent Platform capability row"
2196 );
2197 }
2198
2199 #[test]
2200 fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
2201 let error = SandboxCapabilities::for_platform(Platform::Machines)
2202 .expect_err("Machines has no sandbox backend");
2203 assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
2204 }
2205
2206 #[test]
2207 fn unsupported_capability_names_platform_and_capability() {
2208 let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
2209 let error = capabilities
2210 .require(SandboxCapability::Snapshot, Platform::Gcp)
2211 .expect_err("GCP has no snapshot");
2212
2213 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2214 let rendered = error.to_string();
2215 assert!(
2216 rendered.contains("snapshot"),
2217 "names the capability: {rendered}"
2218 );
2219 assert!(rendered.contains("gcp"), "names the platform: {rendered}");
2220 }
2221
2222 #[test]
2226 fn a_hostname_allowlist_is_refused_everywhere_it_would_be_approximated() {
2227 let sandbox = sandbox_with(
2228 SandboxEgress::AllowDomains {
2229 domains: vec!["example.com".to_string()],
2230 },
2231 vec![],
2232 );
2233
2234 for platform in [
2235 Platform::Aws,
2236 Platform::Gcp,
2237 Platform::Kubernetes,
2238 Platform::Local,
2239 ] {
2240 let error = sandbox
2241 .validate_for_platform(platform)
2242 .expect_err("only Azure expresses a hostname allowlist");
2243 assert_eq!(
2244 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2245 "on {platform:?}"
2246 );
2247 }
2248
2249 assert!(
2250 SandboxCapabilities::for_platform(Platform::Azure)
2251 .expect("supported")
2252 .domain_egress_rules,
2253 "Azure's egress policy matches on host pattern"
2254 );
2255 }
2256
2257 #[test]
2260 fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
2261 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2262
2263 assert!(
2266 SandboxCapabilities::for_platform(Platform::Gcp)
2267 .expect("supported")
2268 .egress_deny
2269 );
2270
2271 for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
2272 sandbox
2273 .validate_for_platform(platform)
2274 .expect("deny is enforced here");
2275 }
2276
2277 let egress_only = Sandbox::new("sbx".to_string())
2279 .code(SandboxCode::Image {
2280 image: "alpine".to_string(),
2281 bundled_from: None,
2282 })
2283 .egress(SandboxEgress::None)
2284 .lifecycle(SandboxLifecyclePolicy {
2285 max_lifetime_seconds: None,
2286 idle_pause_seconds: None,
2287 })
2288 .build();
2289
2290 egress_only
2291 .validate_for_platform(Platform::Azure)
2292 .expect("Azure creates the sandbox under a Deny policy with full inspection");
2293 }
2294
2295 #[test]
2299 fn a_sandbox_declaring_no_ceilings_takes_the_platforms_own() {
2300 let undeclared = Sandbox::new("sbx".to_string())
2301 .code(SandboxCode::Image {
2302 image: "alpine".to_string(),
2303 bundled_from: None,
2304 })
2305 .egress(SandboxEgress::None)
2306 .lifecycle(SandboxLifecyclePolicy {
2307 max_lifetime_seconds: None,
2308 idle_pause_seconds: None,
2309 })
2310 .build();
2311
2312 undeclared
2313 .validate_for_platform(Platform::Azure)
2314 .expect("a sandbox naming no ceilings takes the platform's own");
2315
2316 assert_eq!(undeclared.resolved_limits().cpu, "1");
2318 }
2319
2320 #[test]
2324 fn azure_sizes_follow_the_rule_the_data_plane_states() {
2325 let sized = |cpu: &str, memory: &str, disk: &str| {
2326 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2327 let limits = sandbox
2328 .limits
2329 .as_mut()
2330 .expect("the fixture declares limits");
2331 limits.cpu = cpu.to_string();
2332 limits.memory = memory.to_string();
2333 limits.disk = disk.to_string();
2334 sandbox.validate_for_platform(Platform::Azure)
2335 };
2336
2337 sized("250m", "512Mi", "5120Mi").expect("the smallest step the data plane accepts");
2338 sized("4000m", "8192Mi", "40960Mi").expect("cpu, memory and disk are all honoured");
2339 sized("16000m", "32Gi", "320Gi").expect("the top of the range");
2340
2341 let off_step = sized("333m", "512Mi", "5120Mi").expect_err("333m is not a step of 250m");
2343 assert_eq!(off_step.code, "SANDBOX_LIMIT_INVALID", "{off_step}");
2344 assert!(off_step.to_string().contains("cpu"), "{off_step}");
2345
2346 let too_big = sized("32000m", "64Gi", "640Gi").expect_err("32 cores is over the ceiling");
2347 assert_eq!(too_big.code, "SANDBOX_LIMIT_INVALID", "{too_big}");
2348
2349 sized("1000m", "2Gi", "20Gi").expect("2Gi is exactly one core's worth");
2352 let over_memory = sized("250m", "2Gi", "5120Mi").expect_err("2Gi needs a full core");
2353 assert_eq!(over_memory.code, "SANDBOX_LIMIT_INVALID", "{over_memory}");
2354 assert!(over_memory.to_string().contains("memory"), "{over_memory}");
2355
2356 let over_disk = sized("250m", "512Mi", "20Gi").expect_err("20Gi needs a full core");
2357 assert!(over_disk.to_string().contains("disk"), "{over_disk}");
2358 }
2359
2360 #[test]
2363 fn kubernetes_root_image_needs_gateway_or_no_egress() {
2364 let root = |egress| {
2365 let mut sandbox = sandbox_with(egress, vec![]);
2366 sandbox.image_user = Some(0);
2367 sandbox
2368 };
2369 for egress in [SandboxEgress::Internet, SandboxEgress::None] {
2370 root(egress)
2371 .validate_for_platform(Platform::Kubernetes)
2372 .expect("root boot is allowed with an external egress boundary");
2373 }
2374 for egress in [
2375 SandboxEgress::Allow,
2376 SandboxEgress::AllowDomains {
2377 domains: vec!["example.com".to_string()],
2378 },
2379 ] {
2380 let error = root(egress)
2381 .validate_for_platform(Platform::Kubernetes)
2382 .expect_err("a root image under unenforced egress is refused");
2383 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2384 assert!(error.to_string().contains("root image USER"), "{error}");
2385 }
2386 root(SandboxEgress::Internet)
2387 .validate_for_platform(Platform::Local)
2388 .expect_err("Local still refuses a root image");
2389 }
2390
2391 #[test]
2392 fn preview_ports_require_the_preview_capability() {
2393 let sandbox = sandbox_with(SandboxEgress::None, vec![8080]);
2394
2395 sandbox
2396 .validate_for_platform(Platform::Aws)
2397 .expect("AWS mints a port-scoped JWE");
2398
2399 sandbox
2400 .validate_for_platform(Platform::Kubernetes)
2401 .expect("Kubernetes serves preview to in-cluster callers through the agent");
2402
2403 sandbox
2404 .validate_for_platform(Platform::Gcp)
2405 .expect("GCP serves preview to callers that already hold execute");
2406 }
2407
2408 #[test]
2410 fn azure_preview_needs_an_image_that_carries_the_agent() {
2411 let catalog = sandbox_with(SandboxEgress::None, vec![8080]);
2412 let error = catalog
2413 .validate_for_platform(Platform::Azure)
2414 .expect_err("a catalog image has no agent to issue a capability");
2415 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2416
2417 let mut registry = sandbox_with(SandboxEgress::None, vec![8080]);
2418 registry.code = SandboxCode::Image {
2419 image: "registry.example.com/workload/sandbox:1".to_string(),
2420 bundled_from: None,
2421 };
2422 registry
2423 .validate_for_platform(Platform::Azure)
2424 .expect("a registry image is built with the agent");
2425 }
2426
2427 #[test]
2431 fn a_private_base_image_is_refused_off_aws() {
2432 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2433 sandbox.code = SandboxCode::Image {
2434 image: "s3://acme-artifacts/agents/bundle.zip".to_string(),
2435 bundled_from: None,
2436 };
2437 sandbox.private_base_image =
2438 Some("123456789012.dkr.ecr.{region}.amazonaws.com/acme:tag".to_string());
2439
2440 sandbox
2441 .validate_for_platform(Platform::Aws)
2442 .expect("AWS builds its image from a bundle, so a base image sits behind code.image");
2443
2444 for platform in [
2445 Platform::Gcp,
2446 Platform::Azure,
2447 Platform::Kubernetes,
2448 Platform::Local,
2449 ] {
2450 let error = sandbox
2451 .validate_for_platform(platform)
2452 .expect_err("a backend that builds no image must refuse a base image for one");
2453 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2454 assert!(
2455 error.to_string().contains("privateBaseImage"),
2456 "the refusal must name the field the user declared: {error}"
2457 );
2458 }
2459 }
2460
2461 #[test]
2465 fn gcp_refuses_a_disk_above_its_cap_and_accepts_the_cap() {
2466 let with_disk = |disk: &str| {
2467 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2468 sandbox
2469 .limits
2470 .as_mut()
2471 .expect("the fixture declares limits")
2472 .disk = disk.to_string();
2473 sandbox
2474 };
2475
2476 let error = with_disk("20Gi")
2477 .validate_for_platform(Platform::Gcp)
2478 .expect_err("20Gi is above the Agent Platform cap");
2479 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2480 let rendered = error.to_string();
2481 assert!(rendered.contains("disk"), "names the field: {rendered}");
2482 assert!(rendered.contains("10Gi"), "names the cap: {rendered}");
2483
2484 with_disk("10Gi")
2485 .validate_for_platform(Platform::Gcp)
2486 .expect("the cap itself is allowed");
2487 with_disk("10240Mi")
2488 .validate_for_platform(Platform::Gcp)
2489 .expect("the cap in MiB is allowed");
2490 for over in ["10240.5Mi", "10241Mi", "10.0000001Gi"] {
2491 with_disk(over)
2492 .validate_for_platform(Platform::Gcp)
2493 .expect_err(&format!("{over} is above the cap and must not round down"));
2494 }
2495 with_disk("8Gi")
2496 .validate_for_platform(Platform::Gcp)
2497 .expect("the default disk is allowed");
2498 with_disk("20Gi")
2499 .validate_for_platform(Platform::Kubernetes)
2500 .expect("the cap is Agent Platform's, not every backend's");
2501 }
2502
2503 #[test]
2504 fn gcp_accepts_a_sandbox_declaring_enforced_limits() {
2505 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2506 sandbox
2507 .limits
2508 .as_mut()
2509 .expect("the fixture declares limits")
2510 .disk = "10Gi".to_string();
2511 sandbox
2512 .validate_for_platform(Platform::Gcp)
2513 .expect("Agent Platform enforces declared ceilings, by terminating on breach");
2514 }
2515
2516 #[test]
2517 fn invalid_quantities_are_rejected_with_the_offending_field() {
2518 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2519 sandbox
2520 .limits
2521 .as_mut()
2522 .expect("the fixture declares limits")
2523 .memory = "2Gb".to_string();
2524
2525 let error = sandbox
2526 .validate_for_platform(Platform::Aws)
2527 .expect_err("Gb is not a valid suffix");
2528 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2529 assert!(error.to_string().contains("memory"));
2530
2531 sandbox
2532 .limits
2533 .as_mut()
2534 .expect("the fixture declares limits")
2535 .memory = "2Gi".to_string();
2536 sandbox
2537 .limits
2538 .as_mut()
2539 .expect("the fixture declares limits")
2540 .cpu = "0".to_string();
2541 let error = sandbox
2542 .validate_for_platform(Platform::Aws)
2543 .expect_err("zero cpu is not a ceiling");
2544 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2545 }
2546
2547 #[test]
2548 fn zero_max_processes_is_rejected() {
2549 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2550 sandbox
2551 .limits
2552 .as_mut()
2553 .expect("the fixture declares limits")
2554 .max_processes = Some(0);
2555
2556 let error = sandbox
2557 .validate_for_platform(Platform::Local)
2558 .expect_err("a sandbox must be able to run at least one process");
2559 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2560 assert!(error.to_string().contains("maxProcesses"));
2561 }
2562
2563 #[test]
2567 fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
2568 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2569 sandbox
2570 .limits
2571 .as_mut()
2572 .expect("the fixture declares limits")
2573 .max_processes = Some(256);
2574
2575 sandbox
2576 .validate_for_platform(Platform::Local)
2577 .expect("Docker takes a pids limit");
2578
2579 for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
2580 let error = sandbox
2581 .validate_for_platform(platform)
2582 .expect_err("a process ceiling nothing applies must be refused");
2583 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2584 }
2585 }
2586
2587 #[test]
2592 fn a_lifetime_aws_would_reject_is_refused_while_planning() {
2593 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2594 let mut without_limits = with_limits.clone();
2595 without_limits.limits = None;
2596
2597 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2598 for seconds in [28_801, 30_000, 100_000] {
2599 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2600 let error = sandbox
2601 .validate_for_platform(Platform::Aws)
2602 .expect_err("a lifetime above what AWS runs is refused");
2603 assert_eq!(
2604 error.code, "SANDBOX_LIMIT_INVALID",
2605 "{seconds}s {declared} limits"
2606 );
2607
2608 sandbox
2610 .validate_for_platform(Platform::Kubernetes)
2611 .expect("Kubernetes takes an activeDeadlineSeconds above 28,800");
2612 }
2613
2614 sandbox.lifecycle.max_lifetime_seconds = Some(28_800);
2615 sandbox
2616 .validate_for_platform(Platform::Aws)
2617 .expect("the ceiling itself is allowed");
2618 }
2619 }
2620
2621 #[test]
2625 fn a_zero_lifetime_is_refused_while_planning() {
2626 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2627 let mut without_limits = with_limits.clone();
2628 without_limits.limits = None;
2629
2630 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2631 sandbox.lifecycle.max_lifetime_seconds = Some(0);
2632 for platform in [
2633 Platform::Aws,
2634 Platform::Kubernetes,
2635 Platform::Gcp,
2636 Platform::Azure,
2637 ] {
2638 let error = sandbox
2639 .validate_for_platform(platform)
2640 .expect_err("a zero lifetime is refused");
2641 assert_eq!(
2642 error.code, "SANDBOX_LIMIT_INVALID",
2643 "{platform} {declared} limits"
2644 );
2645 assert!(
2646 error.to_string().contains("maxLifetimeSeconds"),
2647 "{platform} {declared} limits"
2648 );
2649 }
2650
2651 for platform in [Platform::Local] {
2653 let error = sandbox
2654 .validate_for_platform(platform)
2655 .expect_err("a lifetime is refused where nothing applies it");
2656 assert_eq!(
2657 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2658 "{platform} {declared} limits"
2659 );
2660 }
2661
2662 sandbox.lifecycle.max_lifetime_seconds = Some(1);
2663 sandbox
2664 .validate_for_platform(Platform::Kubernetes)
2665 .expect("one second is the API server's floor");
2666 }
2667 }
2668
2669 #[test]
2673 fn a_lifetime_kubernetes_would_reject_is_refused_while_planning() {
2674 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2675 let mut without_limits = with_limits.clone();
2676 without_limits.limits = None;
2677
2678 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2679 for seconds in [2_147_483_648, u32::MAX] {
2680 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2681 let error = sandbox
2682 .validate_for_platform(Platform::Kubernetes)
2683 .expect_err("a lifetime above what the API server takes is refused");
2684 assert_eq!(
2685 error.code, "SANDBOX_LIMIT_INVALID",
2686 "{seconds}s {declared} limits"
2687 );
2688 assert!(
2689 error.to_string().contains("maxLifetimeSeconds"),
2690 "{seconds}s {declared} limits"
2691 );
2692 }
2693
2694 sandbox.lifecycle.max_lifetime_seconds = Some(2_147_483_647);
2695 sandbox
2696 .validate_for_platform(Platform::Kubernetes)
2697 .expect("the ceiling itself is allowed");
2698 }
2699 }
2700
2701 #[test]
2704 fn an_image_azure_cannot_pull_is_refused_while_planning() {
2705 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2706 sandbox.limits = None;
2709
2710 for image in ["ubuntu@sha256:abc", "", " ", "ubuntu latest", "ubuntu?x"] {
2712 sandbox.code = SandboxCode::Image {
2713 image: image.to_string(),
2714 bundled_from: None,
2715 };
2716 let error = sandbox
2717 .validate_for_platform(Platform::Azure)
2718 .expect_err("an image Azure has nowhere to put is refused");
2719 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "image '{image}'");
2720 }
2721
2722 for image in ["ubuntu", "ubuntu-22.04", "debian_slim"] {
2723 sandbox.code = SandboxCode::Image {
2724 image: image.to_string(),
2725 bundled_from: None,
2726 };
2727 sandbox
2728 .validate_for_platform(Platform::Azure)
2729 .unwrap_or_else(|error| panic!("'{image}' is a catalog name: {error}"));
2730 }
2731
2732 for image in [
2733 "ubuntu:24.04",
2734 "ghcr.io/myorg/sandbox:latest",
2735 "docker.io/library/python:3.14-slim",
2736 "localhost:5000/team/agent@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d",
2737 ] {
2738 sandbox.code = SandboxCode::Image {
2739 image: image.to_string(),
2740 bundled_from: None,
2741 };
2742 sandbox
2743 .validate_for_platform(Platform::Azure)
2744 .unwrap_or_else(|error| panic!("'{image}' is a registry image: {error}"));
2745 }
2746
2747 sandbox.code = SandboxCode::Image {
2749 image: " ubuntu ".to_string(),
2750 bundled_from: None,
2751 };
2752 assert_eq!(
2753 sandbox
2754 .azure_image()
2755 .expect("a padded name is still a name"),
2756 AzureSandboxImage::Catalog("ubuntu")
2757 );
2758 }
2759
2760 #[test]
2764 fn every_value_the_catalog_allowlist_accepted_is_still_a_catalog_name() {
2765 const ALPHABET: &[u8] =
2766 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
2767
2768 let assert_catalog = |value: &str| {
2769 assert_eq!(
2770 classify_azure_sandbox_image(value),
2771 Some(AzureSandboxImage::Catalog(value.trim())),
2772 "'{value}'"
2773 );
2774 };
2775
2776 for a in ALPHABET {
2777 assert_catalog(&String::from_utf8(vec![*a]).unwrap());
2778 for b in ALPHABET {
2779 assert_catalog(&String::from_utf8(vec![*a, *b]).unwrap());
2780 for c in ALPHABET {
2781 assert_catalog(&String::from_utf8(vec![*a, *b, *c]).unwrap());
2782 }
2783 }
2784 }
2785
2786 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
2787 let mut next = || {
2788 state ^= state << 13;
2789 state ^= state >> 7;
2790 state ^= state << 17;
2791 state
2792 };
2793 for _ in 0..20_000 {
2794 let len = 4 + (next() % 60) as usize;
2795 let mut value: String = (0..len)
2796 .map(|_| ALPHABET[(next() % ALPHABET.len() as u64) as usize] as char)
2797 .collect();
2798 if next() % 4 == 0 {
2799 value = format!(" {value}\t");
2800 }
2801 assert_catalog(&value);
2802 }
2803 }
2804
2805 #[test]
2808 fn the_disk_image_label_is_stable_and_label_safe() {
2809 let label = azure_disk_image_label("docker.io/library/python:3.14-slim");
2810 assert_eq!(
2811 label,
2812 azure_disk_image_label(" docker.io/library/python:3.14-slim ")
2813 );
2814 assert_ne!(
2815 label,
2816 azure_disk_image_label("docker.io/library/python:3.13-slim")
2817 );
2818 assert_eq!(label.len(), 32);
2819 assert!(label.chars().all(|c| c.is_ascii_hexdigit()), "{label}");
2820 }
2821
2822 #[test]
2826 fn a_sandbox_deadline_is_accepted_only_where_the_platform_applies_it() {
2827 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2828 sandbox.lifecycle.max_lifetime_seconds = Some(3600);
2829
2830 sandbox
2831 .validate_for_platform(Platform::Kubernetes)
2832 .expect("the kubelet enforces activeDeadlineSeconds");
2833 sandbox
2834 .validate_for_platform(Platform::Aws)
2835 .expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
2836
2837 sandbox.validate_for_platform(Platform::Azure).expect(
2838 "the binding stamps a deadline label and the controller's reaper deletes by it",
2839 );
2840
2841 for platform in [Platform::Local] {
2842 let error = sandbox
2843 .validate_for_platform(platform)
2844 .expect_err("a deadline nothing applies must be refused");
2845 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2846 }
2847 }
2848
2849 #[test]
2853 fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
2854 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2855 let tier = sandbox
2856 .microvm_tier()
2857 .expect("2Gi/1cpu/20Gi is satisfiable");
2858
2859 assert_eq!(
2860 tier.peak_memory_mib, 2048,
2861 "the peak is the declared ceiling"
2862 );
2863 assert_eq!(
2864 tier.baseline_memory_mib, 512,
2865 "which is a quarter of it as the baseline"
2866 );
2867 assert!(tier.max_disk_mib <= 20 * 1024);
2868 }
2869
2870 #[test]
2874 fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
2875 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2876 {
2877 let limits = sandbox
2878 .limits
2879 .as_mut()
2880 .expect("the fixture declares limits");
2881 limits.cpu = "1".to_string();
2882 limits.memory = "8Gi".to_string();
2883 }
2884
2885 let error = sandbox
2886 .microvm_tier()
2887 .expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
2888 assert!(
2889 error.to_string().contains("4 vCPU"),
2890 "the refusal must say what the memory ceiling implies: {error}"
2891 );
2892
2893 sandbox
2894 .limits
2895 .as_mut()
2896 .expect("the fixture declares limits")
2897 .cpu = "4".to_string();
2898 let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
2899 assert_eq!(tier.peak_memory_mib, 8192);
2900 }
2901
2902 #[test]
2905 fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
2906 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2907 sandbox
2908 .limits
2909 .as_mut()
2910 .expect("the fixture declares limits")
2911 .memory = "1Gi".to_string();
2912
2913 let error = sandbox
2914 .validate_for_platform(Platform::Aws)
2915 .expect_err("no MicroVM size peaks at or below 1Gi");
2916 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2917 assert!(
2918 error.to_string().contains("2Gi"),
2919 "the refusal must say what the smallest holdable ceiling is: {error}"
2920 );
2921 }
2922
2923 #[test]
2926 fn source_code_is_refused_where_no_backend_builds_it() {
2927 let sandbox = Sandbox::new("agent".to_string())
2928 .code(SandboxCode::Source {
2929 src: "./sandbox".to_string(),
2930 toolchain: ToolchainConfig::Docker {
2931 dockerfile: None,
2932 build_args: None,
2933 target: None,
2934 },
2935 })
2936 .egress(SandboxEgress::None)
2937 .lifecycle(SandboxLifecyclePolicy {
2938 max_lifetime_seconds: None,
2939 idle_pause_seconds: None,
2940 })
2941 .build();
2942
2943 sandbox
2944 .validate_for_platform(Platform::Aws)
2945 .expect("an AWS sandbox base image is built by `alien build`");
2946 sandbox
2947 .validate_for_platform(Platform::Azure)
2948 .expect("an Azure sandbox base image is built by `alien build`");
2949 sandbox
2950 .validate_for_platform(Platform::Gcp)
2951 .expect("a GCP sandbox base image is built by `alien build`");
2952 sandbox
2953 .validate_for_platform(Platform::Kubernetes)
2954 .expect("a Kubernetes sandbox base image is built by `alien build`");
2955
2956 for platform in [Platform::Local] {
2957 let error = sandbox
2958 .validate_for_platform(platform)
2959 .expect_err("no backend builds a sandbox image from source here");
2960 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2961 assert!(
2962 error.to_string().contains("code.image"),
2963 "the refusal must say what to write instead: {error}"
2964 );
2965 assert!(
2966 error.to_string().contains(&platform.to_string()),
2967 "the refusal must name the platform that cannot build it: {error}"
2968 );
2969 }
2970 }
2971
2972 #[test]
2975 fn every_accepted_unit_converts_rather_than_falling_back() {
2976 assert_eq!(quantity_mib("2Gi"), Some(2048));
2977 assert_eq!(quantity_mib("512Mi"), Some(512));
2978 assert_eq!(quantity_mib("4G"), Some(3814));
2979 assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
2980 assert_eq!(millicores("1"), Some(1000));
2981 assert_eq!(millicores("500m"), Some(500));
2982 }
2983
2984 #[test]
2985 fn privileged_supervisor_fixes_identity_and_requires_an_enforceable_backend() {
2986 let mut sandbox = sandbox_with(
2987 SandboxEgress::AllowDomains {
2988 domains: vec!["example.com".to_string()],
2989 },
2990 vec![],
2991 );
2992 sandbox.privileged_supervisor = Some(SandboxPrivilegedSupervisor { command_uid: 60001 });
2993 sandbox
2994 .validate_for_platform(Platform::Aws)
2995 .expect("AWS can enforce the policy in the agent");
2996 assert_eq!(sandbox.cloud_egress(), &SandboxEgress::Allow);
2997 assert_eq!(
2998 sandbox.supervisor_environment()["ALIEN_SANDBOX_EXPECTED_EXEC_UID"],
2999 "60001"
3000 );
3001 for platform in [
3002 Platform::Local,
3003 Platform::Kubernetes,
3004 Platform::Azure,
3005 Platform::Gcp,
3006 ] {
3007 let error = sandbox
3008 .validate_for_platform(platform)
3009 .expect_err("cannot grant a privilege boundary the backend lacks");
3010 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
3011 assert!(error.message.contains("privilegedSupervisor"));
3012 }
3013 for uid in [0, u32::MAX] {
3014 sandbox.privileged_supervisor.as_mut().unwrap().command_uid = uid;
3015 let error = sandbox
3016 .validate_for_platform(Platform::Aws)
3017 .expect_err("invalid uid must fail at plan time");
3018 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3019 }
3020 }
3021
3022 #[test]
3023 fn unknown_fields_are_rejected() {
3024 let json = r#"{
3025 "id": "sbx",
3026 "code": {"type": "image", "image": "ubuntu:24.04"},
3027 "limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
3028 "egress": {"mode": "deny"},
3029 "lifecycle": {},
3030 "unexpected": true
3031 }"#;
3032
3033 serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
3034 }
3035
3036 #[test]
3037 fn serialization_roundtrips() {
3038 let sandbox = sandbox_with(
3039 SandboxEgress::AllowDomains {
3040 domains: vec!["example.com".to_string()],
3041 },
3042 vec![8080, 9090],
3043 );
3044
3045 let json = serde_json::to_string(&sandbox).expect("serializes");
3046 let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
3047 assert_eq!(sandbox, restored);
3048 }
3049
3050 #[test]
3051 fn id_is_immutable_across_updates() {
3052 let original = sandbox_with(SandboxEgress::None, vec![]);
3053 let renamed = Sandbox::new("other".to_string())
3054 .code(SandboxCode::Image {
3055 image: "ubuntu".to_string(),
3056 bundled_from: None,
3057 })
3058 .limits(
3059 original
3060 .limits
3061 .clone()
3062 .expect("the fixture declares limits"),
3063 )
3064 .egress(SandboxEgress::None)
3065 .lifecycle(SandboxLifecyclePolicy {
3066 max_lifetime_seconds: None,
3067 idle_pause_seconds: None,
3068 })
3069 .build();
3070
3071 original
3072 .validate_update(&original.clone())
3073 .expect("an unchanged config is a valid update");
3074 original
3075 .validate_update(&renamed)
3076 .expect_err("renaming a sandbox is not an update");
3077 }
3078
3079 #[test]
3083 fn azure_takes_an_idle_policy_and_a_lifetime_ceiling() {
3084 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
3085 Sandbox::new("sbx".to_string())
3086 .code(SandboxCode::Image {
3087 image: "ubuntu".to_string(),
3088 bundled_from: None,
3089 })
3090 .egress(SandboxEgress::Allow)
3091 .lifecycle(lifecycle)
3092 .build()
3093 .validate_for_platform(Platform::Azure)
3094 };
3095
3096 with_policy(SandboxLifecyclePolicy {
3097 max_lifetime_seconds: None,
3098 idle_pause_seconds: Some(900),
3099 })
3100 .expect("Azure pauses a sandbox on idle");
3101
3102 with_policy(SandboxLifecyclePolicy {
3103 max_lifetime_seconds: Some(3600),
3104 idle_pause_seconds: None,
3105 })
3106 .expect("the reaper enforces a wall-clock ceiling");
3107 }
3108
3109 #[test]
3115 fn an_allowlist_with_no_domains_is_refused() {
3116 let declared = |domains: Vec<String>| {
3117 Sandbox::new("sbx".to_string())
3118 .code(SandboxCode::Image {
3119 image: "ubuntu".to_string(),
3120 bundled_from: None,
3121 })
3122 .egress(SandboxEgress::AllowDomains { domains })
3123 .lifecycle(SandboxLifecyclePolicy {
3124 max_lifetime_seconds: None,
3125 idle_pause_seconds: None,
3126 })
3127 .build()
3128 .validate_for_platform(Platform::Azure)
3129 };
3130
3131 let error = declared(vec![]).expect_err("an empty allowlist must be refused");
3132 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3133
3134 declared(vec!["api.example.com".to_string()])
3135 .expect("a named domain is what an allowlist is for");
3136 }
3137
3138 #[test]
3141 fn internet_access_switch_maps_only_the_two_expressible_modes() {
3142 assert_eq!(SandboxEgress::Allow.internet_access_switch(), Some(true));
3143 assert_eq!(SandboxEgress::None.internet_access_switch(), Some(false));
3144 assert_eq!(
3145 SandboxEgress::AllowDomains {
3146 domains: vec!["api.example.com".to_string()]
3147 }
3148 .internet_access_switch(),
3149 None,
3150 "a host list has no boolean and must not be approximated"
3151 );
3152 }
3153
3154 #[test]
3158 fn stack_state_written_before_the_lifecycle_rename_still_reads() {
3159 let stored: crate::StackResourceState = serde_json::from_value(serde_json::json!({
3160 "type": "sandbox",
3161 "config": {
3162 "id": "sandbox",
3163 "code": {
3164 "type": "image",
3165 "image": "s3://example-bundles/analysis/v1/bundle.zip"
3166 },
3167 "type": "sandbox",
3168 "egress": { "mode": "allow" },
3169 "session": { "maxLifetimeSeconds": 28800, "idleSuspendSeconds": 600 }
3170 },
3171 "status": "running",
3172 "outputs": {
3173 "type": "sandbox",
3174 "identifier": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox",
3175 "parentName": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox"
3176 },
3177 "lifecycle": "frozen",
3178 "dependencies": [
3179 { "id": "management", "type": "remote-stack-management" },
3180 { "id": "access", "type": "resource-access" }
3181 ],
3182 "controllerPlatform": "aws"
3183 }))
3184 .expect("a stack state written before the rename must still deserialize");
3185
3186 let expected = Sandbox::new("sandbox".to_string())
3187 .code(SandboxCode::Image {
3188 image: "s3://example-bundles/analysis/v1/bundle.zip".to_string(),
3189 bundled_from: None,
3190 })
3191 .egress(SandboxEgress::Allow)
3192 .lifecycle(SandboxLifecyclePolicy {
3193 max_lifetime_seconds: Some(28_800),
3194 idle_pause_seconds: Some(600),
3195 })
3196 .build();
3197 assert_eq!(stored.config.downcast_ref::<Sandbox>(), Some(&expected));
3198
3199 let rewritten = serde_json::to_value(&stored.config).expect("the sandbox serializes");
3200 assert_eq!(
3201 rewritten["lifecycle"],
3202 serde_json::json!({ "maxLifetimeSeconds": 28800, "idlePauseSeconds": 600 }),
3203 "the next write stores the current names"
3204 );
3205 assert!(rewritten.get("session").is_none());
3206 }
3207}
3208
3209#[cfg(test)]
3210mod label_format_tests {
3211 use super::*;
3212
3213 #[test]
3214 fn request_keys_are_bounded_and_safe() {
3215 for good in ["a", "A-z_9", &"x".repeat(64)] {
3216 assert!(is_valid_request_key(good), "{good}");
3217 }
3218 for bad in ["", "a b", "a/b", "a.b", "é", &"x".repeat(65)] {
3219 assert!(!is_valid_request_key(bad), "{bad}");
3220 }
3221 }
3222
3223 #[test]
3224 fn expiry_is_a_positive_integer() {
3225 assert!(is_valid_sandbox_expiry("1700000000000"));
3226 for bad in ["", "0", "-1", "1.5", "never", "+5 "] {
3227 assert!(!is_valid_sandbox_expiry(bad), "{bad}");
3228 }
3229 }
3230}