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
309#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
315#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
316#[serde(rename_all = "camelCase", deny_unknown_fields)]
317pub struct SandboxCapabilities {
318 pub files: bool,
320 pub reconnect: bool,
322 pub jobs: bool,
325 pub interactive_commands: bool,
328 pub preview: bool,
330 pub pause_resume: bool,
332 pub snapshot: bool,
334 pub domain_egress_rules: bool,
336 pub egress_deny: bool,
339 pub enforced_limits: bool,
341 pub process_limit: bool,
343 pub sandbox_lifetime: bool,
345 pub supervisor_pid_namespace: bool,
351 pub supervisor_isolation: bool,
358}
359
360impl SandboxCapabilities {
361 pub fn for_platform(platform: Platform) -> Result<Self> {
367 match platform {
368 Platform::Aws => Ok(Self {
369 files: true,
370 reconnect: true,
371 jobs: true,
372 interactive_commands: true,
375 preview: true,
376 pause_resume: true,
377 snapshot: false,
378 domain_egress_rules: false,
379 egress_deny: true,
382 enforced_limits: true,
383 process_limit: false,
385 sandbox_lifetime: true,
388 supervisor_pid_namespace: false,
393 supervisor_isolation: true,
396 }),
397 Platform::Azure => Ok(Self::azure()),
398 Platform::Gcp => Ok(Self::gcp_agent_platform()),
399 Platform::Kubernetes => Ok(Self {
400 files: true,
401 reconnect: true,
402 jobs: true,
403 interactive_commands: true,
408 preview: true,
414 pause_resume: false,
417 snapshot: false,
419 domain_egress_rules: false,
420 egress_deny: true,
421 enforced_limits: true,
422 process_limit: false,
427 sandbox_lifetime: true,
433 supervisor_pid_namespace: false,
437 supervisor_isolation: true,
443 }),
444 Platform::Local => Ok(Self {
445 files: true,
446 reconnect: true,
447 jobs: false,
449 interactive_commands: true,
452 preview: true,
453 pause_resume: false,
454 snapshot: false,
455 domain_egress_rules: false,
456 egress_deny: true,
457 enforced_limits: true,
458 process_limit: true,
460 sandbox_lifetime: false,
461 supervisor_pid_namespace: false,
464 supervisor_isolation: true,
468 }),
469 Platform::Machines | Platform::Test => {
470 Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
471 platform: platform.to_string(),
472 }))
473 }
474 }
475 }
476
477 pub fn azure() -> Self {
479 Self {
480 files: true,
481 reconnect: true,
482 jobs: true,
485 interactive_commands: true,
489 preview: true,
496 pause_resume: true,
497 snapshot: false,
501 domain_egress_rules: true,
502 egress_deny: true,
503 enforced_limits: true,
507 process_limit: false,
508 sandbox_lifetime: true,
513 supervisor_pid_namespace: false,
515 supervisor_isolation: false,
518 }
519 }
520
521 pub fn gcp_agent_platform() -> Self {
523 Self {
524 files: true,
526 reconnect: true,
530 jobs: true,
531 interactive_commands: false,
534 preview: false,
537 pause_resume: false,
540 snapshot: false,
543 domain_egress_rules: false,
545 egress_deny: true,
548 enforced_limits: true,
552 process_limit: false,
554 sandbox_lifetime: true,
556 supervisor_pid_namespace: false,
558 supervisor_isolation: false,
561 }
562 }
563
564 pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
566 let available = match capability {
567 SandboxCapability::Files => self.files,
568 SandboxCapability::Reconnect => self.reconnect,
569 SandboxCapability::Jobs => self.jobs,
570 SandboxCapability::InteractiveCommands => self.interactive_commands,
571 SandboxCapability::Preview => self.preview,
572 SandboxCapability::PauseResume => self.pause_resume,
573 SandboxCapability::Snapshot => self.snapshot,
574 SandboxCapability::DomainEgressRules => self.domain_egress_rules,
575 SandboxCapability::EgressDeny => self.egress_deny,
576 SandboxCapability::EnforcedLimits => self.enforced_limits,
577 SandboxCapability::ProcessLimit => self.process_limit,
578 SandboxCapability::SandboxLifetime => self.sandbox_lifetime,
579 SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
580 SandboxCapability::SupervisorIsolation => self.supervisor_isolation,
581 };
582
583 if available {
584 return Ok(());
585 }
586
587 Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
588 capability: capability.as_str().to_string(),
589 platform: platform.to_string(),
590 }))
591 }
592}
593
594#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
596#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
597#[serde(rename_all = "camelCase")]
598pub enum SandboxCapability {
599 Files,
601 Reconnect,
603 Jobs,
605 InteractiveCommands,
607 Preview,
609 PauseResume,
611 Snapshot,
613 DomainEgressRules,
615 EgressDeny,
617 EnforcedLimits,
619 ProcessLimit,
621 SandboxLifetime,
623 SupervisorPidNamespace,
625 SupervisorIsolation,
627}
628
629impl SandboxCapability {
630 pub fn as_str(&self) -> &'static str {
632 match self {
633 Self::Files => "files",
634 Self::Reconnect => "reconnect",
635 Self::Jobs => "jobs",
636 Self::InteractiveCommands => "interactiveCommands",
637 Self::Preview => "preview",
638 Self::PauseResume => "pauseResume",
639 Self::Snapshot => "snapshot",
640 Self::DomainEgressRules => "domainEgressRules",
641 Self::EgressDeny => "egressDeny",
642 Self::EnforcedLimits => "enforcedLimits",
643 Self::ProcessLimit => "processLimit",
644 Self::SandboxLifetime => "sandboxLifetime",
645 Self::SupervisorPidNamespace => "supervisorPidNamespace",
646 Self::SupervisorIsolation => "supervisorIsolation",
647 }
648 }
649}
650
651#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
653#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
654#[serde(rename_all = "camelCase", deny_unknown_fields)]
655pub struct SandboxPrivilegedSupervisor {
656 pub command_uid: u32,
658}
659
660#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
662#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
663#[serde(rename_all = "camelCase", deny_unknown_fields)]
664#[builder(start_fn = new)]
665pub struct Sandbox {
666 #[builder(start_fn)]
669 pub id: String,
670 #[builder(field)]
673 #[serde(default, skip_serializing_if = "Vec::is_empty")]
674 #[cfg_attr(feature = "openapi", schema(ignore))]
675 pub links: Vec<ResourceRef>,
676 pub code: SandboxCode,
678 #[builder(skip)]
681 #[serde(default, skip_serializing_if = "Option::is_none")]
682 #[cfg_attr(feature = "openapi", schema(ignore))]
683 pub image_user: Option<u32>,
684 #[serde(skip_serializing_if = "Option::is_none")]
688 pub private_base_image: Option<String>,
689 #[serde(skip_serializing_if = "Option::is_none")]
695 pub limits: Option<SandboxLimits>,
696 pub egress: SandboxEgress,
698 #[serde(default, skip_serializing_if = "Option::is_none")]
700 pub default_policy: Option<EgressPolicy>,
701 #[builder(skip)]
705 #[serde(default, skip_serializing_if = "Option::is_none")]
706 pub privileged_supervisor: Option<SandboxPrivilegedSupervisor>,
707 #[serde(alias = "session")]
712 pub lifecycle: SandboxLifecyclePolicy,
713 #[builder(default)]
717 #[serde(default, skip_serializing_if = "Vec::is_empty")]
718 pub preview_ports: Vec<u16>,
719}
720
721pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
726 !targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
727}
728
729pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
735 stack.resources().any(|(_, entry)| {
736 entry
737 .config
738 .downcast_ref::<Sandbox>()
739 .is_some_and(|sandbox| crate::sandbox_egress::sandbox_needs_connector(stack, sandbox))
740 })
741}
742
743impl Sandbox {
744 pub(crate) fn setup_digest_value(&self) -> serde_json::Value {
745 match &self.egress {
746 SandboxEgress::None => serde_json::json!({"mode":"deny"}),
747 value => serde_json::to_value(value).expect("egress serializes"),
748 }
749 }
750
751 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
753
754 pub fn id(&self) -> &str {
756 &self.id
757 }
758
759 pub fn cloud_egress(&self) -> &SandboxEgress {
762 if self.privileged_supervisor.is_some() && self.egress != SandboxEgress::Internet {
763 &SandboxEgress::Allow
764 } else {
765 &self.egress
766 }
767 }
768
769 pub fn supervisor_environment(&self) -> std::collections::BTreeMap<String, String> {
771 let mut env = std::collections::BTreeMap::new();
772 if let Some(supervisor) = &self.privileged_supervisor {
773 env.insert(
774 "ALIEN_SANDBOX_EXPECTED_EXEC_UID".to_string(),
775 supervisor.command_uid.to_string(),
776 );
777 env.insert(
778 "ALIEN_SANDBOX_EGRESS".to_string(),
779 if self.egress == SandboxEgress::None {
781 r#"{"mode":"deny"}"#.to_string()
782 } else {
783 serde_json::to_string(&self.egress).expect("egress serializes")
784 },
785 );
786 }
787 env
788 }
789
790 pub fn resolved_limits(&self) -> SandboxLimits {
796 self.limits.clone().unwrap_or_else(default_limits)
797 }
798
799 pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
804 if let Some(policy) = &self.default_policy {
805 if self.egress != SandboxEgress::Internet {
806 return Err(AlienError::new(ErrorData::SandboxEgressInvalid {
807 target: "defaultPolicy".into(),
808 reason: "defaultPolicy requires the new internet declaration".into(),
809 }));
810 }
811 policy.validate()?;
812 }
813 if self.image_user == Some(0) && platform == Platform::Local {
814 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
815 capability: "root image USER: this backend does not yet separate bounded root boot from non-root exec; use a non-root image USER".into(),
816 platform: platform.to_string(),
817 }));
818 }
819 if self.image_user == Some(0)
823 && platform == Platform::Kubernetes
824 && !matches!(self.egress, SandboxEgress::Internet | SandboxEgress::None)
825 {
826 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
827 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(),
828 platform: platform.to_string(),
829 }));
830 }
831 let mut capabilities = SandboxCapabilities::for_platform(platform)?;
832 if let Some(supervisor) = &self.privileged_supervisor {
833 if platform != Platform::Aws {
834 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
835 capability: "privilegedSupervisor".to_string(),
836 platform: platform.to_string(),
837 }));
838 }
839 if supervisor.command_uid == 0 || supervisor.command_uid == u32::MAX {
840 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
841 resource_id: self.id.clone(),
842 field: "privilegedSupervisor.commandUid".to_string(),
843 value: supervisor.command_uid.to_string(),
844 reason: "must be a non-root Linux uid other than the invalid uid sentinel"
845 .to_string(),
846 }));
847 }
848 if let SandboxEgress::AllowDomains { domains } = &self.egress {
849 for domain in domains {
850 let hostname = domain.strip_suffix('.').unwrap_or(domain);
851 if hostname.len() > 253
852 || !hostname.split('.').all(|label| {
853 !label.is_empty()
854 && label.len() <= 63
855 && label
856 .bytes()
857 .all(|c| c.is_ascii_alphanumeric() || c == b'-')
858 && !label.starts_with('-')
859 && !label.ends_with('-')
860 })
861 {
862 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
863 resource_id: self.id.clone(), field: "egress.domains".to_string(), value: domain.clone(),
864 reason: "privileged supervisor allowlists require exact DNS hostnames; wildcards are unsupported".to_string(),
865 }));
866 }
867 }
868 }
869 capabilities.domain_egress_rules = true;
870 }
871
872 if matches!(&self.code, SandboxCode::Source { .. })
877 && !matches!(
878 platform,
879 Platform::Aws | Platform::Azure | Platform::Gcp | Platform::Kubernetes
880 )
881 {
882 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
883 resource_id: self.id.clone(),
884 field: "code".to_string(),
885 value: "source".to_string(),
886 reason: format!(
887 "no sandbox backend builds an image from source on {platform}; give \
888 code.image a prebuilt reference"
889 ),
890 }));
891 }
892
893 if self.private_base_image.is_some() && platform != Platform::Aws {
896 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
897 capability: "privateBaseImage".to_string(),
898 platform: platform.to_string(),
899 }));
900 }
901
902 if platform == Platform::Azure && matches!(&self.code, SandboxCode::Image { .. }) {
905 self.azure_image()?;
906 }
907
908 if let Some(seconds) = self.lifecycle.max_lifetime_seconds {
911 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
913
914 if seconds == 0 {
915 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
916 resource_id: self.id.clone(),
917 field: "maxLifetimeSeconds".to_string(),
918 value: "0".to_string(),
919 reason: "a sandbox must be allowed to run for at least 1 second".to_string(),
920 }));
921 }
922
923 let ceiling = match platform {
928 Platform::Aws => Some((AWS_MAX_LIFETIME_SECONDS, "AWS runs a MicroVM for")),
929 Platform::Kubernetes => {
930 Some((KUBERNETES_MAX_LIFETIME_SECONDS, "Kubernetes runs a pod for"))
931 }
932 Platform::Gcp => None,
935 Platform::Azure | Platform::Local | Platform::Machines | Platform::Test => None,
938 };
939 if let Some((max, runs_for)) = ceiling {
940 if seconds > max {
941 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
942 resource_id: self.id.clone(),
943 field: "maxLifetimeSeconds".to_string(),
944 value: seconds.to_string(),
945 reason: format!("{runs_for} between 1 and {max} seconds"),
946 }));
947 }
948 }
949 }
950
951 let Some(limits) = self.limits.as_ref() else {
952 return self.validate_capabilities(&capabilities, platform);
954 };
955
956 validate_quantity(&self.id, "cpu", &limits.cpu)?;
957 validate_quantity(&self.id, "memory", &limits.memory)?;
958 validate_quantity(&self.id, "disk", &limits.disk)?;
959
960 if let Some(max_processes) = limits.max_processes {
961 if max_processes == 0 {
962 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
963 resource_id: self.id.clone(),
964 field: "maxProcesses".to_string(),
965 value: "0".to_string(),
966 reason: "a sandbox that may run no processes cannot run code".to_string(),
967 }));
968 }
969 capabilities.require(SandboxCapability::ProcessLimit, platform)?;
970 }
971
972 capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
975
976 if platform == Platform::Azure {
977 self.azure_sandbox_limits()?;
978 }
979
980 if platform == Platform::Gcp {
981 self.gcp_sandbox_limits()?;
982 }
983
984 if platform == Platform::Aws {
985 self.microvm_tier()?;
988 }
989
990 self.validate_capabilities(&capabilities, platform)
991 }
992
993 pub fn azure_image(&self) -> Result<AzureSandboxImage<'_>> {
997 let SandboxCode::Image { image, .. } = &self.code else {
998 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
999 resource_id: self.id.clone(),
1000 field: "code".to_string(),
1001 value: "source".to_string(),
1002 reason: "the sandbox still has unbuilt source code. Run 'alien build' first"
1003 .to_string(),
1004 }));
1005 };
1006
1007 classify_azure_sandbox_image(image).ok_or_else(|| {
1008 let image = image.trim();
1009 AlienError::new(ErrorData::SandboxLimitInvalid {
1010 resource_id: self.id.clone(),
1011 field: "code.image".to_string(),
1012 value: image.to_string(),
1013 reason: if image.is_empty() {
1014 "a sandbox has to name an image".to_string()
1015 } else {
1016 "Azure creates a sandbox from a catalog name such as 'ubuntu' or from a \
1017 registry image such as 'docker.io/library/python:3.14-slim'"
1018 .to_string()
1019 },
1020 })
1021 })
1022 }
1023
1024 pub fn gcp_sandbox_limits(&self) -> Result<()> {
1027 let Some(limits) = self.limits.as_ref() else {
1028 return Ok(());
1029 };
1030 let over_cap =
1031 quantity_exceeds_bytes(&limits.disk, GCP_MAX_DISK_BYTES).ok_or_else(|| {
1032 AlienError::new(ErrorData::SandboxLimitInvalid {
1033 resource_id: self.id.clone(),
1034 field: "disk".to_string(),
1035 value: limits.disk.clone(),
1036 reason: "expected a size such as 8Gi".to_string(),
1037 })
1038 })?;
1039 if over_cap {
1040 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1041 resource_id: self.id.clone(),
1042 field: "disk".to_string(),
1043 value: limits.disk.clone(),
1044 reason: "GCP Agent Platform caps a sandbox's ephemeral storage at 10Gi; declare \
1045 10Gi or less"
1046 .to_string(),
1047 }));
1048 }
1049 Ok(())
1050 }
1051
1052 pub fn azure_sandbox_limits(&self) -> Result<()> {
1056 let Some(limits) = self.limits.as_ref() else {
1057 return Ok(());
1060 };
1061
1062 let refused = |field: &str, value: &str, reason: &str| {
1063 AlienError::new(ErrorData::SandboxLimitInvalid {
1064 resource_id: self.id.clone(),
1065 field: field.to_string(),
1066 value: value.to_string(),
1067 reason: reason.to_string(),
1068 })
1069 };
1070
1071 let cpu_millicores = millicores(&limits.cpu)
1072 .ok_or_else(|| refused("cpu", &limits.cpu, "expected cores or millicores"))?;
1073
1074 if cpu_millicores % AZURE_CPU_STEP_MILLICORES != 0
1078 || !(AZURE_CPU_STEP_MILLICORES..=AZURE_MAX_CPU_MILLICORES).contains(&cpu_millicores)
1079 {
1080 return Err(refused(
1081 "cpu",
1082 &limits.cpu,
1083 "Azure allocates cpu in steps of 250m from 250m to 16000m",
1084 ));
1085 }
1086
1087 let memory_ceiling_mib = cpu_millicores * AZURE_MEMORY_MIB_PER_CORE / 1000;
1089 let disk_ceiling_mib = cpu_millicores * AZURE_DISK_MIB_PER_CORE / 1000;
1090
1091 let memory_mib = quantity_mib(&limits.memory)
1092 .ok_or_else(|| refused("memory", &limits.memory, "Azure sizes memory in whole MiB"))?;
1093 if memory_mib > memory_ceiling_mib {
1094 return Err(refused(
1095 "memory",
1096 &limits.memory,
1097 &format!(
1098 "Azure allows at most 2Gi of memory per core, or {memory_ceiling_mib}Mi \
1099 at the declared cpu"
1100 ),
1101 ));
1102 }
1103
1104 let disk_mib = quantity_mib(&limits.disk)
1105 .ok_or_else(|| refused("disk", &limits.disk, "Azure sizes disk in whole MiB"))?;
1106 if disk_mib > disk_ceiling_mib {
1107 return Err(refused(
1108 "disk",
1109 &limits.disk,
1110 &format!(
1111 "Azure allows at most 20Gi of disk per core, or {disk_ceiling_mib}Mi at \
1112 the declared cpu"
1113 ),
1114 ));
1115 }
1116
1117 Ok(())
1118 }
1119
1120 pub fn microvm_tier(&self) -> Result<MicrovmTier> {
1127 let Some(limits) = self.limits.as_ref() else {
1128 return Ok(MICROVM_TIERS[2]);
1132 };
1133
1134 let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
1135 AlienError::new(ErrorData::SandboxLimitInvalid {
1136 resource_id: self.id.clone(),
1137 field: "memory".to_string(),
1138 value: limits.memory.clone(),
1139 reason: "AWS sizes a MicroVM in whole MiB".to_string(),
1140 })
1141 })?;
1142 let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
1143 AlienError::new(ErrorData::SandboxLimitInvalid {
1144 resource_id: self.id.clone(),
1145 field: "disk".to_string(),
1146 value: limits.disk.clone(),
1147 reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
1148 })
1149 })?;
1150 let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
1151 AlienError::new(ErrorData::SandboxLimitInvalid {
1152 resource_id: self.id.clone(),
1153 field: "cpu".to_string(),
1154 value: limits.cpu.clone(),
1155 reason: "expected cores or millicores".to_string(),
1156 })
1157 })?;
1158
1159 let sized = |tier: &&MicrovmTier| {
1164 tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
1165 };
1166
1167 let tier = MICROVM_TIERS
1168 .iter()
1169 .rev()
1170 .find(sized)
1171 .copied()
1172 .ok_or_else(|| {
1173 AlienError::new(ErrorData::SandboxLimitInvalid {
1174 resource_id: self.id.clone(),
1175 field: "memory".to_string(),
1176 value: limits.memory.clone(),
1177 reason: format!(
1178 "a Lambda MicroVM bursts to four times its baseline, so the smallest \
1179 ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
1180 disk fit no size",
1181 limits.memory, limits.disk
1182 ),
1183 })
1184 })?;
1185
1186 let required_millicores = i64::from(tier.peak_vcpu) * 1000;
1187 if cpu_millicores < required_millicores {
1188 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1189 resource_id: self.id.clone(),
1190 field: "cpu".to_string(),
1191 value: limits.cpu.clone(),
1192 reason: format!(
1193 "AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
1194 reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
1195 limits.memory, tier.peak_vcpu, tier.peak_vcpu
1196 ),
1197 }));
1198 }
1199
1200 Ok(tier)
1201 }
1202
1203 fn validate_capabilities(
1205 &self,
1206 capabilities: &SandboxCapabilities,
1207 platform: Platform,
1208 ) -> Result<()> {
1209 if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
1210 capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
1211 }
1212
1213 if let SandboxEgress::AllowDomains { domains } = &self.egress {
1219 if domains.is_empty() {
1220 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1221 resource_id: self.id.clone(),
1222 field: "egress.domains".to_string(),
1223 value: "[]".to_string(),
1224 reason: "an allowlist naming no domain denies everything; declare \
1225 egress: deny if that is what was meant"
1226 .to_string(),
1227 }));
1228 }
1229 }
1230
1231 if matches!(self.egress, SandboxEgress::None) {
1232 capabilities.require(SandboxCapability::EgressDeny, platform)?;
1233 }
1234
1235 if platform == Platform::Gcp && matches!(self.egress, SandboxEgress::Internet) {
1238 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1239 capability: "egress internet: not built or proven on GCP Agent Platform yet; declare egress none".to_string(),
1240 platform: platform.to_string(),
1241 }));
1242 }
1243
1244 if platform == Platform::Gcp && !self.preview_ports.is_empty() {
1245 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1246 capability:
1247 "preview: not built or proven on GCP Agent Platform yet; remove the preview ports"
1248 .to_string(),
1249 platform: platform.to_string(),
1250 }));
1251 }
1252
1253 if !self.preview_ports.is_empty() {
1254 capabilities.require(SandboxCapability::Preview, platform)?;
1255 if platform == Platform::Azure
1256 && matches!(self.azure_image(), Ok(AzureSandboxImage::Catalog(_)))
1257 {
1258 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1259 capability:
1260 "preview (a catalog image runs without the Alien agent that issues \
1261 the capability; build the sandbox from source)"
1262 .to_string(),
1263 platform: platform.to_string(),
1264 }));
1265 }
1266 }
1267
1268 if self.lifecycle.idle_pause_seconds.is_some() {
1269 if platform == Platform::Gcp {
1272 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1273 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(),
1274 platform: platform.to_string(),
1275 }));
1276 }
1277 capabilities.require(SandboxCapability::PauseResume, platform)?;
1278 }
1279
1280 if self.lifecycle.max_lifetime_seconds.is_some() {
1281 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
1282 }
1283
1284 Ok(())
1285 }
1286}
1287
1288fn default_limits() -> SandboxLimits {
1293 SandboxLimits {
1294 cpu: "1".to_string(),
1295 memory: "2Gi".to_string(),
1296 disk: "8Gi".to_string(),
1297 max_processes: None,
1298 }
1299}
1300
1301fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
1303 let invalid = |reason: &str| {
1304 AlienError::new(ErrorData::SandboxLimitInvalid {
1305 resource_id: resource_id.to_string(),
1306 field: field.to_string(),
1307 value: value.to_string(),
1308 reason: reason.to_string(),
1309 })
1310 };
1311
1312 let digits_end = value
1313 .find(|c: char| !c.is_ascii_digit() && c != '.')
1314 .unwrap_or(value.len());
1315 let (number, suffix) = value.split_at(digits_end);
1316
1317 let parsed: f64 = number
1318 .parse()
1319 .map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
1320
1321 if parsed <= 0.0 {
1322 return Err(invalid("must be greater than zero"));
1323 }
1324
1325 const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
1326 if !SUFFIXES.contains(&suffix) {
1327 return Err(invalid(
1328 "unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
1329 ));
1330 }
1331
1332 Ok(())
1333}
1334
1335fn split_quantity(value: &str) -> Option<(f64, &str)> {
1337 let trimmed = value.trim();
1338 let digits_end = trimmed
1339 .find(|c: char| !c.is_ascii_digit() && c != '.')
1340 .unwrap_or(trimmed.len());
1341 let (number, suffix) = trimmed.split_at(digits_end);
1342 number.parse().ok().map(|number| (number, suffix))
1343}
1344
1345pub fn quantity_mib(value: &str) -> Option<i64> {
1351 let (number, suffix) = split_quantity(value)?;
1352 let bytes = match suffix {
1353 "" => number,
1354 "k" => number * 1e3,
1355 "M" => number * 1e6,
1356 "G" => number * 1e9,
1357 "T" => number * 1e12,
1358 "Ki" => number * 1024.0,
1359 "Mi" => number * 1024.0 * 1024.0,
1360 "Gi" => number * 1024.0 * 1024.0 * 1024.0,
1361 "Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
1362 _ => return None,
1364 };
1365 Some((bytes / (1024.0 * 1024.0)) as i64)
1366}
1367
1368fn quantity_exceeds_bytes(value: &str, cap_bytes: u128) -> Option<bool> {
1371 let trimmed = value.trim();
1372 let digits_end = trimmed
1373 .find(|c: char| !c.is_ascii_digit() && c != '.')
1374 .unwrap_or(trimmed.len());
1375 let (number, suffix) = trimmed.split_at(digits_end);
1376 let unit: u128 = match suffix {
1377 "" => 1,
1378 "k" => 1_000,
1379 "M" => 1_000_000,
1380 "G" => 1_000_000_000,
1381 "T" => 1_000_000_000_000,
1382 "Ki" => 1 << 10,
1383 "Mi" => 1 << 20,
1384 "Gi" => 1 << 30,
1385 "Ti" => 1 << 40,
1386 _ => return None,
1387 };
1388 let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
1389 if (whole.is_empty() && fraction.is_empty()) || fraction.contains('.') {
1390 return None;
1391 }
1392 let digits = format!("{whole}{fraction}");
1393 let scale = 10u128.checked_pow(u32::try_from(fraction.len()).ok()?)?;
1394 let mantissa: u128 = digits.parse().ok()?;
1395 Some(mantissa.checked_mul(unit)? > cap_bytes.checked_mul(scale)?)
1397}
1398
1399pub fn millicores(value: &str) -> Option<i64> {
1401 let (number, suffix) = split_quantity(value)?;
1402 match suffix {
1403 "" => Some((number * 1000.0) as i64),
1404 "m" => Some(number as i64),
1405 _ => None,
1406 }
1407}
1408
1409#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1411#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1412#[serde(rename_all = "camelCase")]
1413pub struct SandboxOutputs {
1414 pub parent_name: String,
1416 #[serde(skip_serializing_if = "Option::is_none")]
1418 pub identifier: Option<String>,
1419 #[serde(skip_serializing_if = "Option::is_none")]
1421 pub endpoint: Option<String>,
1422}
1423
1424impl ResourceOutputsDefinition for SandboxOutputs {
1425 fn get_resource_type(&self) -> ResourceType {
1426 Sandbox::RESOURCE_TYPE
1427 }
1428
1429 fn as_any(&self) -> &dyn Any {
1430 self
1431 }
1432
1433 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
1434 Box::new(self.clone())
1435 }
1436
1437 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
1438 other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
1439 }
1440
1441 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1442 serde_json::to_value(self)
1443 }
1444}
1445
1446impl ResourceDefinition for Sandbox {
1447 fn get_resource_type(&self) -> ResourceType {
1448 Self::RESOURCE_TYPE
1449 }
1450
1451 fn id(&self) -> &str {
1452 &self.id
1453 }
1454
1455 fn replace_after_failed_create_is_safe(&self) -> bool {
1456 false
1459 }
1460
1461 fn get_dependencies(&self) -> Vec<ResourceRef> {
1462 Vec::new()
1463 }
1464
1465 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1466 let new_sandbox = new_config
1467 .as_any()
1468 .downcast_ref::<Sandbox>()
1469 .ok_or_else(|| {
1470 AlienError::new(ErrorData::UnexpectedResourceType {
1471 resource_id: self.id.clone(),
1472 expected: Self::RESOURCE_TYPE,
1473 actual: new_config.get_resource_type(),
1474 })
1475 })?;
1476
1477 if self.id != new_sandbox.id {
1478 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1479 resource_id: self.id.clone(),
1480 reason: "the 'id' field is immutable".to_string(),
1481 }));
1482 }
1483
1484 Ok(())
1485 }
1486
1487 fn as_any(&self) -> &dyn Any {
1488 self
1489 }
1490
1491 fn as_any_mut(&mut self) -> &mut dyn Any {
1492 self
1493 }
1494
1495 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1496 Box::new(self.clone())
1497 }
1498
1499 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1500 other.as_any().downcast_ref::<Sandbox>() == Some(self)
1501 }
1502
1503 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1504 serde_json::to_value(self)
1505 }
1506}
1507
1508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1510pub enum AzureSandboxImage<'a> {
1511 Catalog(&'a str),
1513 Registry(&'a str),
1516}
1517
1518impl<'a> AzureSandboxImage<'a> {
1519 pub fn as_str(&self) -> &'a str {
1521 match self {
1522 Self::Catalog(value) | Self::Registry(value) => value,
1523 }
1524 }
1525}
1526
1527pub const AZURE_DISK_IMAGE_LABEL: &str = "alienImage";
1529
1530pub fn classify_azure_sandbox_image(image: &str) -> Option<AzureSandboxImage<'_>> {
1534 let image = image.trim();
1535 if image.is_empty() {
1536 return None;
1537 }
1538 if image
1539 .chars()
1540 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1541 {
1542 return Some(AzureSandboxImage::Catalog(image));
1543 }
1544 (image.contains(|c| matches!(c, '/' | ':' | '@')) && OCI_REFERENCE.is_match(image))
1545 .then_some(AzureSandboxImage::Registry(image))
1546}
1547
1548pub fn azure_disk_image_label(reference: &str) -> String {
1551 let digest = format!("{:x}", Sha256::digest(reference.trim().as_bytes()));
1552 digest[..32].to_string()
1553}
1554
1555static OCI_REFERENCE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1557 let domain_component = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
1558 let domain = format!(r"{domain_component}(?:\.{domain_component})*(?::[0-9]+)?");
1559 let path_component = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
1560 let name = format!(r"(?:{domain}/)?{path_component}(?:/{path_component})*");
1561 let tag = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}";
1562 let digest = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
1563 regex::Regex::new(&format!(r"^{name}(?::{tag})?(?:@{digest})?$"))
1564 .expect("the OCI reference grammar compiles")
1565});
1566
1567pub const BUNDLE_REGION_TOKEN: &str = "{region}";
1572
1573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1575pub enum BundleUri<'a> {
1576 Literal(&'a str),
1578 Regional { before: &'a str, after: &'a str },
1581}
1582
1583pub fn stable_bundle_key_prefix(key: &str) -> Option<&str> {
1587 let (above_file, _) = key.rsplit_once('/')?;
1588 let (above_version, _) = above_file.rsplit_once('/')?;
1589 Some(above_version)
1590}
1591
1592pub fn parse_bundle_uri(uri: &str) -> std::result::Result<BundleUri<'_>, String> {
1598 let path = uri
1599 .strip_prefix("s3://")
1600 .ok_or_else(|| format!("'{uri}' is not an s3:// URI"))?;
1601 let (bucket, key) = path
1602 .split_once('/')
1603 .ok_or_else(|| format!("'{uri}' names a bucket with no object key"))?;
1604
1605 if path.contains('*') || path.contains('?') {
1609 return Err(format!(
1610 "'{uri}' carries an IAM wildcard; the bundle's path is interpolated into the build \
1611 role's grant, so '*' and '?' would widen it past the bundle"
1612 ));
1613 }
1614
1615 if key.contains('{') || key.contains('}') {
1616 return Err(format!(
1617 "'{uri}' places a token in the object key; {BUNDLE_REGION_TOKEN} is accepted in the \
1618 bucket name alone"
1619 ));
1620 }
1621
1622 let Some((before, after)) = bucket.split_once(BUNDLE_REGION_TOKEN) else {
1623 if bucket.contains('{') || bucket.contains('}') {
1624 return Err(format!(
1625 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the \
1626 only one"
1627 ));
1628 }
1629 return Ok(BundleUri::Literal(uri));
1630 };
1631
1632 if after.contains(BUNDLE_REGION_TOKEN) {
1633 return Err(format!("'{uri}' repeats {BUNDLE_REGION_TOKEN}"));
1634 }
1635 if before.contains('{') || before.contains('}') || after.contains('{') || after.contains('}') {
1636 return Err(format!(
1637 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the only one"
1638 ));
1639 }
1640
1641 Ok(BundleUri::Regional {
1642 before: &uri[.."s3://".len() + before.len()],
1643 after: &uri["s3://".len() + before.len() + BUNDLE_REGION_TOKEN.len()..],
1644 })
1645}
1646
1647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1649pub enum EcrImageRegion<'a> {
1650 Literal(&'a str),
1652 Deployment,
1654}
1655
1656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1658pub struct EcrImageRepository<'a> {
1659 pub account_id: &'a str,
1660 pub region: EcrImageRegion<'a>,
1661 pub repository: &'a str,
1663}
1664
1665impl EcrImageRepository<'_> {
1666 pub fn arn(&self, partition: &str, region: &str) -> String {
1669 let region = match self.region {
1670 EcrImageRegion::Literal(region) => region,
1671 EcrImageRegion::Deployment => region,
1672 };
1673 format!(
1674 "arn:{partition}:ecr:{region}:{}:repository/{}",
1675 self.account_id, self.repository
1676 )
1677 }
1678}
1679
1680pub fn parse_ecr_image_repository(
1686 image: &str,
1687) -> std::result::Result<EcrImageRepository<'_>, String> {
1688 let refuse = |reason: &str| format!("privateBaseImage '{image}' {reason}");
1689 let (host, path) = image
1690 .split_once('/')
1691 .ok_or_else(|| refuse("names no repository"))?;
1692 let (account_id, rest) = host.split_once(".dkr.ecr.").ok_or_else(|| {
1693 refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)")
1694 })?;
1695 let region = rest
1697 .strip_suffix(".amazonaws.com.cn")
1698 .or_else(|| rest.strip_suffix(".amazonaws.com"))
1699 .ok_or_else(|| refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)"))?;
1700 if account_id.len() != 12 || !account_id.bytes().all(|b| b.is_ascii_digit()) {
1701 return Err(refuse("names no 12-digit account in its registry host"));
1702 }
1703 let region = if region == BUNDLE_REGION_TOKEN {
1704 EcrImageRegion::Deployment
1705 } else if !region.is_empty()
1706 && region
1707 .bytes()
1708 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1709 {
1710 EcrImageRegion::Literal(region)
1711 } else {
1712 return Err(refuse(&format!(
1713 "names no region in its registry host; give one or {BUNDLE_REGION_TOKEN}"
1714 )));
1715 };
1716
1717 let repository = match path.split_once('@') {
1718 Some((repository, _digest)) => repository,
1719 None => match path.rsplit_once('/') {
1720 Some((parent, last)) => match last.split_once(':') {
1721 Some((name, _tag)) => &path[..parent.len() + 1 + name.len()],
1722 None => path,
1723 },
1724 None => path.split_once(':').map_or(path, |(name, _tag)| name),
1725 },
1726 };
1727 let valid_segment = |segment: &str| {
1728 !segment.is_empty()
1729 && segment.bytes().all(|b| {
1730 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
1731 })
1732 };
1733 if !repository.split('/').all(valid_segment) {
1734 return Err(refuse(
1735 "names a repository outside ECR's grammar (lowercase letters, digits, '.', '_', '-', and '/' between them)",
1736 ));
1737 }
1738 Ok(EcrImageRepository {
1739 account_id,
1740 region,
1741 repository,
1742 })
1743}
1744
1745#[cfg(test)]
1746mod tests {
1747 use super::*;
1748
1749 #[test]
1750 fn private_database_setup_accepts_the_default_network() {
1751 for lifecycle in [
1752 crate::ResourceLifecycle::Frozen,
1753 crate::ResourceLifecycle::Live,
1754 ] {
1755 let stack = crate::Stack::new("database".to_string())
1756 .add(
1757 crate::Postgres::new("metadata".to_string()).build(),
1758 lifecycle,
1759 )
1760 .build();
1761 assert!(!restricts_network_mode(&stack, false));
1762 assert!(!restricts_network_mode(&stack, true));
1763 }
1764 assert!(!restricts_network_mode(
1765 &crate::Stack::new("empty".to_string()).build(),
1766 false,
1767 ));
1768 }
1769
1770 fn repository_key(image: &str) -> String {
1773 match parse_ecr_image_repository(image) {
1774 Ok(parsed) => {
1775 let host = image.split_once('/').map_or(image, |(host, _)| host);
1776 format!("{host}/{}", parsed.repository)
1777 }
1778 Err(_) => image.to_string(),
1779 }
1780 }
1781
1782 #[test]
1783 fn a_private_base_image_names_one_repository() {
1784 let vectors: serde_json::Value = serde_json::from_str(include_str!(
1785 "../../tests/fixtures/ecr-image-repository-parity.json"
1786 ))
1787 .expect("the ECR repository vectors must be JSON");
1788 let field = |case: &serde_json::Value, name: &str| {
1789 case[name]
1790 .as_str()
1791 .unwrap_or_else(|| panic!("vector must carry {name}: {case}"))
1792 .to_string()
1793 };
1794
1795 for case in vectors["accepted"].as_array().expect("accepted vectors") {
1796 let image = field(case, "image");
1797 let region = field(case, "region");
1798 let region = if region == BUNDLE_REGION_TOKEN {
1799 EcrImageRegion::Deployment
1800 } else {
1801 EcrImageRegion::Literal(®ion)
1802 };
1803 assert_eq!(
1804 parse_ecr_image_repository(&image),
1805 Ok(EcrImageRepository {
1806 account_id: &field(case, "accountId"),
1807 region,
1808 repository: &field(case, "repository"),
1809 }),
1810 "{image}"
1811 );
1812 assert_eq!(
1813 repository_key(&image),
1814 field(case, "repositoryKey"),
1815 "{image}"
1816 );
1817 }
1818
1819 for case in vectors["refused"].as_array().expect("refused vectors") {
1820 let image = field(case, "image");
1821 assert!(
1822 parse_ecr_image_repository(&image).is_err(),
1823 "{image} must be refused"
1824 );
1825 assert_eq!(
1826 repository_key(&image),
1827 field(case, "repositoryKey"),
1828 "{image}"
1829 );
1830 }
1831 }
1832
1833 #[test]
1834 fn a_repository_arn_takes_the_deployment_region_only_where_the_host_leaves_it() {
1835 let regional =
1836 parse_ecr_image_repository("123456789012.dkr.ecr.{region}.amazonaws.com/team/base:1")
1837 .expect("parses");
1838 let pinned =
1839 parse_ecr_image_repository("123456789012.dkr.ecr.eu-west-1.amazonaws.com/team/base:1")
1840 .expect("parses");
1841 assert_eq!(
1842 regional.arn("aws-us-gov", "us-gov-west-1"),
1843 "arn:aws-us-gov:ecr:us-gov-west-1:123456789012:repository/team/base"
1844 );
1845 assert_eq!(
1846 pinned.arn("aws", "us-east-1"),
1847 "arn:aws:ecr:eu-west-1:123456789012:repository/team/base"
1848 );
1849 }
1850
1851 #[test]
1854 fn a_uri_carrying_an_iam_wildcard_is_refused() {
1855 for uri in [
1856 "s3://acme/team-*/v1/bundle.zip",
1857 "s3://acme/sandbox-bundle/f00d/bundle?.zip",
1858 "s3://acme-*/sandbox-bundle/f00d/bundle.zip",
1859 ] {
1860 let error = parse_bundle_uri(uri).expect_err("a wildcard must be refused");
1861 assert!(error.contains("IAM wildcard"), "for {uri}: {error}");
1862 }
1863
1864 parse_bundle_uri("s3://acme/sandbox-bundle/f00d/bundle.zip")
1865 .expect("an ordinary key still parses");
1866 }
1867
1868 #[test]
1872 fn a_grantable_prefix_ends_above_the_segment_that_moves() {
1873 assert_eq!(
1874 stable_bundle_key_prefix("sandbox-bundle/f00dcafe/bundle.zip"),
1875 Some("sandbox-bundle")
1876 );
1877 assert_eq!(
1878 stable_bundle_key_prefix("artifacts/team-a/sandbox/f00dcafe/bundle.zip"),
1879 Some("artifacts/team-a/sandbox"),
1880 "a deeper key narrows the prefix, it never widens to the first segment"
1881 );
1882
1883 assert_eq!(stable_bundle_key_prefix("agents/bundle.zip"), None);
1886 assert_eq!(stable_bundle_key_prefix("bundle.zip"), None);
1887 }
1888
1889 fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
1890 Sandbox::new("agent-sbx".to_string())
1891 .code(SandboxCode::Image {
1892 image: "ubuntu".to_string(),
1893 bundled_from: None,
1894 })
1895 .limits(SandboxLimits {
1896 cpu: "1".to_string(),
1897 memory: "2Gi".to_string(),
1898 disk: "10Gi".to_string(),
1899 max_processes: None,
1900 })
1901 .egress(egress)
1902 .lifecycle(SandboxLifecyclePolicy {
1903 max_lifetime_seconds: None,
1904 idle_pause_seconds: None,
1905 })
1906 .preview_ports(preview_ports)
1907 .build()
1908 }
1909
1910 #[test]
1913 fn gcp_refuses_internet_egress_at_plan_time_and_still_takes_none() {
1914 let refused = sandbox_with(SandboxEgress::Internet, vec![])
1915 .validate_for_platform(Platform::Gcp)
1916 .unwrap_err();
1917 assert!(refused.to_string().contains("egress internet"), "{refused}");
1918 sandbox_with(SandboxEgress::None, vec![])
1919 .validate_for_platform(Platform::Gcp)
1920 .unwrap();
1921 }
1922
1923 #[test]
1926 fn gcp_refuses_an_idle_pause_policy_at_plan_time_and_still_takes_a_lifetime() {
1927 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
1928 Sandbox::new("sbx".to_string())
1929 .code(SandboxCode::Image {
1930 image: "ubuntu".to_string(),
1931 bundled_from: None,
1932 })
1933 .egress(SandboxEgress::None)
1934 .lifecycle(lifecycle)
1935 .build()
1936 .validate_for_platform(Platform::Gcp)
1937 };
1938 let refused = with_policy(SandboxLifecyclePolicy {
1939 max_lifetime_seconds: None,
1940 idle_pause_seconds: Some(900),
1941 })
1942 .expect_err("no idle policy exists on GCP");
1943 assert_eq!(refused.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
1944 assert!(refused.message.contains("idle"), "{}", refused.message);
1945 with_policy(SandboxLifecyclePolicy {
1946 max_lifetime_seconds: Some(3600),
1947 idle_pause_seconds: None,
1948 })
1949 .expect("a lifetime is a TTL on GCP");
1950 }
1951
1952 #[test]
1953 fn gcp_refuses_preview_ports_at_plan_time() {
1954 let error = sandbox_with(SandboxEgress::Deny, vec![8080])
1955 .validate_for_platform(Platform::Gcp)
1956 .expect_err("preview is refused on GCP");
1957 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
1958 assert!(
1959 error
1960 .to_string()
1961 .contains("not built or proven on GCP Agent Platform yet"),
1962 "{error}"
1963 );
1964 sandbox_with(SandboxEgress::Deny, vec![])
1965 .validate_for_platform(Platform::Gcp)
1966 .expect("a sandbox without preview ports is unaffected");
1967 }
1968
1969 #[test]
1970 fn a_uri_without_a_token_is_carried_whole() {
1971 assert_eq!(
1972 parse_bundle_uri("s3://acme-artifacts-us-east-2/agents/bundle.zip"),
1973 Ok(BundleUri::Literal(
1974 "s3://acme-artifacts-us-east-2/agents/bundle.zip"
1975 ))
1976 );
1977 }
1978
1979 #[test]
1982 fn a_regional_uri_splits_either_side_of_the_token() {
1983 let BundleUri::Regional { before, after } =
1984 parse_bundle_uri("s3://acme-artifacts-{region}/agents/bundle.zip")
1985 .expect("the token is accepted in the bucket")
1986 else {
1987 panic!("a bucket-position token must split");
1988 };
1989
1990 assert_eq!(before, "s3://acme-artifacts-");
1991 assert_eq!(after, "/agents/bundle.zip");
1992 assert_eq!(
1993 format!("{before}us-east-2{after}"),
1994 "s3://acme-artifacts-us-east-2/agents/bundle.zip",
1995 "the halves must rejoin to the URI the vendor meant"
1996 );
1997 }
1998
1999 #[test]
2002 fn a_token_this_build_cannot_resolve_is_refused() {
2003 for uri in [
2004 "s3://acme-artifacts-{regio}/bundle.zip",
2005 "s3://acme-artifacts/{region}/bundle.zip",
2006 "s3://acme-artifacts-{region}-{region}/bundle.zip",
2007 "s3://acme-artifacts/bundle-{version}.zip",
2008 "s3://acme}-artifacts-{region}/bundle.zip",
2009 "s3://acme{-artifacts-{region}/bundle.zip",
2010 ] {
2011 assert!(
2012 parse_bundle_uri(uri).is_err(),
2013 "'{uri}' must be refused before it can reach an image build"
2014 );
2015 }
2016 }
2017
2018 #[test]
2019 fn resource_type_is_stable() {
2020 assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
2021 }
2022
2023 #[test]
2024 fn capability_sets_are_per_platform() {
2025 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2026 assert!(
2027 gcp.reconnect,
2028 "generation from the container boot id makes a sandbox reachable across processes"
2029 );
2030 assert!(!gcp.preview);
2031 assert!(gcp.enforced_limits);
2032
2033 let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
2034 assert!(azure.files, "every backend moves files");
2035 assert!(gcp.files);
2036 assert!(azure.domain_egress_rules);
2039 assert!(azure.egress_deny);
2040 assert!(azure.enforced_limits);
2043 assert!(azure.pause_resume);
2044 assert!(!azure.snapshot);
2046 assert!(
2047 azure.preview,
2048 "the in-sandbox agent issues a port-scoped capability"
2049 );
2050
2051 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2052 assert!(!aws.snapshot, "AWS has no user-callable sandbox snapshot");
2053 assert!(aws.pause_resume);
2054
2055 let k8s =
2056 SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
2057 assert!(
2058 k8s.preview,
2059 "an in-cluster caller previews through the agent route"
2060 );
2061 }
2062
2063 #[test]
2072 fn supervisor_isolation_is_per_platform() {
2073 let value = |platform| {
2074 SandboxCapabilities::for_platform(platform)
2075 .expect("supported")
2076 .supervisor_isolation
2077 };
2078
2079 assert!(
2080 value(Platform::Aws),
2081 "root agent setuids the command to 60000"
2082 );
2083 assert!(
2084 value(Platform::Local),
2085 "the supervisor is on the host, outside the container"
2086 );
2087 assert!(
2088 value(Platform::Kubernetes),
2089 "root boot splits the command off the supervisor"
2090 );
2091 assert!(!value(Platform::Azure), "no Alien process runs the command");
2092 assert!(
2093 !value(Platform::Gcp),
2094 "no separate supervisor identity runs the command"
2095 );
2096 }
2097
2098 #[test]
2102 fn supervisor_isolation_separates_aws_from_a_subprocess_backend() {
2103 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2104 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2105
2106 assert_eq!(
2107 aws.supervisor_pid_namespace, gcp.supervisor_pid_namespace,
2108 "the older axis cannot tell them apart"
2109 );
2110 assert!(
2111 aws.supervisor_isolation,
2112 "AWS setuids the command off the supervisor"
2113 );
2114 assert!(
2115 !gcp.supervisor_isolation,
2116 "the command runs under no separate supervisor identity"
2117 );
2118 }
2119
2120 #[test]
2125 fn gcp_agent_platform_row_matches_measured_backend() {
2126 let row = SandboxCapabilities::gcp_agent_platform();
2127
2128 assert!(row.files, "agent file ops move over the sandbox envelope");
2129 assert!(
2130 row.reconnect,
2131 "generation is derived from the container boot id, so a sandbox is reachable across \
2132 processes"
2133 );
2134 assert!(
2135 !row.preview,
2136 "the only ingress is :execute; no port-scoped capability"
2137 );
2138 assert!(
2139 !row.pause_resume,
2140 ":resume can return a fresh container, so a pause keeps no state"
2141 );
2142 assert!(
2143 !row.snapshot,
2144 "the create path never sends a snapshot, so none is reachable through the trait"
2145 );
2146 assert!(
2147 !row.domain_egress_rules,
2148 "VPC and DNS peering is not a hostname allowlist"
2149 );
2150 assert!(
2151 row.egress_deny,
2152 "a declared deny blocks TCP, the metadata server and DNS on the default placement"
2153 );
2154 assert!(
2155 row.enforced_limits,
2156 "ceilings are enforced, by terminating the sandbox on breach"
2157 );
2158 assert!(!row.process_limit, "no process-count ceiling is observed");
2159 assert!(row.sandbox_lifetime, "ttl maps to a sandbox expireTime");
2160 assert!(!row.supervisor_pid_namespace, "no PID-namespace isolation");
2161 assert!(
2162 !row.supervisor_isolation,
2163 "the command is not run under a separate supervisor identity"
2164 );
2165
2166 let live = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2168 assert_eq!(
2169 live, row,
2170 "the Platform::Gcp arm is the Agent Platform capability row"
2171 );
2172 }
2173
2174 #[test]
2175 fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
2176 let error = SandboxCapabilities::for_platform(Platform::Machines)
2177 .expect_err("Machines has no sandbox backend");
2178 assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
2179 }
2180
2181 #[test]
2182 fn unsupported_capability_names_platform_and_capability() {
2183 let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
2184 let error = capabilities
2185 .require(SandboxCapability::Preview, Platform::Gcp)
2186 .expect_err("GCP has no preview");
2187
2188 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2189 let rendered = error.to_string();
2190 assert!(
2191 rendered.contains("preview"),
2192 "names the capability: {rendered}"
2193 );
2194 assert!(rendered.contains("gcp"), "names the platform: {rendered}");
2195 }
2196
2197 #[test]
2201 fn a_hostname_allowlist_is_refused_everywhere_it_would_be_approximated() {
2202 let sandbox = sandbox_with(
2203 SandboxEgress::AllowDomains {
2204 domains: vec!["example.com".to_string()],
2205 },
2206 vec![],
2207 );
2208
2209 for platform in [
2210 Platform::Aws,
2211 Platform::Gcp,
2212 Platform::Kubernetes,
2213 Platform::Local,
2214 ] {
2215 let error = sandbox
2216 .validate_for_platform(platform)
2217 .expect_err("only Azure expresses a hostname allowlist");
2218 assert_eq!(
2219 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2220 "on {platform:?}"
2221 );
2222 }
2223
2224 assert!(
2225 SandboxCapabilities::for_platform(Platform::Azure)
2226 .expect("supported")
2227 .domain_egress_rules,
2228 "Azure's egress policy matches on host pattern"
2229 );
2230 }
2231
2232 #[test]
2235 fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
2236 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2237
2238 assert!(
2241 SandboxCapabilities::for_platform(Platform::Gcp)
2242 .expect("supported")
2243 .egress_deny
2244 );
2245
2246 for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
2247 sandbox
2248 .validate_for_platform(platform)
2249 .expect("deny is enforced here");
2250 }
2251
2252 let egress_only = Sandbox::new("sbx".to_string())
2254 .code(SandboxCode::Image {
2255 image: "alpine".to_string(),
2256 bundled_from: None,
2257 })
2258 .egress(SandboxEgress::None)
2259 .lifecycle(SandboxLifecyclePolicy {
2260 max_lifetime_seconds: None,
2261 idle_pause_seconds: None,
2262 })
2263 .build();
2264
2265 egress_only
2266 .validate_for_platform(Platform::Azure)
2267 .expect("Azure creates the sandbox under a Deny policy with full inspection");
2268 }
2269
2270 #[test]
2274 fn a_sandbox_declaring_no_ceilings_takes_the_platforms_own() {
2275 let undeclared = Sandbox::new("sbx".to_string())
2276 .code(SandboxCode::Image {
2277 image: "alpine".to_string(),
2278 bundled_from: None,
2279 })
2280 .egress(SandboxEgress::None)
2281 .lifecycle(SandboxLifecyclePolicy {
2282 max_lifetime_seconds: None,
2283 idle_pause_seconds: None,
2284 })
2285 .build();
2286
2287 undeclared
2288 .validate_for_platform(Platform::Azure)
2289 .expect("a sandbox naming no ceilings takes the platform's own");
2290
2291 assert_eq!(undeclared.resolved_limits().cpu, "1");
2293 }
2294
2295 #[test]
2299 fn azure_sizes_follow_the_rule_the_data_plane_states() {
2300 let sized = |cpu: &str, memory: &str, disk: &str| {
2301 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2302 let limits = sandbox
2303 .limits
2304 .as_mut()
2305 .expect("the fixture declares limits");
2306 limits.cpu = cpu.to_string();
2307 limits.memory = memory.to_string();
2308 limits.disk = disk.to_string();
2309 sandbox.validate_for_platform(Platform::Azure)
2310 };
2311
2312 sized("250m", "512Mi", "5120Mi").expect("the smallest step the data plane accepts");
2313 sized("4000m", "8192Mi", "40960Mi").expect("cpu, memory and disk are all honoured");
2314 sized("16000m", "32Gi", "320Gi").expect("the top of the range");
2315
2316 let off_step = sized("333m", "512Mi", "5120Mi").expect_err("333m is not a step of 250m");
2318 assert_eq!(off_step.code, "SANDBOX_LIMIT_INVALID", "{off_step}");
2319 assert!(off_step.to_string().contains("cpu"), "{off_step}");
2320
2321 let too_big = sized("32000m", "64Gi", "640Gi").expect_err("32 cores is over the ceiling");
2322 assert_eq!(too_big.code, "SANDBOX_LIMIT_INVALID", "{too_big}");
2323
2324 sized("1000m", "2Gi", "20Gi").expect("2Gi is exactly one core's worth");
2327 let over_memory = sized("250m", "2Gi", "5120Mi").expect_err("2Gi needs a full core");
2328 assert_eq!(over_memory.code, "SANDBOX_LIMIT_INVALID", "{over_memory}");
2329 assert!(over_memory.to_string().contains("memory"), "{over_memory}");
2330
2331 let over_disk = sized("250m", "512Mi", "20Gi").expect_err("20Gi needs a full core");
2332 assert!(over_disk.to_string().contains("disk"), "{over_disk}");
2333 }
2334
2335 #[test]
2338 fn kubernetes_root_image_needs_gateway_or_no_egress() {
2339 let root = |egress| {
2340 let mut sandbox = sandbox_with(egress, vec![]);
2341 sandbox.image_user = Some(0);
2342 sandbox
2343 };
2344 for egress in [SandboxEgress::Internet, SandboxEgress::None] {
2345 root(egress)
2346 .validate_for_platform(Platform::Kubernetes)
2347 .expect("root boot is allowed with an external egress boundary");
2348 }
2349 for egress in [
2350 SandboxEgress::Allow,
2351 SandboxEgress::AllowDomains {
2352 domains: vec!["example.com".to_string()],
2353 },
2354 ] {
2355 let error = root(egress)
2356 .validate_for_platform(Platform::Kubernetes)
2357 .expect_err("a root image under unenforced egress is refused");
2358 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2359 assert!(error.to_string().contains("root image USER"), "{error}");
2360 }
2361 root(SandboxEgress::Internet)
2362 .validate_for_platform(Platform::Local)
2363 .expect_err("Local still refuses a root image");
2364 }
2365
2366 #[test]
2367 fn preview_ports_require_the_preview_capability() {
2368 let sandbox = sandbox_with(SandboxEgress::None, vec![8080]);
2369
2370 sandbox
2371 .validate_for_platform(Platform::Aws)
2372 .expect("AWS mints a port-scoped JWE");
2373
2374 sandbox
2375 .validate_for_platform(Platform::Kubernetes)
2376 .expect("Kubernetes serves preview to in-cluster callers through the agent");
2377
2378 let error = sandbox
2379 .validate_for_platform(Platform::Gcp)
2380 .expect_err("GCP has no port-scoped credential yet");
2381 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2382 }
2383
2384 #[test]
2386 fn azure_preview_needs_an_image_that_carries_the_agent() {
2387 let catalog = sandbox_with(SandboxEgress::None, vec![8080]);
2388 let error = catalog
2389 .validate_for_platform(Platform::Azure)
2390 .expect_err("a catalog image has no agent to issue a capability");
2391 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2392
2393 let mut registry = sandbox_with(SandboxEgress::None, vec![8080]);
2394 registry.code = SandboxCode::Image {
2395 image: "registry.example.com/workload/sandbox:1".to_string(),
2396 bundled_from: None,
2397 };
2398 registry
2399 .validate_for_platform(Platform::Azure)
2400 .expect("a registry image is built with the agent");
2401 }
2402
2403 #[test]
2407 fn a_private_base_image_is_refused_off_aws() {
2408 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2409 sandbox.code = SandboxCode::Image {
2410 image: "s3://acme-artifacts/agents/bundle.zip".to_string(),
2411 bundled_from: None,
2412 };
2413 sandbox.private_base_image =
2414 Some("123456789012.dkr.ecr.{region}.amazonaws.com/acme:tag".to_string());
2415
2416 sandbox
2417 .validate_for_platform(Platform::Aws)
2418 .expect("AWS builds its image from a bundle, so a base image sits behind code.image");
2419
2420 for platform in [
2421 Platform::Gcp,
2422 Platform::Azure,
2423 Platform::Kubernetes,
2424 Platform::Local,
2425 ] {
2426 let error = sandbox
2427 .validate_for_platform(platform)
2428 .expect_err("a backend that builds no image must refuse a base image for one");
2429 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2430 assert!(
2431 error.to_string().contains("privateBaseImage"),
2432 "the refusal must name the field the user declared: {error}"
2433 );
2434 }
2435 }
2436
2437 #[test]
2441 fn gcp_refuses_a_disk_above_its_cap_and_accepts_the_cap() {
2442 let with_disk = |disk: &str| {
2443 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2444 sandbox
2445 .limits
2446 .as_mut()
2447 .expect("the fixture declares limits")
2448 .disk = disk.to_string();
2449 sandbox
2450 };
2451
2452 let error = with_disk("20Gi")
2453 .validate_for_platform(Platform::Gcp)
2454 .expect_err("20Gi is above the Agent Platform cap");
2455 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2456 let rendered = error.to_string();
2457 assert!(rendered.contains("disk"), "names the field: {rendered}");
2458 assert!(rendered.contains("10Gi"), "names the cap: {rendered}");
2459
2460 with_disk("10Gi")
2461 .validate_for_platform(Platform::Gcp)
2462 .expect("the cap itself is allowed");
2463 with_disk("10240Mi")
2464 .validate_for_platform(Platform::Gcp)
2465 .expect("the cap in MiB is allowed");
2466 for over in ["10240.5Mi", "10241Mi", "10.0000001Gi"] {
2467 with_disk(over)
2468 .validate_for_platform(Platform::Gcp)
2469 .expect_err(&format!("{over} is above the cap and must not round down"));
2470 }
2471 with_disk("8Gi")
2472 .validate_for_platform(Platform::Gcp)
2473 .expect("the default disk is allowed");
2474 with_disk("20Gi")
2475 .validate_for_platform(Platform::Kubernetes)
2476 .expect("the cap is Agent Platform's, not every backend's");
2477 }
2478
2479 #[test]
2480 fn gcp_accepts_a_sandbox_declaring_enforced_limits() {
2481 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2482 sandbox
2483 .limits
2484 .as_mut()
2485 .expect("the fixture declares limits")
2486 .disk = "10Gi".to_string();
2487 sandbox
2488 .validate_for_platform(Platform::Gcp)
2489 .expect("Agent Platform enforces declared ceilings, by terminating on breach");
2490 }
2491
2492 #[test]
2493 fn invalid_quantities_are_rejected_with_the_offending_field() {
2494 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2495 sandbox
2496 .limits
2497 .as_mut()
2498 .expect("the fixture declares limits")
2499 .memory = "2Gb".to_string();
2500
2501 let error = sandbox
2502 .validate_for_platform(Platform::Aws)
2503 .expect_err("Gb is not a valid suffix");
2504 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2505 assert!(error.to_string().contains("memory"));
2506
2507 sandbox
2508 .limits
2509 .as_mut()
2510 .expect("the fixture declares limits")
2511 .memory = "2Gi".to_string();
2512 sandbox
2513 .limits
2514 .as_mut()
2515 .expect("the fixture declares limits")
2516 .cpu = "0".to_string();
2517 let error = sandbox
2518 .validate_for_platform(Platform::Aws)
2519 .expect_err("zero cpu is not a ceiling");
2520 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2521 }
2522
2523 #[test]
2524 fn zero_max_processes_is_rejected() {
2525 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2526 sandbox
2527 .limits
2528 .as_mut()
2529 .expect("the fixture declares limits")
2530 .max_processes = Some(0);
2531
2532 let error = sandbox
2533 .validate_for_platform(Platform::Local)
2534 .expect_err("a sandbox must be able to run at least one process");
2535 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2536 assert!(error.to_string().contains("maxProcesses"));
2537 }
2538
2539 #[test]
2543 fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
2544 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2545 sandbox
2546 .limits
2547 .as_mut()
2548 .expect("the fixture declares limits")
2549 .max_processes = Some(256);
2550
2551 sandbox
2552 .validate_for_platform(Platform::Local)
2553 .expect("Docker takes a pids limit");
2554
2555 for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
2556 let error = sandbox
2557 .validate_for_platform(platform)
2558 .expect_err("a process ceiling nothing applies must be refused");
2559 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2560 }
2561 }
2562
2563 #[test]
2568 fn a_lifetime_aws_would_reject_is_refused_while_planning() {
2569 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2570 let mut without_limits = with_limits.clone();
2571 without_limits.limits = None;
2572
2573 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2574 for seconds in [28_801, 30_000, 100_000] {
2575 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2576 let error = sandbox
2577 .validate_for_platform(Platform::Aws)
2578 .expect_err("a lifetime above what AWS runs is refused");
2579 assert_eq!(
2580 error.code, "SANDBOX_LIMIT_INVALID",
2581 "{seconds}s {declared} limits"
2582 );
2583
2584 sandbox
2586 .validate_for_platform(Platform::Kubernetes)
2587 .expect("Kubernetes takes an activeDeadlineSeconds above 28,800");
2588 }
2589
2590 sandbox.lifecycle.max_lifetime_seconds = Some(28_800);
2591 sandbox
2592 .validate_for_platform(Platform::Aws)
2593 .expect("the ceiling itself is allowed");
2594 }
2595 }
2596
2597 #[test]
2601 fn a_zero_lifetime_is_refused_while_planning() {
2602 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2603 let mut without_limits = with_limits.clone();
2604 without_limits.limits = None;
2605
2606 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2607 sandbox.lifecycle.max_lifetime_seconds = Some(0);
2608 for platform in [
2609 Platform::Aws,
2610 Platform::Kubernetes,
2611 Platform::Gcp,
2612 Platform::Azure,
2613 ] {
2614 let error = sandbox
2615 .validate_for_platform(platform)
2616 .expect_err("a zero lifetime is refused");
2617 assert_eq!(
2618 error.code, "SANDBOX_LIMIT_INVALID",
2619 "{platform} {declared} limits"
2620 );
2621 assert!(
2622 error.to_string().contains("maxLifetimeSeconds"),
2623 "{platform} {declared} limits"
2624 );
2625 }
2626
2627 for platform in [Platform::Local] {
2629 let error = sandbox
2630 .validate_for_platform(platform)
2631 .expect_err("a lifetime is refused where nothing applies it");
2632 assert_eq!(
2633 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2634 "{platform} {declared} limits"
2635 );
2636 }
2637
2638 sandbox.lifecycle.max_lifetime_seconds = Some(1);
2639 sandbox
2640 .validate_for_platform(Platform::Kubernetes)
2641 .expect("one second is the API server's floor");
2642 }
2643 }
2644
2645 #[test]
2649 fn a_lifetime_kubernetes_would_reject_is_refused_while_planning() {
2650 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2651 let mut without_limits = with_limits.clone();
2652 without_limits.limits = None;
2653
2654 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2655 for seconds in [2_147_483_648, u32::MAX] {
2656 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2657 let error = sandbox
2658 .validate_for_platform(Platform::Kubernetes)
2659 .expect_err("a lifetime above what the API server takes is refused");
2660 assert_eq!(
2661 error.code, "SANDBOX_LIMIT_INVALID",
2662 "{seconds}s {declared} limits"
2663 );
2664 assert!(
2665 error.to_string().contains("maxLifetimeSeconds"),
2666 "{seconds}s {declared} limits"
2667 );
2668 }
2669
2670 sandbox.lifecycle.max_lifetime_seconds = Some(2_147_483_647);
2671 sandbox
2672 .validate_for_platform(Platform::Kubernetes)
2673 .expect("the ceiling itself is allowed");
2674 }
2675 }
2676
2677 #[test]
2680 fn an_image_azure_cannot_pull_is_refused_while_planning() {
2681 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2682 sandbox.limits = None;
2685
2686 for image in ["ubuntu@sha256:abc", "", " ", "ubuntu latest", "ubuntu?x"] {
2688 sandbox.code = SandboxCode::Image {
2689 image: image.to_string(),
2690 bundled_from: None,
2691 };
2692 let error = sandbox
2693 .validate_for_platform(Platform::Azure)
2694 .expect_err("an image Azure has nowhere to put is refused");
2695 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "image '{image}'");
2696 }
2697
2698 for image in ["ubuntu", "ubuntu-22.04", "debian_slim"] {
2699 sandbox.code = SandboxCode::Image {
2700 image: image.to_string(),
2701 bundled_from: None,
2702 };
2703 sandbox
2704 .validate_for_platform(Platform::Azure)
2705 .unwrap_or_else(|error| panic!("'{image}' is a catalog name: {error}"));
2706 }
2707
2708 for image in [
2709 "ubuntu:24.04",
2710 "ghcr.io/myorg/sandbox:latest",
2711 "docker.io/library/python:3.14-slim",
2712 "localhost:5000/team/agent@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d",
2713 ] {
2714 sandbox.code = SandboxCode::Image {
2715 image: image.to_string(),
2716 bundled_from: None,
2717 };
2718 sandbox
2719 .validate_for_platform(Platform::Azure)
2720 .unwrap_or_else(|error| panic!("'{image}' is a registry image: {error}"));
2721 }
2722
2723 sandbox.code = SandboxCode::Image {
2725 image: " ubuntu ".to_string(),
2726 bundled_from: None,
2727 };
2728 assert_eq!(
2729 sandbox
2730 .azure_image()
2731 .expect("a padded name is still a name"),
2732 AzureSandboxImage::Catalog("ubuntu")
2733 );
2734 }
2735
2736 #[test]
2740 fn every_value_the_catalog_allowlist_accepted_is_still_a_catalog_name() {
2741 const ALPHABET: &[u8] =
2742 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
2743
2744 let assert_catalog = |value: &str| {
2745 assert_eq!(
2746 classify_azure_sandbox_image(value),
2747 Some(AzureSandboxImage::Catalog(value.trim())),
2748 "'{value}'"
2749 );
2750 };
2751
2752 for a in ALPHABET {
2753 assert_catalog(&String::from_utf8(vec![*a]).unwrap());
2754 for b in ALPHABET {
2755 assert_catalog(&String::from_utf8(vec![*a, *b]).unwrap());
2756 for c in ALPHABET {
2757 assert_catalog(&String::from_utf8(vec![*a, *b, *c]).unwrap());
2758 }
2759 }
2760 }
2761
2762 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
2763 let mut next = || {
2764 state ^= state << 13;
2765 state ^= state >> 7;
2766 state ^= state << 17;
2767 state
2768 };
2769 for _ in 0..20_000 {
2770 let len = 4 + (next() % 60) as usize;
2771 let mut value: String = (0..len)
2772 .map(|_| ALPHABET[(next() % ALPHABET.len() as u64) as usize] as char)
2773 .collect();
2774 if next() % 4 == 0 {
2775 value = format!(" {value}\t");
2776 }
2777 assert_catalog(&value);
2778 }
2779 }
2780
2781 #[test]
2784 fn the_disk_image_label_is_stable_and_label_safe() {
2785 let label = azure_disk_image_label("docker.io/library/python:3.14-slim");
2786 assert_eq!(
2787 label,
2788 azure_disk_image_label(" docker.io/library/python:3.14-slim ")
2789 );
2790 assert_ne!(
2791 label,
2792 azure_disk_image_label("docker.io/library/python:3.13-slim")
2793 );
2794 assert_eq!(label.len(), 32);
2795 assert!(label.chars().all(|c| c.is_ascii_hexdigit()), "{label}");
2796 }
2797
2798 #[test]
2802 fn a_sandbox_deadline_is_accepted_only_where_the_platform_applies_it() {
2803 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2804 sandbox.lifecycle.max_lifetime_seconds = Some(3600);
2805
2806 sandbox
2807 .validate_for_platform(Platform::Kubernetes)
2808 .expect("the kubelet enforces activeDeadlineSeconds");
2809 sandbox
2810 .validate_for_platform(Platform::Aws)
2811 .expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
2812
2813 sandbox.validate_for_platform(Platform::Azure).expect(
2814 "the binding stamps a deadline label and the controller's reaper deletes by it",
2815 );
2816
2817 for platform in [Platform::Local] {
2818 let error = sandbox
2819 .validate_for_platform(platform)
2820 .expect_err("a deadline nothing applies must be refused");
2821 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2822 }
2823 }
2824
2825 #[test]
2829 fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
2830 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2831 let tier = sandbox
2832 .microvm_tier()
2833 .expect("2Gi/1cpu/20Gi is satisfiable");
2834
2835 assert_eq!(
2836 tier.peak_memory_mib, 2048,
2837 "the peak is the declared ceiling"
2838 );
2839 assert_eq!(
2840 tier.baseline_memory_mib, 512,
2841 "which is a quarter of it as the baseline"
2842 );
2843 assert!(tier.max_disk_mib <= 20 * 1024);
2844 }
2845
2846 #[test]
2850 fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
2851 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2852 {
2853 let limits = sandbox
2854 .limits
2855 .as_mut()
2856 .expect("the fixture declares limits");
2857 limits.cpu = "1".to_string();
2858 limits.memory = "8Gi".to_string();
2859 }
2860
2861 let error = sandbox
2862 .microvm_tier()
2863 .expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
2864 assert!(
2865 error.to_string().contains("4 vCPU"),
2866 "the refusal must say what the memory ceiling implies: {error}"
2867 );
2868
2869 sandbox
2870 .limits
2871 .as_mut()
2872 .expect("the fixture declares limits")
2873 .cpu = "4".to_string();
2874 let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
2875 assert_eq!(tier.peak_memory_mib, 8192);
2876 }
2877
2878 #[test]
2881 fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
2882 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2883 sandbox
2884 .limits
2885 .as_mut()
2886 .expect("the fixture declares limits")
2887 .memory = "1Gi".to_string();
2888
2889 let error = sandbox
2890 .validate_for_platform(Platform::Aws)
2891 .expect_err("no MicroVM size peaks at or below 1Gi");
2892 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2893 assert!(
2894 error.to_string().contains("2Gi"),
2895 "the refusal must say what the smallest holdable ceiling is: {error}"
2896 );
2897 }
2898
2899 #[test]
2902 fn source_code_is_refused_where_no_backend_builds_it() {
2903 let sandbox = Sandbox::new("agent".to_string())
2904 .code(SandboxCode::Source {
2905 src: "./sandbox".to_string(),
2906 toolchain: ToolchainConfig::Docker {
2907 dockerfile: None,
2908 build_args: None,
2909 target: None,
2910 },
2911 })
2912 .egress(SandboxEgress::None)
2913 .lifecycle(SandboxLifecyclePolicy {
2914 max_lifetime_seconds: None,
2915 idle_pause_seconds: None,
2916 })
2917 .build();
2918
2919 sandbox
2920 .validate_for_platform(Platform::Aws)
2921 .expect("an AWS sandbox base image is built by `alien build`");
2922 sandbox
2923 .validate_for_platform(Platform::Azure)
2924 .expect("an Azure sandbox base image is built by `alien build`");
2925 sandbox
2926 .validate_for_platform(Platform::Gcp)
2927 .expect("a GCP sandbox base image is built by `alien build`");
2928 sandbox
2929 .validate_for_platform(Platform::Kubernetes)
2930 .expect("a Kubernetes sandbox base image is built by `alien build`");
2931
2932 for platform in [Platform::Local] {
2933 let error = sandbox
2934 .validate_for_platform(platform)
2935 .expect_err("no backend builds a sandbox image from source here");
2936 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2937 assert!(
2938 error.to_string().contains("code.image"),
2939 "the refusal must say what to write instead: {error}"
2940 );
2941 assert!(
2942 error.to_string().contains(&platform.to_string()),
2943 "the refusal must name the platform that cannot build it: {error}"
2944 );
2945 }
2946 }
2947
2948 #[test]
2951 fn every_accepted_unit_converts_rather_than_falling_back() {
2952 assert_eq!(quantity_mib("2Gi"), Some(2048));
2953 assert_eq!(quantity_mib("512Mi"), Some(512));
2954 assert_eq!(quantity_mib("4G"), Some(3814));
2955 assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
2956 assert_eq!(millicores("1"), Some(1000));
2957 assert_eq!(millicores("500m"), Some(500));
2958 }
2959
2960 #[test]
2961 fn privileged_supervisor_fixes_identity_and_requires_an_enforceable_backend() {
2962 let mut sandbox = sandbox_with(
2963 SandboxEgress::AllowDomains {
2964 domains: vec!["example.com".to_string()],
2965 },
2966 vec![],
2967 );
2968 sandbox.privileged_supervisor = Some(SandboxPrivilegedSupervisor { command_uid: 60001 });
2969 sandbox
2970 .validate_for_platform(Platform::Aws)
2971 .expect("AWS can enforce the policy in the agent");
2972 assert_eq!(sandbox.cloud_egress(), &SandboxEgress::Allow);
2973 assert_eq!(
2974 sandbox.supervisor_environment()["ALIEN_SANDBOX_EXPECTED_EXEC_UID"],
2975 "60001"
2976 );
2977 for platform in [
2978 Platform::Local,
2979 Platform::Kubernetes,
2980 Platform::Azure,
2981 Platform::Gcp,
2982 ] {
2983 let error = sandbox
2984 .validate_for_platform(platform)
2985 .expect_err("cannot grant a privilege boundary the backend lacks");
2986 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2987 assert!(error.message.contains("privilegedSupervisor"));
2988 }
2989 for uid in [0, u32::MAX] {
2990 sandbox.privileged_supervisor.as_mut().unwrap().command_uid = uid;
2991 let error = sandbox
2992 .validate_for_platform(Platform::Aws)
2993 .expect_err("invalid uid must fail at plan time");
2994 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2995 }
2996 }
2997
2998 #[test]
2999 fn unknown_fields_are_rejected() {
3000 let json = r#"{
3001 "id": "sbx",
3002 "code": {"type": "image", "image": "ubuntu:24.04"},
3003 "limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
3004 "egress": {"mode": "deny"},
3005 "lifecycle": {},
3006 "unexpected": true
3007 }"#;
3008
3009 serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
3010 }
3011
3012 #[test]
3013 fn serialization_roundtrips() {
3014 let sandbox = sandbox_with(
3015 SandboxEgress::AllowDomains {
3016 domains: vec!["example.com".to_string()],
3017 },
3018 vec![8080, 9090],
3019 );
3020
3021 let json = serde_json::to_string(&sandbox).expect("serializes");
3022 let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
3023 assert_eq!(sandbox, restored);
3024 }
3025
3026 #[test]
3027 fn id_is_immutable_across_updates() {
3028 let original = sandbox_with(SandboxEgress::None, vec![]);
3029 let renamed = Sandbox::new("other".to_string())
3030 .code(SandboxCode::Image {
3031 image: "ubuntu".to_string(),
3032 bundled_from: None,
3033 })
3034 .limits(
3035 original
3036 .limits
3037 .clone()
3038 .expect("the fixture declares limits"),
3039 )
3040 .egress(SandboxEgress::None)
3041 .lifecycle(SandboxLifecyclePolicy {
3042 max_lifetime_seconds: None,
3043 idle_pause_seconds: None,
3044 })
3045 .build();
3046
3047 original
3048 .validate_update(&original.clone())
3049 .expect("an unchanged config is a valid update");
3050 original
3051 .validate_update(&renamed)
3052 .expect_err("renaming a sandbox is not an update");
3053 }
3054
3055 #[test]
3059 fn azure_takes_an_idle_policy_and_a_lifetime_ceiling() {
3060 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
3061 Sandbox::new("sbx".to_string())
3062 .code(SandboxCode::Image {
3063 image: "ubuntu".to_string(),
3064 bundled_from: None,
3065 })
3066 .egress(SandboxEgress::Allow)
3067 .lifecycle(lifecycle)
3068 .build()
3069 .validate_for_platform(Platform::Azure)
3070 };
3071
3072 with_policy(SandboxLifecyclePolicy {
3073 max_lifetime_seconds: None,
3074 idle_pause_seconds: Some(900),
3075 })
3076 .expect("Azure pauses a sandbox on idle");
3077
3078 with_policy(SandboxLifecyclePolicy {
3079 max_lifetime_seconds: Some(3600),
3080 idle_pause_seconds: None,
3081 })
3082 .expect("the reaper enforces a wall-clock ceiling");
3083 }
3084
3085 #[test]
3091 fn an_allowlist_with_no_domains_is_refused() {
3092 let declared = |domains: Vec<String>| {
3093 Sandbox::new("sbx".to_string())
3094 .code(SandboxCode::Image {
3095 image: "ubuntu".to_string(),
3096 bundled_from: None,
3097 })
3098 .egress(SandboxEgress::AllowDomains { domains })
3099 .lifecycle(SandboxLifecyclePolicy {
3100 max_lifetime_seconds: None,
3101 idle_pause_seconds: None,
3102 })
3103 .build()
3104 .validate_for_platform(Platform::Azure)
3105 };
3106
3107 let error = declared(vec![]).expect_err("an empty allowlist must be refused");
3108 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3109
3110 declared(vec!["api.example.com".to_string()])
3111 .expect("a named domain is what an allowlist is for");
3112 }
3113
3114 #[test]
3117 fn internet_access_switch_maps_only_the_two_expressible_modes() {
3118 assert_eq!(SandboxEgress::Allow.internet_access_switch(), Some(true));
3119 assert_eq!(SandboxEgress::None.internet_access_switch(), Some(false));
3120 assert_eq!(
3121 SandboxEgress::AllowDomains {
3122 domains: vec!["api.example.com".to_string()]
3123 }
3124 .internet_access_switch(),
3125 None,
3126 "a host list has no boolean and must not be approximated"
3127 );
3128 }
3129
3130 #[test]
3134 fn stack_state_written_before_the_lifecycle_rename_still_reads() {
3135 let stored: crate::StackResourceState = serde_json::from_value(serde_json::json!({
3136 "type": "sandbox",
3137 "config": {
3138 "id": "sandbox",
3139 "code": {
3140 "type": "image",
3141 "image": "s3://example-bundles/analysis/v1/bundle.zip"
3142 },
3143 "type": "sandbox",
3144 "egress": { "mode": "allow" },
3145 "session": { "maxLifetimeSeconds": 28800, "idleSuspendSeconds": 600 }
3146 },
3147 "status": "running",
3148 "outputs": {
3149 "type": "sandbox",
3150 "identifier": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox",
3151 "parentName": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox"
3152 },
3153 "lifecycle": "frozen",
3154 "dependencies": [
3155 { "id": "management", "type": "remote-stack-management" },
3156 { "id": "access", "type": "resource-access" }
3157 ],
3158 "controllerPlatform": "aws"
3159 }))
3160 .expect("a stack state written before the rename must still deserialize");
3161
3162 let expected = Sandbox::new("sandbox".to_string())
3163 .code(SandboxCode::Image {
3164 image: "s3://example-bundles/analysis/v1/bundle.zip".to_string(),
3165 bundled_from: None,
3166 })
3167 .egress(SandboxEgress::Allow)
3168 .lifecycle(SandboxLifecyclePolicy {
3169 max_lifetime_seconds: Some(28_800),
3170 idle_pause_seconds: Some(600),
3171 })
3172 .build();
3173 assert_eq!(stored.config.downcast_ref::<Sandbox>(), Some(&expected));
3174
3175 let rewritten = serde_json::to_value(&stored.config).expect("the sandbox serializes");
3176 assert_eq!(
3177 rewritten["lifecycle"],
3178 serde_json::json!({ "maxLifetimeSeconds": 28800, "idlePauseSeconds": 600 }),
3179 "the next write stores the current names"
3180 );
3181 assert!(rewritten.get("session").is_none());
3182 }
3183}
3184
3185#[cfg(test)]
3186mod label_format_tests {
3187 use super::*;
3188
3189 #[test]
3190 fn request_keys_are_bounded_and_safe() {
3191 for good in ["a", "A-z_9", &"x".repeat(64)] {
3192 assert!(is_valid_request_key(good), "{good}");
3193 }
3194 for bad in ["", "a b", "a/b", "a.b", "é", &"x".repeat(65)] {
3195 assert!(!is_valid_request_key(bad), "{bad}");
3196 }
3197 }
3198
3199 #[test]
3200 fn expiry_is_a_positive_integer() {
3201 assert!(is_valid_sandbox_expiry("1700000000000"));
3202 for bad in ["", "0", "-1", "1.5", "never", "+5 "] {
3203 assert!(!is_valid_sandbox_expiry(bad), "{bad}");
3204 }
3205 }
3206}