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