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 GCP_NO_EGRESS_ALLOWLIST: &str = "Google Cloud sandboxes have no outbound allowlist: \
265`internet` is open outbound through Google's shared addresses (no fixed egress IP) and takes no \
266per-sandbox policy; declare `none` to block all outbound traffic";
267
268pub const SANDBOX_EXPIRY_LABEL: &str = "alienExpiresAtMs";
270
271pub const SANDBOX_REQUEST_KEY_LABEL: &str = "alienRequestKey";
273
274pub const SANDBOX_REQUEST_KEY_MAX_LEN: usize = 64;
276
277pub fn is_valid_request_key(value: &str) -> bool {
280 !value.is_empty()
281 && value.len() <= SANDBOX_REQUEST_KEY_MAX_LEN
282 && value
283 .bytes()
284 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
285}
286
287pub fn is_valid_sandbox_expiry(value: &str) -> bool {
289 value.parse::<u64>().is_ok_and(|ms| ms > 0)
290}
291
292pub const AZURE_GATEWAY_MAX_LIFETIME_SECONDS: u32 = 24 * 60 * 60;
294
295#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
301#[serde(rename_all = "camelCase", deny_unknown_fields)]
302pub struct SandboxLifecyclePolicy {
303 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub max_lifetime_seconds: Option<u32>,
311 #[serde(alias = "idleSuspendSeconds", skip_serializing_if = "Option::is_none")]
315 pub idle_pause_seconds: Option<u32>,
316}
317
318pub const GCP_PREVIEW_IS_COMMAND_ACCESS: &str = "On Google Cloud, preview access equals command access; port-scoped preview sharing is not available.";
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
329#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
330#[serde(rename_all = "camelCase", deny_unknown_fields)]
331pub struct SandboxCapabilities {
332 pub files: bool,
334 pub reconnect: bool,
336 pub jobs: bool,
339 pub interactive_commands: bool,
342 pub preview: bool,
344 pub pause_resume: bool,
346 pub snapshot: bool,
348 pub domain_egress_rules: bool,
350 pub egress_deny: bool,
353 pub enforced_limits: bool,
355 pub process_limit: bool,
357 pub sandbox_lifetime: bool,
359 pub supervisor_pid_namespace: bool,
365 pub supervisor_isolation: bool,
372}
373
374impl SandboxCapabilities {
375 pub fn for_platform(platform: Platform) -> Result<Self> {
381 match platform {
382 Platform::Aws => Ok(Self {
383 files: true,
384 reconnect: true,
385 jobs: true,
386 interactive_commands: true,
389 preview: true,
390 pause_resume: true,
391 snapshot: false,
392 domain_egress_rules: false,
393 egress_deny: true,
396 enforced_limits: true,
397 process_limit: false,
399 sandbox_lifetime: true,
402 supervisor_pid_namespace: false,
407 supervisor_isolation: true,
410 }),
411 Platform::Azure => Ok(Self::azure()),
412 Platform::Gcp => Ok(Self::gcp_agent_platform()),
413 Platform::Kubernetes => Ok(Self {
414 files: true,
415 reconnect: true,
416 jobs: true,
417 interactive_commands: true,
422 preview: true,
428 pause_resume: false,
431 snapshot: false,
433 domain_egress_rules: false,
434 egress_deny: true,
435 enforced_limits: true,
436 process_limit: false,
441 sandbox_lifetime: true,
447 supervisor_pid_namespace: false,
451 supervisor_isolation: true,
457 }),
458 Platform::Local => Ok(Self {
459 files: true,
460 reconnect: true,
461 jobs: false,
463 interactive_commands: true,
466 preview: true,
467 pause_resume: false,
468 snapshot: false,
469 domain_egress_rules: false,
470 egress_deny: true,
471 enforced_limits: true,
472 process_limit: true,
474 sandbox_lifetime: false,
475 supervisor_pid_namespace: false,
478 supervisor_isolation: true,
482 }),
483 Platform::Machines | Platform::Test => {
484 Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
485 platform: platform.to_string(),
486 }))
487 }
488 }
489 }
490
491 pub fn azure() -> Self {
493 Self {
494 files: true,
495 reconnect: true,
496 jobs: true,
499 interactive_commands: true,
503 preview: true,
510 pause_resume: true,
511 snapshot: false,
515 domain_egress_rules: true,
516 egress_deny: true,
517 enforced_limits: true,
521 process_limit: false,
522 sandbox_lifetime: true,
527 supervisor_pid_namespace: false,
529 supervisor_isolation: false,
532 }
533 }
534
535 pub fn gcp_agent_platform() -> Self {
537 Self {
538 files: true,
540 reconnect: true,
544 jobs: true,
545 interactive_commands: false,
548 preview: true,
554 pause_resume: true,
560 snapshot: false,
563 domain_egress_rules: false,
565 egress_deny: true,
568 enforced_limits: true,
572 process_limit: false,
574 sandbox_lifetime: true,
576 supervisor_pid_namespace: false,
578 supervisor_isolation: false,
581 }
582 }
583
584 pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
586 let available = match capability {
587 SandboxCapability::Files => self.files,
588 SandboxCapability::Reconnect => self.reconnect,
589 SandboxCapability::Jobs => self.jobs,
590 SandboxCapability::InteractiveCommands => self.interactive_commands,
591 SandboxCapability::Preview => self.preview,
592 SandboxCapability::PauseResume => self.pause_resume,
593 SandboxCapability::Snapshot => self.snapshot,
594 SandboxCapability::DomainEgressRules => self.domain_egress_rules,
595 SandboxCapability::EgressDeny => self.egress_deny,
596 SandboxCapability::EnforcedLimits => self.enforced_limits,
597 SandboxCapability::ProcessLimit => self.process_limit,
598 SandboxCapability::SandboxLifetime => self.sandbox_lifetime,
599 SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
600 SandboxCapability::SupervisorIsolation => self.supervisor_isolation,
601 };
602
603 if available {
604 return Ok(());
605 }
606
607 Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
608 capability: capability.as_str().to_string(),
609 platform: platform.to_string(),
610 }))
611 }
612}
613
614#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
616#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
617#[serde(rename_all = "camelCase")]
618pub enum SandboxCapability {
619 Files,
621 Reconnect,
623 Jobs,
625 InteractiveCommands,
627 Preview,
629 PauseResume,
631 Snapshot,
633 DomainEgressRules,
635 EgressDeny,
637 EnforcedLimits,
639 ProcessLimit,
641 SandboxLifetime,
643 SupervisorPidNamespace,
645 SupervisorIsolation,
647}
648
649impl SandboxCapability {
650 pub fn as_str(&self) -> &'static str {
652 match self {
653 Self::Files => "files",
654 Self::Reconnect => "reconnect",
655 Self::Jobs => "jobs",
656 Self::InteractiveCommands => "interactiveCommands",
657 Self::Preview => "preview",
658 Self::PauseResume => "pauseResume",
659 Self::Snapshot => "snapshot",
660 Self::DomainEgressRules => "domainEgressRules",
661 Self::EgressDeny => "egressDeny",
662 Self::EnforcedLimits => "enforcedLimits",
663 Self::ProcessLimit => "processLimit",
664 Self::SandboxLifetime => "sandboxLifetime",
665 Self::SupervisorPidNamespace => "supervisorPidNamespace",
666 Self::SupervisorIsolation => "supervisorIsolation",
667 }
668 }
669}
670
671#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
673#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
674#[serde(rename_all = "camelCase", deny_unknown_fields)]
675pub struct SandboxPrivilegedSupervisor {
676 pub command_uid: u32,
678}
679
680#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
682#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
683#[serde(rename_all = "camelCase", deny_unknown_fields)]
684#[builder(start_fn = new)]
685pub struct Sandbox {
686 #[builder(start_fn)]
689 pub id: String,
690 #[builder(field)]
693 #[serde(default, skip_serializing_if = "Vec::is_empty")]
694 #[cfg_attr(feature = "openapi", schema(ignore))]
695 pub links: Vec<ResourceRef>,
696 pub code: SandboxCode,
698 #[builder(skip)]
701 #[serde(default, skip_serializing_if = "Option::is_none")]
702 #[cfg_attr(feature = "openapi", schema(ignore))]
703 pub image_user: Option<u32>,
704 #[serde(skip_serializing_if = "Option::is_none")]
708 pub private_base_image: Option<String>,
709 #[serde(skip_serializing_if = "Option::is_none")]
715 pub limits: Option<SandboxLimits>,
716 pub egress: SandboxEgress,
718 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub default_policy: Option<EgressPolicy>,
721 #[builder(skip)]
725 #[serde(default, skip_serializing_if = "Option::is_none")]
726 pub privileged_supervisor: Option<SandboxPrivilegedSupervisor>,
727 #[serde(alias = "session")]
732 pub lifecycle: SandboxLifecyclePolicy,
733 #[builder(default)]
737 #[serde(default, skip_serializing_if = "Vec::is_empty")]
738 pub preview_ports: Vec<u16>,
739}
740
741pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
746 !targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
747}
748
749pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
755 stack.resources().any(|(_, entry)| {
756 entry
757 .config
758 .downcast_ref::<Sandbox>()
759 .is_some_and(|sandbox| crate::sandbox_egress::sandbox_needs_connector(stack, sandbox))
760 })
761}
762
763impl Sandbox {
764 pub(crate) fn setup_digest_value(&self) -> serde_json::Value {
765 match &self.egress {
766 SandboxEgress::None => serde_json::json!({"mode":"deny"}),
767 value => serde_json::to_value(value).expect("egress serializes"),
768 }
769 }
770
771 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
773
774 pub fn id(&self) -> &str {
776 &self.id
777 }
778
779 pub fn cloud_egress(&self) -> &SandboxEgress {
782 if self.privileged_supervisor.is_some() && self.egress != SandboxEgress::Internet {
783 &SandboxEgress::Allow
784 } else {
785 &self.egress
786 }
787 }
788
789 pub fn supervisor_environment(&self) -> std::collections::BTreeMap<String, String> {
791 let mut env = std::collections::BTreeMap::new();
792 if let Some(supervisor) = &self.privileged_supervisor {
793 env.insert(
794 "ALIEN_SANDBOX_EXPECTED_EXEC_UID".to_string(),
795 supervisor.command_uid.to_string(),
796 );
797 env.insert(
798 "ALIEN_SANDBOX_EGRESS".to_string(),
799 if self.egress == SandboxEgress::None {
801 r#"{"mode":"deny"}"#.to_string()
802 } else {
803 serde_json::to_string(&self.egress).expect("egress serializes")
804 },
805 );
806 }
807 env
808 }
809
810 pub fn resolved_limits(&self) -> SandboxLimits {
816 self.limits.clone().unwrap_or_else(default_limits)
817 }
818
819 pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
824 if let Some(policy) = &self.default_policy {
825 if self.egress != SandboxEgress::Internet {
826 return Err(AlienError::new(ErrorData::SandboxEgressInvalid {
827 target: "defaultPolicy".into(),
828 reason: "defaultPolicy requires the new internet declaration".into(),
829 }));
830 }
831 policy.validate()?;
832 if platform == Platform::Gcp {
833 return Err(AlienError::new(ErrorData::SandboxEgressInvalid {
834 target: "defaultPolicy".into(),
835 reason: GCP_NO_EGRESS_ALLOWLIST.into(),
836 }));
837 }
838 }
839 if self.image_user == Some(0) && platform == Platform::Local {
840 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
841 capability: "root image USER: this backend does not yet separate bounded root boot from non-root exec; use a non-root image USER".into(),
842 platform: platform.to_string(),
843 }));
844 }
845 if self.image_user == Some(0)
849 && platform == Platform::Kubernetes
850 && !matches!(self.egress, SandboxEgress::Internet | SandboxEgress::None)
851 {
852 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
853 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(),
854 platform: platform.to_string(),
855 }));
856 }
857 let mut capabilities = SandboxCapabilities::for_platform(platform)?;
858 if let Some(supervisor) = &self.privileged_supervisor {
859 if platform != Platform::Aws {
860 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
861 capability: "privilegedSupervisor".to_string(),
862 platform: platform.to_string(),
863 }));
864 }
865 if supervisor.command_uid == 0 || supervisor.command_uid == u32::MAX {
866 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
867 resource_id: self.id.clone(),
868 field: "privilegedSupervisor.commandUid".to_string(),
869 value: supervisor.command_uid.to_string(),
870 reason: "must be a non-root Linux uid other than the invalid uid sentinel"
871 .to_string(),
872 }));
873 }
874 if let SandboxEgress::AllowDomains { domains } = &self.egress {
875 for domain in domains {
876 let hostname = domain.strip_suffix('.').unwrap_or(domain);
877 if hostname.len() > 253
878 || !hostname.split('.').all(|label| {
879 !label.is_empty()
880 && label.len() <= 63
881 && label
882 .bytes()
883 .all(|c| c.is_ascii_alphanumeric() || c == b'-')
884 && !label.starts_with('-')
885 && !label.ends_with('-')
886 })
887 {
888 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
889 resource_id: self.id.clone(), field: "egress.domains".to_string(), value: domain.clone(),
890 reason: "privileged supervisor allowlists require exact DNS hostnames; wildcards are unsupported".to_string(),
891 }));
892 }
893 }
894 }
895 capabilities.domain_egress_rules = true;
896 }
897
898 if matches!(&self.code, SandboxCode::Source { .. })
903 && !matches!(
904 platform,
905 Platform::Aws | Platform::Azure | Platform::Gcp | Platform::Kubernetes
906 )
907 {
908 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
909 resource_id: self.id.clone(),
910 field: "code".to_string(),
911 value: "source".to_string(),
912 reason: format!(
913 "no sandbox backend builds an image from source on {platform}; give \
914 code.image a prebuilt reference"
915 ),
916 }));
917 }
918
919 if self.private_base_image.is_some() && platform != Platform::Aws {
922 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
923 capability: "privateBaseImage".to_string(),
924 platform: platform.to_string(),
925 }));
926 }
927
928 if platform == Platform::Azure && matches!(&self.code, SandboxCode::Image { .. }) {
931 self.azure_image()?;
932 }
933
934 if let Some(seconds) = self.lifecycle.max_lifetime_seconds {
937 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
939
940 if seconds == 0 {
941 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
942 resource_id: self.id.clone(),
943 field: "maxLifetimeSeconds".to_string(),
944 value: "0".to_string(),
945 reason: "a sandbox must be allowed to run for at least 1 second".to_string(),
946 }));
947 }
948
949 let ceiling = match platform {
954 Platform::Aws => Some((AWS_MAX_LIFETIME_SECONDS, "AWS runs a MicroVM for")),
955 Platform::Kubernetes => {
956 Some((KUBERNETES_MAX_LIFETIME_SECONDS, "Kubernetes runs a pod for"))
957 }
958 Platform::Gcp => None,
961 Platform::Azure | Platform::Local | Platform::Machines | Platform::Test => None,
964 };
965 if let Some((max, runs_for)) = ceiling {
966 if seconds > max {
967 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
968 resource_id: self.id.clone(),
969 field: "maxLifetimeSeconds".to_string(),
970 value: seconds.to_string(),
971 reason: format!("{runs_for} between 1 and {max} seconds"),
972 }));
973 }
974 }
975 }
976
977 let Some(limits) = self.limits.as_ref() else {
978 return self.validate_capabilities(&capabilities, platform);
980 };
981
982 validate_quantity(&self.id, "cpu", &limits.cpu)?;
983 validate_quantity(&self.id, "memory", &limits.memory)?;
984 validate_quantity(&self.id, "disk", &limits.disk)?;
985
986 if let Some(max_processes) = limits.max_processes {
987 if max_processes == 0 {
988 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
989 resource_id: self.id.clone(),
990 field: "maxProcesses".to_string(),
991 value: "0".to_string(),
992 reason: "a sandbox that may run no processes cannot run code".to_string(),
993 }));
994 }
995 capabilities.require(SandboxCapability::ProcessLimit, platform)?;
996 }
997
998 capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
1001
1002 if platform == Platform::Azure {
1003 self.azure_sandbox_limits()?;
1004 }
1005
1006 if platform == Platform::Gcp {
1007 self.gcp_sandbox_limits()?;
1008 }
1009
1010 if platform == Platform::Aws {
1011 self.microvm_tier()?;
1014 }
1015
1016 self.validate_capabilities(&capabilities, platform)
1017 }
1018
1019 pub fn azure_image(&self) -> Result<AzureSandboxImage<'_>> {
1023 let SandboxCode::Image { image, .. } = &self.code else {
1024 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1025 resource_id: self.id.clone(),
1026 field: "code".to_string(),
1027 value: "source".to_string(),
1028 reason: "the sandbox still has unbuilt source code. Run 'alien build' first"
1029 .to_string(),
1030 }));
1031 };
1032
1033 classify_azure_sandbox_image(image).ok_or_else(|| {
1034 let image = image.trim();
1035 AlienError::new(ErrorData::SandboxLimitInvalid {
1036 resource_id: self.id.clone(),
1037 field: "code.image".to_string(),
1038 value: image.to_string(),
1039 reason: if image.is_empty() {
1040 "a sandbox has to name an image".to_string()
1041 } else {
1042 "Azure creates a sandbox from a catalog name such as 'ubuntu' or from a \
1043 registry image such as 'docker.io/library/python:3.14-slim'"
1044 .to_string()
1045 },
1046 })
1047 })
1048 }
1049
1050 pub fn gcp_sandbox_limits(&self) -> Result<()> {
1053 let Some(limits) = self.limits.as_ref() else {
1054 return Ok(());
1055 };
1056 let over_cap =
1057 quantity_exceeds_bytes(&limits.disk, GCP_MAX_DISK_BYTES).ok_or_else(|| {
1058 AlienError::new(ErrorData::SandboxLimitInvalid {
1059 resource_id: self.id.clone(),
1060 field: "disk".to_string(),
1061 value: limits.disk.clone(),
1062 reason: "expected a size such as 8Gi".to_string(),
1063 })
1064 })?;
1065 if over_cap {
1066 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1067 resource_id: self.id.clone(),
1068 field: "disk".to_string(),
1069 value: limits.disk.clone(),
1070 reason: "GCP Agent Platform caps a sandbox's ephemeral storage at 10Gi; declare \
1071 10Gi or less"
1072 .to_string(),
1073 }));
1074 }
1075 Ok(())
1076 }
1077
1078 pub fn azure_sandbox_limits(&self) -> Result<()> {
1082 let Some(limits) = self.limits.as_ref() else {
1083 return Ok(());
1086 };
1087
1088 let refused = |field: &str, value: &str, reason: &str| {
1089 AlienError::new(ErrorData::SandboxLimitInvalid {
1090 resource_id: self.id.clone(),
1091 field: field.to_string(),
1092 value: value.to_string(),
1093 reason: reason.to_string(),
1094 })
1095 };
1096
1097 let cpu_millicores = millicores(&limits.cpu)
1098 .ok_or_else(|| refused("cpu", &limits.cpu, "expected cores or millicores"))?;
1099
1100 if cpu_millicores % AZURE_CPU_STEP_MILLICORES != 0
1104 || !(AZURE_CPU_STEP_MILLICORES..=AZURE_MAX_CPU_MILLICORES).contains(&cpu_millicores)
1105 {
1106 return Err(refused(
1107 "cpu",
1108 &limits.cpu,
1109 "Azure allocates cpu in steps of 250m from 250m to 16000m",
1110 ));
1111 }
1112
1113 let memory_ceiling_mib = cpu_millicores * AZURE_MEMORY_MIB_PER_CORE / 1000;
1115 let disk_ceiling_mib = cpu_millicores * AZURE_DISK_MIB_PER_CORE / 1000;
1116
1117 let memory_mib = quantity_mib(&limits.memory)
1118 .ok_or_else(|| refused("memory", &limits.memory, "Azure sizes memory in whole MiB"))?;
1119 if memory_mib > memory_ceiling_mib {
1120 return Err(refused(
1121 "memory",
1122 &limits.memory,
1123 &format!(
1124 "Azure allows at most 2Gi of memory per core, or {memory_ceiling_mib}Mi \
1125 at the declared cpu"
1126 ),
1127 ));
1128 }
1129
1130 let disk_mib = quantity_mib(&limits.disk)
1131 .ok_or_else(|| refused("disk", &limits.disk, "Azure sizes disk in whole MiB"))?;
1132 if disk_mib > disk_ceiling_mib {
1133 return Err(refused(
1134 "disk",
1135 &limits.disk,
1136 &format!(
1137 "Azure allows at most 20Gi of disk per core, or {disk_ceiling_mib}Mi at \
1138 the declared cpu"
1139 ),
1140 ));
1141 }
1142
1143 Ok(())
1144 }
1145
1146 pub fn microvm_tier(&self) -> Result<MicrovmTier> {
1153 let Some(limits) = self.limits.as_ref() else {
1154 return Ok(MICROVM_TIERS[2]);
1158 };
1159
1160 let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
1161 AlienError::new(ErrorData::SandboxLimitInvalid {
1162 resource_id: self.id.clone(),
1163 field: "memory".to_string(),
1164 value: limits.memory.clone(),
1165 reason: "AWS sizes a MicroVM in whole MiB".to_string(),
1166 })
1167 })?;
1168 let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
1169 AlienError::new(ErrorData::SandboxLimitInvalid {
1170 resource_id: self.id.clone(),
1171 field: "disk".to_string(),
1172 value: limits.disk.clone(),
1173 reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
1174 })
1175 })?;
1176 let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
1177 AlienError::new(ErrorData::SandboxLimitInvalid {
1178 resource_id: self.id.clone(),
1179 field: "cpu".to_string(),
1180 value: limits.cpu.clone(),
1181 reason: "expected cores or millicores".to_string(),
1182 })
1183 })?;
1184
1185 let sized = |tier: &&MicrovmTier| {
1190 tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
1191 };
1192
1193 let tier = MICROVM_TIERS
1194 .iter()
1195 .rev()
1196 .find(sized)
1197 .copied()
1198 .ok_or_else(|| {
1199 AlienError::new(ErrorData::SandboxLimitInvalid {
1200 resource_id: self.id.clone(),
1201 field: "memory".to_string(),
1202 value: limits.memory.clone(),
1203 reason: format!(
1204 "a Lambda MicroVM bursts to four times its baseline, so the smallest \
1205 ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
1206 disk fit no size",
1207 limits.memory, limits.disk
1208 ),
1209 })
1210 })?;
1211
1212 let required_millicores = i64::from(tier.peak_vcpu) * 1000;
1213 if cpu_millicores < required_millicores {
1214 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1215 resource_id: self.id.clone(),
1216 field: "cpu".to_string(),
1217 value: limits.cpu.clone(),
1218 reason: format!(
1219 "AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
1220 reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
1221 limits.memory, tier.peak_vcpu, tier.peak_vcpu
1222 ),
1223 }));
1224 }
1225
1226 Ok(tier)
1227 }
1228
1229 fn validate_capabilities(
1231 &self,
1232 capabilities: &SandboxCapabilities,
1233 platform: Platform,
1234 ) -> Result<()> {
1235 if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
1236 capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
1237 }
1238
1239 if let SandboxEgress::AllowDomains { domains } = &self.egress {
1245 if domains.is_empty() {
1246 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1247 resource_id: self.id.clone(),
1248 field: "egress.domains".to_string(),
1249 value: "[]".to_string(),
1250 reason: "an allowlist naming no domain denies everything; declare \
1251 egress: deny if that is what was meant"
1252 .to_string(),
1253 }));
1254 }
1255 }
1256
1257 if matches!(self.egress, SandboxEgress::None) {
1258 capabilities.require(SandboxCapability::EgressDeny, platform)?;
1259 }
1260
1261 if platform == Platform::Gcp
1264 && self
1265 .preview_ports
1266 .contains(&crate::sandbox_image::GCP_AGENT_PLATFORM.port)
1267 {
1268 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1269 resource_id: self.id.clone(),
1270 field: "previewPorts".to_string(),
1271 value: crate::sandbox_image::GCP_AGENT_PLATFORM.port.to_string(),
1272 reason: "that port is the Alien agent's own on GCP Agent Platform; choose \
1273 another port for the workload"
1274 .to_string(),
1275 }));
1276 }
1277
1278 if !self.preview_ports.is_empty() {
1279 capabilities.require(SandboxCapability::Preview, platform)?;
1280 if platform == Platform::Azure
1281 && matches!(self.azure_image(), Ok(AzureSandboxImage::Catalog(_)))
1282 {
1283 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1284 capability:
1285 "preview (a catalog image runs without the Alien agent that issues \
1286 the capability; build the sandbox from source)"
1287 .to_string(),
1288 platform: platform.to_string(),
1289 }));
1290 }
1291 }
1292
1293 if self.lifecycle.idle_pause_seconds.is_some() {
1294 if platform == Platform::Gcp {
1297 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
1298 capability: "idle pause policy: the GCP Agent Platform backend has no idle policy and Alien does not watch for idleness there; remove the idle policy and pause the sandbox explicitly".to_string(),
1299 platform: platform.to_string(),
1300 }));
1301 }
1302 capabilities.require(SandboxCapability::PauseResume, platform)?;
1303 }
1304
1305 if self.lifecycle.max_lifetime_seconds.is_some() {
1306 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
1307 }
1308
1309 Ok(())
1310 }
1311}
1312
1313fn default_limits() -> SandboxLimits {
1318 SandboxLimits {
1319 cpu: "1".to_string(),
1320 memory: "2Gi".to_string(),
1321 disk: "8Gi".to_string(),
1322 max_processes: None,
1323 }
1324}
1325
1326fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
1328 let invalid = |reason: &str| {
1329 AlienError::new(ErrorData::SandboxLimitInvalid {
1330 resource_id: resource_id.to_string(),
1331 field: field.to_string(),
1332 value: value.to_string(),
1333 reason: reason.to_string(),
1334 })
1335 };
1336
1337 let digits_end = value
1338 .find(|c: char| !c.is_ascii_digit() && c != '.')
1339 .unwrap_or(value.len());
1340 let (number, suffix) = value.split_at(digits_end);
1341
1342 let parsed: f64 = number
1343 .parse()
1344 .map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
1345
1346 if parsed <= 0.0 {
1347 return Err(invalid("must be greater than zero"));
1348 }
1349
1350 const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
1351 if !SUFFIXES.contains(&suffix) {
1352 return Err(invalid(
1353 "unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
1354 ));
1355 }
1356
1357 Ok(())
1358}
1359
1360fn split_quantity(value: &str) -> Option<(f64, &str)> {
1362 let trimmed = value.trim();
1363 let digits_end = trimmed
1364 .find(|c: char| !c.is_ascii_digit() && c != '.')
1365 .unwrap_or(trimmed.len());
1366 let (number, suffix) = trimmed.split_at(digits_end);
1367 number.parse().ok().map(|number| (number, suffix))
1368}
1369
1370pub fn quantity_mib(value: &str) -> Option<i64> {
1376 let (number, suffix) = split_quantity(value)?;
1377 let bytes = match suffix {
1378 "" => number,
1379 "k" => number * 1e3,
1380 "M" => number * 1e6,
1381 "G" => number * 1e9,
1382 "T" => number * 1e12,
1383 "Ki" => number * 1024.0,
1384 "Mi" => number * 1024.0 * 1024.0,
1385 "Gi" => number * 1024.0 * 1024.0 * 1024.0,
1386 "Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
1387 _ => return None,
1389 };
1390 Some((bytes / (1024.0 * 1024.0)) as i64)
1391}
1392
1393fn quantity_exceeds_bytes(value: &str, cap_bytes: u128) -> Option<bool> {
1396 let trimmed = value.trim();
1397 let digits_end = trimmed
1398 .find(|c: char| !c.is_ascii_digit() && c != '.')
1399 .unwrap_or(trimmed.len());
1400 let (number, suffix) = trimmed.split_at(digits_end);
1401 let unit: u128 = match suffix {
1402 "" => 1,
1403 "k" => 1_000,
1404 "M" => 1_000_000,
1405 "G" => 1_000_000_000,
1406 "T" => 1_000_000_000_000,
1407 "Ki" => 1 << 10,
1408 "Mi" => 1 << 20,
1409 "Gi" => 1 << 30,
1410 "Ti" => 1 << 40,
1411 _ => return None,
1412 };
1413 let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
1414 if (whole.is_empty() && fraction.is_empty()) || fraction.contains('.') {
1415 return None;
1416 }
1417 let digits = format!("{whole}{fraction}");
1418 let scale = 10u128.checked_pow(u32::try_from(fraction.len()).ok()?)?;
1419 let mantissa: u128 = digits.parse().ok()?;
1420 Some(mantissa.checked_mul(unit)? > cap_bytes.checked_mul(scale)?)
1422}
1423
1424pub fn millicores(value: &str) -> Option<i64> {
1426 let (number, suffix) = split_quantity(value)?;
1427 match suffix {
1428 "" => Some((number * 1000.0) as i64),
1429 "m" => Some(number as i64),
1430 _ => None,
1431 }
1432}
1433
1434#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1436#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1437#[serde(rename_all = "camelCase")]
1438pub struct SandboxOutputs {
1439 pub parent_name: String,
1441 #[serde(skip_serializing_if = "Option::is_none")]
1443 pub identifier: Option<String>,
1444 #[serde(skip_serializing_if = "Option::is_none")]
1446 pub endpoint: Option<String>,
1447}
1448
1449impl ResourceOutputsDefinition for SandboxOutputs {
1450 fn get_resource_type(&self) -> ResourceType {
1451 Sandbox::RESOURCE_TYPE
1452 }
1453
1454 fn as_any(&self) -> &dyn Any {
1455 self
1456 }
1457
1458 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
1459 Box::new(self.clone())
1460 }
1461
1462 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
1463 other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
1464 }
1465
1466 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1467 serde_json::to_value(self)
1468 }
1469}
1470
1471impl ResourceDefinition for Sandbox {
1472 fn get_resource_type(&self) -> ResourceType {
1473 Self::RESOURCE_TYPE
1474 }
1475
1476 fn id(&self) -> &str {
1477 &self.id
1478 }
1479
1480 fn replace_after_failed_create_is_safe(&self) -> bool {
1481 false
1484 }
1485
1486 fn get_dependencies(&self) -> Vec<ResourceRef> {
1487 Vec::new()
1488 }
1489
1490 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1491 let new_sandbox = new_config
1492 .as_any()
1493 .downcast_ref::<Sandbox>()
1494 .ok_or_else(|| {
1495 AlienError::new(ErrorData::UnexpectedResourceType {
1496 resource_id: self.id.clone(),
1497 expected: Self::RESOURCE_TYPE,
1498 actual: new_config.get_resource_type(),
1499 })
1500 })?;
1501
1502 if self.id != new_sandbox.id {
1503 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1504 resource_id: self.id.clone(),
1505 reason: "the 'id' field is immutable".to_string(),
1506 }));
1507 }
1508
1509 Ok(())
1510 }
1511
1512 fn as_any(&self) -> &dyn Any {
1513 self
1514 }
1515
1516 fn as_any_mut(&mut self) -> &mut dyn Any {
1517 self
1518 }
1519
1520 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1521 Box::new(self.clone())
1522 }
1523
1524 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1525 other.as_any().downcast_ref::<Sandbox>() == Some(self)
1526 }
1527
1528 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1529 serde_json::to_value(self)
1530 }
1531}
1532
1533#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1535pub enum AzureSandboxImage<'a> {
1536 Catalog(&'a str),
1538 Registry(&'a str),
1541}
1542
1543impl<'a> AzureSandboxImage<'a> {
1544 pub fn as_str(&self) -> &'a str {
1546 match self {
1547 Self::Catalog(value) | Self::Registry(value) => value,
1548 }
1549 }
1550}
1551
1552pub const AZURE_DISK_IMAGE_LABEL: &str = "alienImage";
1554
1555pub fn classify_azure_sandbox_image(image: &str) -> Option<AzureSandboxImage<'_>> {
1559 let image = image.trim();
1560 if image.is_empty() {
1561 return None;
1562 }
1563 if image
1564 .chars()
1565 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1566 {
1567 return Some(AzureSandboxImage::Catalog(image));
1568 }
1569 (image.contains(|c| matches!(c, '/' | ':' | '@')) && OCI_REFERENCE.is_match(image))
1570 .then_some(AzureSandboxImage::Registry(image))
1571}
1572
1573pub fn azure_disk_image_label(reference: &str) -> String {
1576 let digest = format!("{:x}", Sha256::digest(reference.trim().as_bytes()));
1577 digest[..32].to_string()
1578}
1579
1580static OCI_REFERENCE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1582 let domain_component = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
1583 let domain = format!(r"{domain_component}(?:\.{domain_component})*(?::[0-9]+)?");
1584 let path_component = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
1585 let name = format!(r"(?:{domain}/)?{path_component}(?:/{path_component})*");
1586 let tag = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}";
1587 let digest = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
1588 regex::Regex::new(&format!(r"^{name}(?::{tag})?(?:@{digest})?$"))
1589 .expect("the OCI reference grammar compiles")
1590});
1591
1592pub const BUNDLE_REGION_TOKEN: &str = "{region}";
1597
1598#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1600pub enum BundleUri<'a> {
1601 Literal(&'a str),
1603 Regional { before: &'a str, after: &'a str },
1606}
1607
1608pub fn stable_bundle_key_prefix(key: &str) -> Option<&str> {
1612 let (above_file, _) = key.rsplit_once('/')?;
1613 let (above_version, _) = above_file.rsplit_once('/')?;
1614 Some(above_version)
1615}
1616
1617pub fn parse_bundle_uri(uri: &str) -> std::result::Result<BundleUri<'_>, String> {
1623 let path = uri
1624 .strip_prefix("s3://")
1625 .ok_or_else(|| format!("'{uri}' is not an s3:// URI"))?;
1626 let (bucket, key) = path
1627 .split_once('/')
1628 .ok_or_else(|| format!("'{uri}' names a bucket with no object key"))?;
1629
1630 if path.contains('*') || path.contains('?') {
1634 return Err(format!(
1635 "'{uri}' carries an IAM wildcard; the bundle's path is interpolated into the build \
1636 role's grant, so '*' and '?' would widen it past the bundle"
1637 ));
1638 }
1639
1640 if key.contains('{') || key.contains('}') {
1641 return Err(format!(
1642 "'{uri}' places a token in the object key; {BUNDLE_REGION_TOKEN} is accepted in the \
1643 bucket name alone"
1644 ));
1645 }
1646
1647 let Some((before, after)) = bucket.split_once(BUNDLE_REGION_TOKEN) else {
1648 if bucket.contains('{') || bucket.contains('}') {
1649 return Err(format!(
1650 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the \
1651 only one"
1652 ));
1653 }
1654 return Ok(BundleUri::Literal(uri));
1655 };
1656
1657 if after.contains(BUNDLE_REGION_TOKEN) {
1658 return Err(format!("'{uri}' repeats {BUNDLE_REGION_TOKEN}"));
1659 }
1660 if before.contains('{') || before.contains('}') || after.contains('{') || after.contains('}') {
1661 return Err(format!(
1662 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the only one"
1663 ));
1664 }
1665
1666 Ok(BundleUri::Regional {
1667 before: &uri[.."s3://".len() + before.len()],
1668 after: &uri["s3://".len() + before.len() + BUNDLE_REGION_TOKEN.len()..],
1669 })
1670}
1671
1672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1674pub enum EcrImageRegion<'a> {
1675 Literal(&'a str),
1677 Deployment,
1679}
1680
1681#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1683pub struct EcrImageRepository<'a> {
1684 pub account_id: &'a str,
1685 pub region: EcrImageRegion<'a>,
1686 pub repository: &'a str,
1688}
1689
1690impl EcrImageRepository<'_> {
1691 pub fn arn(&self, partition: &str, region: &str) -> String {
1694 let region = match self.region {
1695 EcrImageRegion::Literal(region) => region,
1696 EcrImageRegion::Deployment => region,
1697 };
1698 format!(
1699 "arn:{partition}:ecr:{region}:{}:repository/{}",
1700 self.account_id, self.repository
1701 )
1702 }
1703}
1704
1705pub fn parse_ecr_image_repository(
1711 image: &str,
1712) -> std::result::Result<EcrImageRepository<'_>, String> {
1713 let refuse = |reason: &str| format!("privateBaseImage '{image}' {reason}");
1714 let (host, path) = image
1715 .split_once('/')
1716 .ok_or_else(|| refuse("names no repository"))?;
1717 let (account_id, rest) = host.split_once(".dkr.ecr.").ok_or_else(|| {
1718 refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)")
1719 })?;
1720 let region = rest
1722 .strip_suffix(".amazonaws.com.cn")
1723 .or_else(|| rest.strip_suffix(".amazonaws.com"))
1724 .ok_or_else(|| refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)"))?;
1725 if account_id.len() != 12 || !account_id.bytes().all(|b| b.is_ascii_digit()) {
1726 return Err(refuse("names no 12-digit account in its registry host"));
1727 }
1728 let region = if region == BUNDLE_REGION_TOKEN {
1729 EcrImageRegion::Deployment
1730 } else if !region.is_empty()
1731 && region
1732 .bytes()
1733 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1734 {
1735 EcrImageRegion::Literal(region)
1736 } else {
1737 return Err(refuse(&format!(
1738 "names no region in its registry host; give one or {BUNDLE_REGION_TOKEN}"
1739 )));
1740 };
1741
1742 let repository = match path.split_once('@') {
1743 Some((repository, _digest)) => repository,
1744 None => match path.rsplit_once('/') {
1745 Some((parent, last)) => match last.split_once(':') {
1746 Some((name, _tag)) => &path[..parent.len() + 1 + name.len()],
1747 None => path,
1748 },
1749 None => path.split_once(':').map_or(path, |(name, _tag)| name),
1750 },
1751 };
1752 let valid_segment = |segment: &str| {
1753 !segment.is_empty()
1754 && segment.bytes().all(|b| {
1755 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
1756 })
1757 };
1758 if !repository.split('/').all(valid_segment) {
1759 return Err(refuse(
1760 "names a repository outside ECR's grammar (lowercase letters, digits, '.', '_', '-', and '/' between them)",
1761 ));
1762 }
1763 Ok(EcrImageRepository {
1764 account_id,
1765 region,
1766 repository,
1767 })
1768}
1769
1770#[cfg(test)]
1771mod tests {
1772 use super::*;
1773
1774 #[test]
1775 fn private_database_setup_accepts_the_default_network() {
1776 for lifecycle in [
1777 crate::ResourceLifecycle::Frozen,
1778 crate::ResourceLifecycle::Live,
1779 ] {
1780 let stack = crate::Stack::new("database".to_string())
1781 .add(
1782 crate::Postgres::new("metadata".to_string()).build(),
1783 lifecycle,
1784 )
1785 .build();
1786 assert!(!restricts_network_mode(&stack, false));
1787 assert!(!restricts_network_mode(&stack, true));
1788 }
1789 assert!(!restricts_network_mode(
1790 &crate::Stack::new("empty".to_string()).build(),
1791 false,
1792 ));
1793 }
1794
1795 fn repository_key(image: &str) -> String {
1798 match parse_ecr_image_repository(image) {
1799 Ok(parsed) => {
1800 let host = image.split_once('/').map_or(image, |(host, _)| host);
1801 format!("{host}/{}", parsed.repository)
1802 }
1803 Err(_) => image.to_string(),
1804 }
1805 }
1806
1807 #[test]
1808 fn a_private_base_image_names_one_repository() {
1809 let vectors: serde_json::Value = serde_json::from_str(include_str!(
1810 "../../tests/fixtures/ecr-image-repository-parity.json"
1811 ))
1812 .expect("the ECR repository vectors must be JSON");
1813 let field = |case: &serde_json::Value, name: &str| {
1814 case[name]
1815 .as_str()
1816 .unwrap_or_else(|| panic!("vector must carry {name}: {case}"))
1817 .to_string()
1818 };
1819
1820 for case in vectors["accepted"].as_array().expect("accepted vectors") {
1821 let image = field(case, "image");
1822 let region = field(case, "region");
1823 let region = if region == BUNDLE_REGION_TOKEN {
1824 EcrImageRegion::Deployment
1825 } else {
1826 EcrImageRegion::Literal(®ion)
1827 };
1828 assert_eq!(
1829 parse_ecr_image_repository(&image),
1830 Ok(EcrImageRepository {
1831 account_id: &field(case, "accountId"),
1832 region,
1833 repository: &field(case, "repository"),
1834 }),
1835 "{image}"
1836 );
1837 assert_eq!(
1838 repository_key(&image),
1839 field(case, "repositoryKey"),
1840 "{image}"
1841 );
1842 }
1843
1844 for case in vectors["refused"].as_array().expect("refused vectors") {
1845 let image = field(case, "image");
1846 assert!(
1847 parse_ecr_image_repository(&image).is_err(),
1848 "{image} must be refused"
1849 );
1850 assert_eq!(
1851 repository_key(&image),
1852 field(case, "repositoryKey"),
1853 "{image}"
1854 );
1855 }
1856 }
1857
1858 #[test]
1859 fn a_repository_arn_takes_the_deployment_region_only_where_the_host_leaves_it() {
1860 let regional =
1861 parse_ecr_image_repository("123456789012.dkr.ecr.{region}.amazonaws.com/team/base:1")
1862 .expect("parses");
1863 let pinned =
1864 parse_ecr_image_repository("123456789012.dkr.ecr.eu-west-1.amazonaws.com/team/base:1")
1865 .expect("parses");
1866 assert_eq!(
1867 regional.arn("aws-us-gov", "us-gov-west-1"),
1868 "arn:aws-us-gov:ecr:us-gov-west-1:123456789012:repository/team/base"
1869 );
1870 assert_eq!(
1871 pinned.arn("aws", "us-east-1"),
1872 "arn:aws:ecr:eu-west-1:123456789012:repository/team/base"
1873 );
1874 }
1875
1876 #[test]
1879 fn a_uri_carrying_an_iam_wildcard_is_refused() {
1880 for uri in [
1881 "s3://acme/team-*/v1/bundle.zip",
1882 "s3://acme/sandbox-bundle/f00d/bundle?.zip",
1883 "s3://acme-*/sandbox-bundle/f00d/bundle.zip",
1884 ] {
1885 let error = parse_bundle_uri(uri).expect_err("a wildcard must be refused");
1886 assert!(error.contains("IAM wildcard"), "for {uri}: {error}");
1887 }
1888
1889 parse_bundle_uri("s3://acme/sandbox-bundle/f00d/bundle.zip")
1890 .expect("an ordinary key still parses");
1891 }
1892
1893 #[test]
1897 fn a_grantable_prefix_ends_above_the_segment_that_moves() {
1898 assert_eq!(
1899 stable_bundle_key_prefix("sandbox-bundle/f00dcafe/bundle.zip"),
1900 Some("sandbox-bundle")
1901 );
1902 assert_eq!(
1903 stable_bundle_key_prefix("artifacts/team-a/sandbox/f00dcafe/bundle.zip"),
1904 Some("artifacts/team-a/sandbox"),
1905 "a deeper key narrows the prefix, it never widens to the first segment"
1906 );
1907
1908 assert_eq!(stable_bundle_key_prefix("agents/bundle.zip"), None);
1911 assert_eq!(stable_bundle_key_prefix("bundle.zip"), None);
1912 }
1913
1914 fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
1915 Sandbox::new("agent-sbx".to_string())
1916 .code(SandboxCode::Image {
1917 image: "ubuntu".to_string(),
1918 bundled_from: None,
1919 })
1920 .limits(SandboxLimits {
1921 cpu: "1".to_string(),
1922 memory: "2Gi".to_string(),
1923 disk: "10Gi".to_string(),
1924 max_processes: None,
1925 })
1926 .egress(egress)
1927 .lifecycle(SandboxLifecyclePolicy {
1928 max_lifetime_seconds: None,
1929 idle_pause_seconds: None,
1930 })
1931 .preview_ports(preview_ports)
1932 .build()
1933 }
1934
1935 #[test]
1938 fn gcp_takes_internet_as_open_outbound_and_refuses_an_allowlist_policy() {
1939 sandbox_with(SandboxEgress::Internet, vec![])
1940 .validate_for_platform(Platform::Gcp)
1941 .unwrap();
1942 sandbox_with(SandboxEgress::None, vec![])
1943 .validate_for_platform(Platform::Gcp)
1944 .unwrap();
1945 for policy in [
1946 EgressPolicy::Allow {
1947 allow: vec!["api.example.com".into()],
1948 },
1949 EgressPolicy::Internet,
1950 ] {
1951 let mut declared = sandbox_with(SandboxEgress::Internet, vec![]);
1952 declared.default_policy = Some(policy);
1953 let refused = declared.validate_for_platform(Platform::Gcp).unwrap_err();
1954 assert!(
1955 refused
1956 .to_string()
1957 .contains("Google Cloud sandboxes have no outbound allowlist"),
1958 "{refused}"
1959 );
1960 }
1961 }
1962
1963 #[test]
1966 fn gcp_refuses_an_idle_pause_policy_at_plan_time_and_still_takes_a_lifetime() {
1967 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
1968 Sandbox::new("sbx".to_string())
1969 .code(SandboxCode::Image {
1970 image: "ubuntu".to_string(),
1971 bundled_from: None,
1972 })
1973 .egress(SandboxEgress::None)
1974 .lifecycle(lifecycle)
1975 .build()
1976 .validate_for_platform(Platform::Gcp)
1977 };
1978 let refused = with_policy(SandboxLifecyclePolicy {
1979 max_lifetime_seconds: None,
1980 idle_pause_seconds: Some(900),
1981 })
1982 .expect_err("no idle policy exists on GCP");
1983 assert_eq!(refused.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
1984 assert!(refused.message.contains("idle"), "{}", refused.message);
1985 with_policy(SandboxLifecyclePolicy {
1986 max_lifetime_seconds: Some(3600),
1987 idle_pause_seconds: None,
1988 })
1989 .expect("a lifetime is a TTL on GCP");
1990 }
1991
1992 #[test]
1993 fn gcp_accepts_preview_ports_but_not_the_agents_own() {
1994 sandbox_with(SandboxEgress::Deny, vec![8080, 8081, 8090])
1995 .validate_for_platform(Platform::Gcp)
1996 .expect("preview ports are served on GCP, as owner access");
1997 let error = sandbox_with(SandboxEgress::Deny, vec![8080, 8971])
1998 .validate_for_platform(Platform::Gcp)
1999 .expect_err("the agent's own port is not a workload port");
2000 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "{error}");
2001 assert!(error.to_string().contains("8971"), "{error}");
2002 sandbox_with(SandboxEgress::Deny, vec![])
2003 .validate_for_platform(Platform::Gcp)
2004 .expect("a sandbox without preview ports is unaffected");
2005 }
2006
2007 #[test]
2008 fn a_uri_without_a_token_is_carried_whole() {
2009 assert_eq!(
2010 parse_bundle_uri("s3://acme-artifacts-us-east-2/agents/bundle.zip"),
2011 Ok(BundleUri::Literal(
2012 "s3://acme-artifacts-us-east-2/agents/bundle.zip"
2013 ))
2014 );
2015 }
2016
2017 #[test]
2020 fn a_regional_uri_splits_either_side_of_the_token() {
2021 let BundleUri::Regional { before, after } =
2022 parse_bundle_uri("s3://acme-artifacts-{region}/agents/bundle.zip")
2023 .expect("the token is accepted in the bucket")
2024 else {
2025 panic!("a bucket-position token must split");
2026 };
2027
2028 assert_eq!(before, "s3://acme-artifacts-");
2029 assert_eq!(after, "/agents/bundle.zip");
2030 assert_eq!(
2031 format!("{before}us-east-2{after}"),
2032 "s3://acme-artifacts-us-east-2/agents/bundle.zip",
2033 "the halves must rejoin to the URI the vendor meant"
2034 );
2035 }
2036
2037 #[test]
2040 fn a_token_this_build_cannot_resolve_is_refused() {
2041 for uri in [
2042 "s3://acme-artifacts-{regio}/bundle.zip",
2043 "s3://acme-artifacts/{region}/bundle.zip",
2044 "s3://acme-artifacts-{region}-{region}/bundle.zip",
2045 "s3://acme-artifacts/bundle-{version}.zip",
2046 "s3://acme}-artifacts-{region}/bundle.zip",
2047 "s3://acme{-artifacts-{region}/bundle.zip",
2048 ] {
2049 assert!(
2050 parse_bundle_uri(uri).is_err(),
2051 "'{uri}' must be refused before it can reach an image build"
2052 );
2053 }
2054 }
2055
2056 #[test]
2057 fn resource_type_is_stable() {
2058 assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
2059 }
2060
2061 #[test]
2062 fn capability_sets_are_per_platform() {
2063 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2064 assert!(
2065 gcp.reconnect,
2066 "generation from the container boot id makes a sandbox reachable across processes"
2067 );
2068 assert!(gcp.preview, "preview is offered as owner access");
2069 assert!(gcp.enforced_limits);
2070
2071 let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
2072 assert!(azure.files, "every backend moves files");
2073 assert!(gcp.files);
2074 assert!(azure.domain_egress_rules);
2077 assert!(azure.egress_deny);
2078 assert!(azure.enforced_limits);
2081 assert!(azure.pause_resume);
2082 assert!(!azure.snapshot);
2084 assert!(
2085 azure.preview,
2086 "the in-sandbox agent issues a port-scoped capability"
2087 );
2088
2089 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2090 assert!(!aws.snapshot, "AWS has no user-callable sandbox snapshot");
2091 assert!(aws.pause_resume);
2092
2093 let k8s =
2094 SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
2095 assert!(
2096 k8s.preview,
2097 "an in-cluster caller previews through the agent route"
2098 );
2099 }
2100
2101 #[test]
2110 fn supervisor_isolation_is_per_platform() {
2111 let value = |platform| {
2112 SandboxCapabilities::for_platform(platform)
2113 .expect("supported")
2114 .supervisor_isolation
2115 };
2116
2117 assert!(
2118 value(Platform::Aws),
2119 "root agent setuids the command to 60000"
2120 );
2121 assert!(
2122 value(Platform::Local),
2123 "the supervisor is on the host, outside the container"
2124 );
2125 assert!(
2126 value(Platform::Kubernetes),
2127 "root boot splits the command off the supervisor"
2128 );
2129 assert!(!value(Platform::Azure), "no Alien process runs the command");
2130 assert!(
2131 !value(Platform::Gcp),
2132 "no separate supervisor identity runs the command"
2133 );
2134 }
2135
2136 #[test]
2140 fn supervisor_isolation_separates_aws_from_a_subprocess_backend() {
2141 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
2142 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2143
2144 assert_eq!(
2145 aws.supervisor_pid_namespace, gcp.supervisor_pid_namespace,
2146 "the older axis cannot tell them apart"
2147 );
2148 assert!(
2149 aws.supervisor_isolation,
2150 "AWS setuids the command off the supervisor"
2151 );
2152 assert!(
2153 !gcp.supervisor_isolation,
2154 "the command runs under no separate supervisor identity"
2155 );
2156 }
2157
2158 #[test]
2163 fn gcp_agent_platform_row_matches_measured_backend() {
2164 let row = SandboxCapabilities::gcp_agent_platform();
2165
2166 assert!(row.files, "agent file ops move over the sandbox envelope");
2167 assert!(
2168 row.reconnect,
2169 "generation is derived from the container boot id, so a sandbox is reachable across \
2170 processes"
2171 );
2172 assert!(
2173 row.preview,
2174 "preview is owner access: the edge credential is the caller's execute right"
2175 );
2176 assert!(
2177 row.pause_resume,
2178 "pause and resume keep memory, and a resume that finds a new container is an error"
2179 );
2180 assert!(
2181 !row.snapshot,
2182 "the create path never sends a snapshot, so none is reachable through the trait"
2183 );
2184 assert!(
2185 !row.domain_egress_rules,
2186 "VPC and DNS peering is not a hostname allowlist"
2187 );
2188 assert!(
2189 row.egress_deny,
2190 "a declared deny blocks TCP, the metadata server and DNS on the default placement"
2191 );
2192 assert!(
2193 row.enforced_limits,
2194 "ceilings are enforced, by terminating the sandbox on breach"
2195 );
2196 assert!(!row.process_limit, "no process-count ceiling is observed");
2197 assert!(row.sandbox_lifetime, "ttl maps to a sandbox expireTime");
2198 assert!(!row.supervisor_pid_namespace, "no PID-namespace isolation");
2199 assert!(
2200 !row.supervisor_isolation,
2201 "the command is not run under a separate supervisor identity"
2202 );
2203
2204 let live = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
2206 assert_eq!(
2207 live, row,
2208 "the Platform::Gcp arm is the Agent Platform capability row"
2209 );
2210 }
2211
2212 #[test]
2213 fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
2214 let error = SandboxCapabilities::for_platform(Platform::Machines)
2215 .expect_err("Machines has no sandbox backend");
2216 assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
2217 }
2218
2219 #[test]
2220 fn unsupported_capability_names_platform_and_capability() {
2221 let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
2222 let error = capabilities
2223 .require(SandboxCapability::Snapshot, Platform::Gcp)
2224 .expect_err("GCP has no snapshot");
2225
2226 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2227 let rendered = error.to_string();
2228 assert!(
2229 rendered.contains("snapshot"),
2230 "names the capability: {rendered}"
2231 );
2232 assert!(rendered.contains("gcp"), "names the platform: {rendered}");
2233 }
2234
2235 #[test]
2239 fn a_hostname_allowlist_is_refused_everywhere_it_would_be_approximated() {
2240 let sandbox = sandbox_with(
2241 SandboxEgress::AllowDomains {
2242 domains: vec!["example.com".to_string()],
2243 },
2244 vec![],
2245 );
2246
2247 for platform in [
2248 Platform::Aws,
2249 Platform::Gcp,
2250 Platform::Kubernetes,
2251 Platform::Local,
2252 ] {
2253 let error = sandbox
2254 .validate_for_platform(platform)
2255 .expect_err("only Azure expresses a hostname allowlist");
2256 assert_eq!(
2257 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2258 "on {platform:?}"
2259 );
2260 }
2261
2262 assert!(
2263 SandboxCapabilities::for_platform(Platform::Azure)
2264 .expect("supported")
2265 .domain_egress_rules,
2266 "Azure's egress policy matches on host pattern"
2267 );
2268 }
2269
2270 #[test]
2273 fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
2274 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2275
2276 assert!(
2279 SandboxCapabilities::for_platform(Platform::Gcp)
2280 .expect("supported")
2281 .egress_deny
2282 );
2283
2284 for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
2285 sandbox
2286 .validate_for_platform(platform)
2287 .expect("deny is enforced here");
2288 }
2289
2290 let egress_only = Sandbox::new("sbx".to_string())
2292 .code(SandboxCode::Image {
2293 image: "alpine".to_string(),
2294 bundled_from: None,
2295 })
2296 .egress(SandboxEgress::None)
2297 .lifecycle(SandboxLifecyclePolicy {
2298 max_lifetime_seconds: None,
2299 idle_pause_seconds: None,
2300 })
2301 .build();
2302
2303 egress_only
2304 .validate_for_platform(Platform::Azure)
2305 .expect("Azure creates the sandbox under a Deny policy with full inspection");
2306 }
2307
2308 #[test]
2312 fn a_sandbox_declaring_no_ceilings_takes_the_platforms_own() {
2313 let undeclared = Sandbox::new("sbx".to_string())
2314 .code(SandboxCode::Image {
2315 image: "alpine".to_string(),
2316 bundled_from: None,
2317 })
2318 .egress(SandboxEgress::None)
2319 .lifecycle(SandboxLifecyclePolicy {
2320 max_lifetime_seconds: None,
2321 idle_pause_seconds: None,
2322 })
2323 .build();
2324
2325 undeclared
2326 .validate_for_platform(Platform::Azure)
2327 .expect("a sandbox naming no ceilings takes the platform's own");
2328
2329 assert_eq!(undeclared.resolved_limits().cpu, "1");
2331 }
2332
2333 #[test]
2337 fn azure_sizes_follow_the_rule_the_data_plane_states() {
2338 let sized = |cpu: &str, memory: &str, disk: &str| {
2339 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2340 let limits = sandbox
2341 .limits
2342 .as_mut()
2343 .expect("the fixture declares limits");
2344 limits.cpu = cpu.to_string();
2345 limits.memory = memory.to_string();
2346 limits.disk = disk.to_string();
2347 sandbox.validate_for_platform(Platform::Azure)
2348 };
2349
2350 sized("250m", "512Mi", "5120Mi").expect("the smallest step the data plane accepts");
2351 sized("4000m", "8192Mi", "40960Mi").expect("cpu, memory and disk are all honoured");
2352 sized("16000m", "32Gi", "320Gi").expect("the top of the range");
2353
2354 let off_step = sized("333m", "512Mi", "5120Mi").expect_err("333m is not a step of 250m");
2356 assert_eq!(off_step.code, "SANDBOX_LIMIT_INVALID", "{off_step}");
2357 assert!(off_step.to_string().contains("cpu"), "{off_step}");
2358
2359 let too_big = sized("32000m", "64Gi", "640Gi").expect_err("32 cores is over the ceiling");
2360 assert_eq!(too_big.code, "SANDBOX_LIMIT_INVALID", "{too_big}");
2361
2362 sized("1000m", "2Gi", "20Gi").expect("2Gi is exactly one core's worth");
2365 let over_memory = sized("250m", "2Gi", "5120Mi").expect_err("2Gi needs a full core");
2366 assert_eq!(over_memory.code, "SANDBOX_LIMIT_INVALID", "{over_memory}");
2367 assert!(over_memory.to_string().contains("memory"), "{over_memory}");
2368
2369 let over_disk = sized("250m", "512Mi", "20Gi").expect_err("20Gi needs a full core");
2370 assert!(over_disk.to_string().contains("disk"), "{over_disk}");
2371 }
2372
2373 #[test]
2376 fn kubernetes_root_image_needs_gateway_or_no_egress() {
2377 let root = |egress| {
2378 let mut sandbox = sandbox_with(egress, vec![]);
2379 sandbox.image_user = Some(0);
2380 sandbox
2381 };
2382 for egress in [SandboxEgress::Internet, SandboxEgress::None] {
2383 root(egress)
2384 .validate_for_platform(Platform::Kubernetes)
2385 .expect("root boot is allowed with an external egress boundary");
2386 }
2387 for egress in [
2388 SandboxEgress::Allow,
2389 SandboxEgress::AllowDomains {
2390 domains: vec!["example.com".to_string()],
2391 },
2392 ] {
2393 let error = root(egress)
2394 .validate_for_platform(Platform::Kubernetes)
2395 .expect_err("a root image under unenforced egress is refused");
2396 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2397 assert!(error.to_string().contains("root image USER"), "{error}");
2398 }
2399 root(SandboxEgress::Internet)
2400 .validate_for_platform(Platform::Local)
2401 .expect_err("Local still refuses a root image");
2402 }
2403
2404 #[test]
2405 fn preview_ports_require_the_preview_capability() {
2406 let sandbox = sandbox_with(SandboxEgress::None, vec![8080]);
2407
2408 sandbox
2409 .validate_for_platform(Platform::Aws)
2410 .expect("AWS mints a port-scoped JWE");
2411
2412 sandbox
2413 .validate_for_platform(Platform::Kubernetes)
2414 .expect("Kubernetes serves preview to in-cluster callers through the agent");
2415
2416 sandbox
2417 .validate_for_platform(Platform::Gcp)
2418 .expect("GCP serves preview to callers that already hold execute");
2419 }
2420
2421 #[test]
2423 fn azure_preview_needs_an_image_that_carries_the_agent() {
2424 let catalog = sandbox_with(SandboxEgress::None, vec![8080]);
2425 let error = catalog
2426 .validate_for_platform(Platform::Azure)
2427 .expect_err("a catalog image has no agent to issue a capability");
2428 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2429
2430 let mut registry = sandbox_with(SandboxEgress::None, vec![8080]);
2431 registry.code = SandboxCode::Image {
2432 image: "registry.example.com/workload/sandbox:1".to_string(),
2433 bundled_from: None,
2434 };
2435 registry
2436 .validate_for_platform(Platform::Azure)
2437 .expect("a registry image is built with the agent");
2438 }
2439
2440 #[test]
2444 fn a_private_base_image_is_refused_off_aws() {
2445 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2446 sandbox.code = SandboxCode::Image {
2447 image: "s3://acme-artifacts/agents/bundle.zip".to_string(),
2448 bundled_from: None,
2449 };
2450 sandbox.private_base_image =
2451 Some("123456789012.dkr.ecr.{region}.amazonaws.com/acme:tag".to_string());
2452
2453 sandbox
2454 .validate_for_platform(Platform::Aws)
2455 .expect("AWS builds its image from a bundle, so a base image sits behind code.image");
2456
2457 for platform in [
2458 Platform::Gcp,
2459 Platform::Azure,
2460 Platform::Kubernetes,
2461 Platform::Local,
2462 ] {
2463 let error = sandbox
2464 .validate_for_platform(platform)
2465 .expect_err("a backend that builds no image must refuse a base image for one");
2466 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2467 assert!(
2468 error.to_string().contains("privateBaseImage"),
2469 "the refusal must name the field the user declared: {error}"
2470 );
2471 }
2472 }
2473
2474 #[test]
2478 fn gcp_refuses_a_disk_above_its_cap_and_accepts_the_cap() {
2479 let with_disk = |disk: &str| {
2480 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2481 sandbox
2482 .limits
2483 .as_mut()
2484 .expect("the fixture declares limits")
2485 .disk = disk.to_string();
2486 sandbox
2487 };
2488
2489 let error = with_disk("20Gi")
2490 .validate_for_platform(Platform::Gcp)
2491 .expect_err("20Gi is above the Agent Platform cap");
2492 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2493 let rendered = error.to_string();
2494 assert!(rendered.contains("disk"), "names the field: {rendered}");
2495 assert!(rendered.contains("10Gi"), "names the cap: {rendered}");
2496
2497 with_disk("10Gi")
2498 .validate_for_platform(Platform::Gcp)
2499 .expect("the cap itself is allowed");
2500 with_disk("10240Mi")
2501 .validate_for_platform(Platform::Gcp)
2502 .expect("the cap in MiB is allowed");
2503 for over in ["10240.5Mi", "10241Mi", "10.0000001Gi"] {
2504 with_disk(over)
2505 .validate_for_platform(Platform::Gcp)
2506 .expect_err(&format!("{over} is above the cap and must not round down"));
2507 }
2508 with_disk("8Gi")
2509 .validate_for_platform(Platform::Gcp)
2510 .expect("the default disk is allowed");
2511 with_disk("20Gi")
2512 .validate_for_platform(Platform::Kubernetes)
2513 .expect("the cap is Agent Platform's, not every backend's");
2514 }
2515
2516 #[test]
2517 fn gcp_accepts_a_sandbox_declaring_enforced_limits() {
2518 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2519 sandbox
2520 .limits
2521 .as_mut()
2522 .expect("the fixture declares limits")
2523 .disk = "10Gi".to_string();
2524 sandbox
2525 .validate_for_platform(Platform::Gcp)
2526 .expect("Agent Platform enforces declared ceilings, by terminating on breach");
2527 }
2528
2529 #[test]
2530 fn invalid_quantities_are_rejected_with_the_offending_field() {
2531 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2532 sandbox
2533 .limits
2534 .as_mut()
2535 .expect("the fixture declares limits")
2536 .memory = "2Gb".to_string();
2537
2538 let error = sandbox
2539 .validate_for_platform(Platform::Aws)
2540 .expect_err("Gb is not a valid suffix");
2541 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2542 assert!(error.to_string().contains("memory"));
2543
2544 sandbox
2545 .limits
2546 .as_mut()
2547 .expect("the fixture declares limits")
2548 .memory = "2Gi".to_string();
2549 sandbox
2550 .limits
2551 .as_mut()
2552 .expect("the fixture declares limits")
2553 .cpu = "0".to_string();
2554 let error = sandbox
2555 .validate_for_platform(Platform::Aws)
2556 .expect_err("zero cpu is not a ceiling");
2557 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2558 }
2559
2560 #[test]
2561 fn zero_max_processes_is_rejected() {
2562 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2563 sandbox
2564 .limits
2565 .as_mut()
2566 .expect("the fixture declares limits")
2567 .max_processes = Some(0);
2568
2569 let error = sandbox
2570 .validate_for_platform(Platform::Local)
2571 .expect_err("a sandbox must be able to run at least one process");
2572 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2573 assert!(error.to_string().contains("maxProcesses"));
2574 }
2575
2576 #[test]
2580 fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
2581 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2582 sandbox
2583 .limits
2584 .as_mut()
2585 .expect("the fixture declares limits")
2586 .max_processes = Some(256);
2587
2588 sandbox
2589 .validate_for_platform(Platform::Local)
2590 .expect("Docker takes a pids limit");
2591
2592 for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
2593 let error = sandbox
2594 .validate_for_platform(platform)
2595 .expect_err("a process ceiling nothing applies must be refused");
2596 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2597 }
2598 }
2599
2600 #[test]
2605 fn a_lifetime_aws_would_reject_is_refused_while_planning() {
2606 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2607 let mut without_limits = with_limits.clone();
2608 without_limits.limits = None;
2609
2610 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2611 for seconds in [28_801, 30_000, 100_000] {
2612 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2613 let error = sandbox
2614 .validate_for_platform(Platform::Aws)
2615 .expect_err("a lifetime above what AWS runs is refused");
2616 assert_eq!(
2617 error.code, "SANDBOX_LIMIT_INVALID",
2618 "{seconds}s {declared} limits"
2619 );
2620
2621 sandbox
2623 .validate_for_platform(Platform::Kubernetes)
2624 .expect("Kubernetes takes an activeDeadlineSeconds above 28,800");
2625 }
2626
2627 sandbox.lifecycle.max_lifetime_seconds = Some(28_800);
2628 sandbox
2629 .validate_for_platform(Platform::Aws)
2630 .expect("the ceiling itself is allowed");
2631 }
2632 }
2633
2634 #[test]
2638 fn a_zero_lifetime_is_refused_while_planning() {
2639 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2640 let mut without_limits = with_limits.clone();
2641 without_limits.limits = None;
2642
2643 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2644 sandbox.lifecycle.max_lifetime_seconds = Some(0);
2645 for platform in [
2646 Platform::Aws,
2647 Platform::Kubernetes,
2648 Platform::Gcp,
2649 Platform::Azure,
2650 ] {
2651 let error = sandbox
2652 .validate_for_platform(platform)
2653 .expect_err("a zero lifetime is refused");
2654 assert_eq!(
2655 error.code, "SANDBOX_LIMIT_INVALID",
2656 "{platform} {declared} limits"
2657 );
2658 assert!(
2659 error.to_string().contains("maxLifetimeSeconds"),
2660 "{platform} {declared} limits"
2661 );
2662 }
2663
2664 for platform in [Platform::Local] {
2666 let error = sandbox
2667 .validate_for_platform(platform)
2668 .expect_err("a lifetime is refused where nothing applies it");
2669 assert_eq!(
2670 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2671 "{platform} {declared} limits"
2672 );
2673 }
2674
2675 sandbox.lifecycle.max_lifetime_seconds = Some(1);
2676 sandbox
2677 .validate_for_platform(Platform::Kubernetes)
2678 .expect("one second is the API server's floor");
2679 }
2680 }
2681
2682 #[test]
2686 fn a_lifetime_kubernetes_would_reject_is_refused_while_planning() {
2687 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2688 let mut without_limits = with_limits.clone();
2689 without_limits.limits = None;
2690
2691 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2692 for seconds in [2_147_483_648, u32::MAX] {
2693 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2694 let error = sandbox
2695 .validate_for_platform(Platform::Kubernetes)
2696 .expect_err("a lifetime above what the API server takes is refused");
2697 assert_eq!(
2698 error.code, "SANDBOX_LIMIT_INVALID",
2699 "{seconds}s {declared} limits"
2700 );
2701 assert!(
2702 error.to_string().contains("maxLifetimeSeconds"),
2703 "{seconds}s {declared} limits"
2704 );
2705 }
2706
2707 sandbox.lifecycle.max_lifetime_seconds = Some(2_147_483_647);
2708 sandbox
2709 .validate_for_platform(Platform::Kubernetes)
2710 .expect("the ceiling itself is allowed");
2711 }
2712 }
2713
2714 #[test]
2717 fn an_image_azure_cannot_pull_is_refused_while_planning() {
2718 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2719 sandbox.limits = None;
2722
2723 for image in ["ubuntu@sha256:abc", "", " ", "ubuntu latest", "ubuntu?x"] {
2725 sandbox.code = SandboxCode::Image {
2726 image: image.to_string(),
2727 bundled_from: None,
2728 };
2729 let error = sandbox
2730 .validate_for_platform(Platform::Azure)
2731 .expect_err("an image Azure has nowhere to put is refused");
2732 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "image '{image}'");
2733 }
2734
2735 for image in ["ubuntu", "ubuntu-22.04", "debian_slim"] {
2736 sandbox.code = SandboxCode::Image {
2737 image: image.to_string(),
2738 bundled_from: None,
2739 };
2740 sandbox
2741 .validate_for_platform(Platform::Azure)
2742 .unwrap_or_else(|error| panic!("'{image}' is a catalog name: {error}"));
2743 }
2744
2745 for image in [
2746 "ubuntu:24.04",
2747 "ghcr.io/myorg/sandbox:latest",
2748 "docker.io/library/python:3.14-slim",
2749 "localhost:5000/team/agent@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d",
2750 ] {
2751 sandbox.code = SandboxCode::Image {
2752 image: image.to_string(),
2753 bundled_from: None,
2754 };
2755 sandbox
2756 .validate_for_platform(Platform::Azure)
2757 .unwrap_or_else(|error| panic!("'{image}' is a registry image: {error}"));
2758 }
2759
2760 sandbox.code = SandboxCode::Image {
2762 image: " ubuntu ".to_string(),
2763 bundled_from: None,
2764 };
2765 assert_eq!(
2766 sandbox
2767 .azure_image()
2768 .expect("a padded name is still a name"),
2769 AzureSandboxImage::Catalog("ubuntu")
2770 );
2771 }
2772
2773 #[test]
2777 fn every_value_the_catalog_allowlist_accepted_is_still_a_catalog_name() {
2778 const ALPHABET: &[u8] =
2779 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
2780
2781 let assert_catalog = |value: &str| {
2782 assert_eq!(
2783 classify_azure_sandbox_image(value),
2784 Some(AzureSandboxImage::Catalog(value.trim())),
2785 "'{value}'"
2786 );
2787 };
2788
2789 for a in ALPHABET {
2790 assert_catalog(&String::from_utf8(vec![*a]).unwrap());
2791 for b in ALPHABET {
2792 assert_catalog(&String::from_utf8(vec![*a, *b]).unwrap());
2793 for c in ALPHABET {
2794 assert_catalog(&String::from_utf8(vec![*a, *b, *c]).unwrap());
2795 }
2796 }
2797 }
2798
2799 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
2800 let mut next = || {
2801 state ^= state << 13;
2802 state ^= state >> 7;
2803 state ^= state << 17;
2804 state
2805 };
2806 for _ in 0..20_000 {
2807 let len = 4 + (next() % 60) as usize;
2808 let mut value: String = (0..len)
2809 .map(|_| ALPHABET[(next() % ALPHABET.len() as u64) as usize] as char)
2810 .collect();
2811 if next() % 4 == 0 {
2812 value = format!(" {value}\t");
2813 }
2814 assert_catalog(&value);
2815 }
2816 }
2817
2818 #[test]
2821 fn the_disk_image_label_is_stable_and_label_safe() {
2822 let label = azure_disk_image_label("docker.io/library/python:3.14-slim");
2823 assert_eq!(
2824 label,
2825 azure_disk_image_label(" docker.io/library/python:3.14-slim ")
2826 );
2827 assert_ne!(
2828 label,
2829 azure_disk_image_label("docker.io/library/python:3.13-slim")
2830 );
2831 assert_eq!(label.len(), 32);
2832 assert!(label.chars().all(|c| c.is_ascii_hexdigit()), "{label}");
2833 }
2834
2835 #[test]
2839 fn a_sandbox_deadline_is_accepted_only_where_the_platform_applies_it() {
2840 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2841 sandbox.lifecycle.max_lifetime_seconds = Some(3600);
2842
2843 sandbox
2844 .validate_for_platform(Platform::Kubernetes)
2845 .expect("the kubelet enforces activeDeadlineSeconds");
2846 sandbox
2847 .validate_for_platform(Platform::Aws)
2848 .expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
2849
2850 sandbox.validate_for_platform(Platform::Azure).expect(
2851 "the binding stamps a deadline label and the controller's reaper deletes by it",
2852 );
2853
2854 for platform in [Platform::Local] {
2855 let error = sandbox
2856 .validate_for_platform(platform)
2857 .expect_err("a deadline nothing applies must be refused");
2858 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2859 }
2860 }
2861
2862 #[test]
2866 fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
2867 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2868 let tier = sandbox
2869 .microvm_tier()
2870 .expect("2Gi/1cpu/20Gi is satisfiable");
2871
2872 assert_eq!(
2873 tier.peak_memory_mib, 2048,
2874 "the peak is the declared ceiling"
2875 );
2876 assert_eq!(
2877 tier.baseline_memory_mib, 512,
2878 "which is a quarter of it as the baseline"
2879 );
2880 assert!(tier.max_disk_mib <= 20 * 1024);
2881 }
2882
2883 #[test]
2887 fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
2888 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2889 {
2890 let limits = sandbox
2891 .limits
2892 .as_mut()
2893 .expect("the fixture declares limits");
2894 limits.cpu = "1".to_string();
2895 limits.memory = "8Gi".to_string();
2896 }
2897
2898 let error = sandbox
2899 .microvm_tier()
2900 .expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
2901 assert!(
2902 error.to_string().contains("4 vCPU"),
2903 "the refusal must say what the memory ceiling implies: {error}"
2904 );
2905
2906 sandbox
2907 .limits
2908 .as_mut()
2909 .expect("the fixture declares limits")
2910 .cpu = "4".to_string();
2911 let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
2912 assert_eq!(tier.peak_memory_mib, 8192);
2913 }
2914
2915 #[test]
2918 fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
2919 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2920 sandbox
2921 .limits
2922 .as_mut()
2923 .expect("the fixture declares limits")
2924 .memory = "1Gi".to_string();
2925
2926 let error = sandbox
2927 .validate_for_platform(Platform::Aws)
2928 .expect_err("no MicroVM size peaks at or below 1Gi");
2929 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2930 assert!(
2931 error.to_string().contains("2Gi"),
2932 "the refusal must say what the smallest holdable ceiling is: {error}"
2933 );
2934 }
2935
2936 #[test]
2939 fn source_code_is_refused_where_no_backend_builds_it() {
2940 let sandbox = Sandbox::new("agent".to_string())
2941 .code(SandboxCode::Source {
2942 src: "./sandbox".to_string(),
2943 toolchain: ToolchainConfig::Docker {
2944 dockerfile: None,
2945 build_args: None,
2946 target: None,
2947 },
2948 })
2949 .egress(SandboxEgress::None)
2950 .lifecycle(SandboxLifecyclePolicy {
2951 max_lifetime_seconds: None,
2952 idle_pause_seconds: None,
2953 })
2954 .build();
2955
2956 sandbox
2957 .validate_for_platform(Platform::Aws)
2958 .expect("an AWS sandbox base image is built by `alien build`");
2959 sandbox
2960 .validate_for_platform(Platform::Azure)
2961 .expect("an Azure sandbox base image is built by `alien build`");
2962 sandbox
2963 .validate_for_platform(Platform::Gcp)
2964 .expect("a GCP sandbox base image is built by `alien build`");
2965 sandbox
2966 .validate_for_platform(Platform::Kubernetes)
2967 .expect("a Kubernetes sandbox base image is built by `alien build`");
2968
2969 for platform in [Platform::Local] {
2970 let error = sandbox
2971 .validate_for_platform(platform)
2972 .expect_err("no backend builds a sandbox image from source here");
2973 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2974 assert!(
2975 error.to_string().contains("code.image"),
2976 "the refusal must say what to write instead: {error}"
2977 );
2978 assert!(
2979 error.to_string().contains(&platform.to_string()),
2980 "the refusal must name the platform that cannot build it: {error}"
2981 );
2982 }
2983 }
2984
2985 #[test]
2988 fn every_accepted_unit_converts_rather_than_falling_back() {
2989 assert_eq!(quantity_mib("2Gi"), Some(2048));
2990 assert_eq!(quantity_mib("512Mi"), Some(512));
2991 assert_eq!(quantity_mib("4G"), Some(3814));
2992 assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
2993 assert_eq!(millicores("1"), Some(1000));
2994 assert_eq!(millicores("500m"), Some(500));
2995 }
2996
2997 #[test]
2998 fn privileged_supervisor_fixes_identity_and_requires_an_enforceable_backend() {
2999 let mut sandbox = sandbox_with(
3000 SandboxEgress::AllowDomains {
3001 domains: vec!["example.com".to_string()],
3002 },
3003 vec![],
3004 );
3005 sandbox.privileged_supervisor = Some(SandboxPrivilegedSupervisor { command_uid: 60001 });
3006 sandbox
3007 .validate_for_platform(Platform::Aws)
3008 .expect("AWS can enforce the policy in the agent");
3009 assert_eq!(sandbox.cloud_egress(), &SandboxEgress::Allow);
3010 assert_eq!(
3011 sandbox.supervisor_environment()["ALIEN_SANDBOX_EXPECTED_EXEC_UID"],
3012 "60001"
3013 );
3014 for platform in [
3015 Platform::Local,
3016 Platform::Kubernetes,
3017 Platform::Azure,
3018 Platform::Gcp,
3019 ] {
3020 let error = sandbox
3021 .validate_for_platform(platform)
3022 .expect_err("cannot grant a privilege boundary the backend lacks");
3023 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
3024 assert!(error.message.contains("privilegedSupervisor"));
3025 }
3026 for uid in [0, u32::MAX] {
3027 sandbox.privileged_supervisor.as_mut().unwrap().command_uid = uid;
3028 let error = sandbox
3029 .validate_for_platform(Platform::Aws)
3030 .expect_err("invalid uid must fail at plan time");
3031 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3032 }
3033 }
3034
3035 #[test]
3036 fn unknown_fields_are_rejected() {
3037 let json = r#"{
3038 "id": "sbx",
3039 "code": {"type": "image", "image": "ubuntu:24.04"},
3040 "limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
3041 "egress": {"mode": "deny"},
3042 "lifecycle": {},
3043 "unexpected": true
3044 }"#;
3045
3046 serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
3047 }
3048
3049 #[test]
3050 fn serialization_roundtrips() {
3051 let sandbox = sandbox_with(
3052 SandboxEgress::AllowDomains {
3053 domains: vec!["example.com".to_string()],
3054 },
3055 vec![8080, 9090],
3056 );
3057
3058 let json = serde_json::to_string(&sandbox).expect("serializes");
3059 let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
3060 assert_eq!(sandbox, restored);
3061 }
3062
3063 #[test]
3064 fn id_is_immutable_across_updates() {
3065 let original = sandbox_with(SandboxEgress::None, vec![]);
3066 let renamed = Sandbox::new("other".to_string())
3067 .code(SandboxCode::Image {
3068 image: "ubuntu".to_string(),
3069 bundled_from: None,
3070 })
3071 .limits(
3072 original
3073 .limits
3074 .clone()
3075 .expect("the fixture declares limits"),
3076 )
3077 .egress(SandboxEgress::None)
3078 .lifecycle(SandboxLifecyclePolicy {
3079 max_lifetime_seconds: None,
3080 idle_pause_seconds: None,
3081 })
3082 .build();
3083
3084 original
3085 .validate_update(&original.clone())
3086 .expect("an unchanged config is a valid update");
3087 original
3088 .validate_update(&renamed)
3089 .expect_err("renaming a sandbox is not an update");
3090 }
3091
3092 #[test]
3096 fn azure_takes_an_idle_policy_and_a_lifetime_ceiling() {
3097 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
3098 Sandbox::new("sbx".to_string())
3099 .code(SandboxCode::Image {
3100 image: "ubuntu".to_string(),
3101 bundled_from: None,
3102 })
3103 .egress(SandboxEgress::Allow)
3104 .lifecycle(lifecycle)
3105 .build()
3106 .validate_for_platform(Platform::Azure)
3107 };
3108
3109 with_policy(SandboxLifecyclePolicy {
3110 max_lifetime_seconds: None,
3111 idle_pause_seconds: Some(900),
3112 })
3113 .expect("Azure pauses a sandbox on idle");
3114
3115 with_policy(SandboxLifecyclePolicy {
3116 max_lifetime_seconds: Some(3600),
3117 idle_pause_seconds: None,
3118 })
3119 .expect("the reaper enforces a wall-clock ceiling");
3120 }
3121
3122 #[test]
3128 fn an_allowlist_with_no_domains_is_refused() {
3129 let declared = |domains: Vec<String>| {
3130 Sandbox::new("sbx".to_string())
3131 .code(SandboxCode::Image {
3132 image: "ubuntu".to_string(),
3133 bundled_from: None,
3134 })
3135 .egress(SandboxEgress::AllowDomains { domains })
3136 .lifecycle(SandboxLifecyclePolicy {
3137 max_lifetime_seconds: None,
3138 idle_pause_seconds: None,
3139 })
3140 .build()
3141 .validate_for_platform(Platform::Azure)
3142 };
3143
3144 let error = declared(vec![]).expect_err("an empty allowlist must be refused");
3145 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
3146
3147 declared(vec!["api.example.com".to_string()])
3148 .expect("a named domain is what an allowlist is for");
3149 }
3150
3151 #[test]
3154 fn internet_access_switch_maps_only_the_two_expressible_modes() {
3155 assert_eq!(SandboxEgress::Allow.internet_access_switch(), Some(true));
3156 assert_eq!(SandboxEgress::None.internet_access_switch(), Some(false));
3157 assert_eq!(
3158 SandboxEgress::AllowDomains {
3159 domains: vec!["api.example.com".to_string()]
3160 }
3161 .internet_access_switch(),
3162 None,
3163 "a host list has no boolean and must not be approximated"
3164 );
3165 }
3166
3167 #[test]
3171 fn stack_state_written_before_the_lifecycle_rename_still_reads() {
3172 let stored: crate::StackResourceState = serde_json::from_value(serde_json::json!({
3173 "type": "sandbox",
3174 "config": {
3175 "id": "sandbox",
3176 "code": {
3177 "type": "image",
3178 "image": "s3://example-bundles/analysis/v1/bundle.zip"
3179 },
3180 "type": "sandbox",
3181 "egress": { "mode": "allow" },
3182 "session": { "maxLifetimeSeconds": 28800, "idleSuspendSeconds": 600 }
3183 },
3184 "status": "running",
3185 "outputs": {
3186 "type": "sandbox",
3187 "identifier": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox",
3188 "parentName": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox"
3189 },
3190 "lifecycle": "frozen",
3191 "dependencies": [
3192 { "id": "management", "type": "remote-stack-management" },
3193 { "id": "access", "type": "resource-access" }
3194 ],
3195 "controllerPlatform": "aws"
3196 }))
3197 .expect("a stack state written before the rename must still deserialize");
3198
3199 let expected = Sandbox::new("sandbox".to_string())
3200 .code(SandboxCode::Image {
3201 image: "s3://example-bundles/analysis/v1/bundle.zip".to_string(),
3202 bundled_from: None,
3203 })
3204 .egress(SandboxEgress::Allow)
3205 .lifecycle(SandboxLifecyclePolicy {
3206 max_lifetime_seconds: Some(28_800),
3207 idle_pause_seconds: Some(600),
3208 })
3209 .build();
3210 assert_eq!(stored.config.downcast_ref::<Sandbox>(), Some(&expected));
3211
3212 let rewritten = serde_json::to_value(&stored.config).expect("the sandbox serializes");
3213 assert_eq!(
3214 rewritten["lifecycle"],
3215 serde_json::json!({ "maxLifetimeSeconds": 28800, "idlePauseSeconds": 600 }),
3216 "the next write stores the current names"
3217 );
3218 assert!(rewritten.get("session").is_none());
3219 }
3220}
3221
3222#[cfg(test)]
3223mod label_format_tests {
3224 use super::*;
3225
3226 #[test]
3227 fn request_keys_are_bounded_and_safe() {
3228 for good in ["a", "A-z_9", &"x".repeat(64)] {
3229 assert!(is_valid_request_key(good), "{good}");
3230 }
3231 for bad in ["", "a b", "a/b", "a.b", "é", &"x".repeat(65)] {
3232 assert!(!is_valid_request_key(bad), "{bad}");
3233 }
3234 }
3235
3236 #[test]
3237 fn expiry_is_a_positive_integer() {
3238 assert!(is_valid_sandbox_expiry("1700000000000"));
3239 for bad in ["", "0", "-1", "1.5", "never", "+5 "] {
3240 assert!(!is_valid_sandbox_expiry(bad), "{bad}");
3241 }
3242 }
3243}