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 AZURE_CPU_STEP_MILLICORES: i64 = 250;
108const AZURE_MAX_CPU_MILLICORES: i64 = 16_000;
109const AZURE_MEMORY_MIB_PER_CORE: i64 = 2 * 1024;
110const AZURE_DISK_MIB_PER_CORE: i64 = 20 * 1024;
111
112const MICROVM_TIERS: &[MicrovmTier] = &[
113 MicrovmTier {
114 baseline_memory_mib: 512,
115 peak_memory_mib: 2048,
116 peak_vcpu: 1,
117 max_disk_mib: 8192,
118 },
119 MicrovmTier {
120 baseline_memory_mib: 1024,
121 peak_memory_mib: 4096,
122 peak_vcpu: 2,
123 max_disk_mib: 8192,
124 },
125 MicrovmTier {
126 baseline_memory_mib: 2048,
127 peak_memory_mib: 8192,
128 peak_vcpu: 4,
129 max_disk_mib: 8192,
130 },
131 MicrovmTier {
132 baseline_memory_mib: 4096,
133 peak_memory_mib: 16384,
134 peak_vcpu: 8,
135 max_disk_mib: 16384,
136 },
137 MicrovmTier {
138 baseline_memory_mib: 8192,
139 peak_memory_mib: 32768,
140 peak_vcpu: 16,
141 max_disk_mib: 32768,
142 },
143];
144
145pub use super::sandbox_policy::{is_public_ipv4, EgressPolicy};
146
147#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum SandboxEgress {
150 None,
151 Internet,
152 Allow,
154 AllowDomains {
156 domains: Vec<String>,
157 },
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
162#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
163#[serde(tag = "mode", rename_all = "camelCase", deny_unknown_fields)]
164pub enum LegacySandboxEgress {
165 Deny,
167 Allow,
170 AllowDomains { domains: Vec<String> },
173}
174
175#[derive(Serialize, Deserialize)]
176#[serde(rename_all = "camelCase")]
177enum SandboxEgressMode {
178 None,
179 Internet,
180}
181
182#[derive(Serialize, Deserialize)]
183#[serde(untagged)]
184enum SandboxEgressInput {
185 Mode(SandboxEgressMode),
186 Legacy(LegacySandboxEgress),
187}
188
189impl Serialize for SandboxEgress {
190 fn serialize<S: serde::Serializer>(
191 &self,
192 serializer: S,
193 ) -> std::result::Result<S::Ok, S::Error> {
194 match self {
195 Self::None => serializer.serialize_str("none"),
196 Self::Internet => serializer.serialize_str("internet"),
197 Self::Allow => LegacySandboxEgress::Allow.serialize(serializer),
198 Self::AllowDomains { domains } => LegacySandboxEgress::AllowDomains {
199 domains: domains.clone(),
200 }
201 .serialize(serializer),
202 }
203 }
204}
205
206impl<'de> Deserialize<'de> for SandboxEgress {
207 fn deserialize<D: serde::Deserializer<'de>>(
208 deserializer: D,
209 ) -> std::result::Result<Self, D::Error> {
210 Ok(match SandboxEgressInput::deserialize(deserializer)? {
211 SandboxEgressInput::Mode(SandboxEgressMode::None)
212 | SandboxEgressInput::Legacy(LegacySandboxEgress::Deny) => Self::None,
213 SandboxEgressInput::Mode(SandboxEgressMode::Internet) => Self::Internet,
214 SandboxEgressInput::Legacy(LegacySandboxEgress::Allow) => Self::Allow,
215 SandboxEgressInput::Legacy(LegacySandboxEgress::AllowDomains { domains }) => {
216 Self::AllowDomains { domains }
217 }
218 })
219 }
220}
221
222#[cfg(feature = "openapi")]
223impl utoipa::PartialSchema for SandboxEgress {
224 fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
225 use utoipa::openapi::schema::{ObjectBuilder, OneOfBuilder, Type};
226 OneOfBuilder::new()
227 .item(
228 ObjectBuilder::new()
229 .schema_type(Type::String)
230 .enum_values(Some(["none", "internet"])),
231 )
232 .item(LegacySandboxEgress::schema())
233 .into()
234 }
235}
236#[cfg(feature = "openapi")]
237impl utoipa::ToSchema for SandboxEgress {}
238
239impl SandboxEgress {
240 #[allow(non_upper_case_globals)]
242 #[deprecated(note = "use SandboxEgress::None")]
243 pub const Deny: Self = Self::None;
244
245 pub fn internet_access_switch(&self) -> Option<bool> {
247 match self {
248 Self::None => Some(false),
249 Self::Internet | Self::Allow => Some(true),
250 Self::AllowDomains { .. } => None,
251 }
252 }
253}
254
255pub const SANDBOX_EXPIRY_LABEL: &str = "alienExpiresAtMs";
257
258pub const AZURE_GATEWAY_MAX_LIFETIME_SECONDS: u32 = 24 * 60 * 60;
260
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
267#[serde(rename_all = "camelCase", deny_unknown_fields)]
268pub struct SandboxLifecyclePolicy {
269 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub max_lifetime_seconds: Option<u32>,
277 #[serde(alias = "idleSuspendSeconds", skip_serializing_if = "Option::is_none")]
281 pub idle_pause_seconds: Option<u32>,
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
290#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
291#[serde(rename_all = "camelCase", deny_unknown_fields)]
292pub struct SandboxCapabilities {
293 pub files: bool,
295 pub reconnect: bool,
297 pub jobs: bool,
300 pub interactive_commands: bool,
303 pub preview: bool,
305 pub pause_resume: bool,
307 pub snapshot: bool,
309 pub domain_egress_rules: bool,
311 pub egress_deny: bool,
314 pub enforced_limits: bool,
316 pub process_limit: bool,
318 pub sandbox_lifetime: bool,
320 pub supervisor_pid_namespace: bool,
326 pub supervisor_isolation: bool,
332}
333
334impl SandboxCapabilities {
335 pub fn for_platform(platform: Platform) -> Result<Self> {
341 match platform {
342 Platform::Aws => Ok(Self {
343 files: true,
344 reconnect: true,
345 jobs: true,
346 interactive_commands: true,
349 preview: true,
350 pause_resume: true,
351 snapshot: false,
352 domain_egress_rules: false,
353 egress_deny: true,
356 enforced_limits: true,
357 process_limit: false,
359 sandbox_lifetime: true,
362 supervisor_pid_namespace: false,
367 supervisor_isolation: true,
370 }),
371 Platform::Azure => Ok(Self::azure()),
372 Platform::Gcp => Ok(Self::gcp_agent_platform()),
373 Platform::Kubernetes => Ok(Self {
376 files: true,
377 reconnect: true,
378 jobs: true,
379 interactive_commands: false,
382 preview: false,
383 pause_resume: false,
384 snapshot: false,
385 domain_egress_rules: false,
386 egress_deny: true,
387 enforced_limits: true,
388 process_limit: false,
390 sandbox_lifetime: true,
392 supervisor_pid_namespace: false,
396 supervisor_isolation: false,
401 }),
402 Platform::Local => Ok(Self {
403 files: true,
404 reconnect: true,
405 jobs: false,
407 interactive_commands: true,
410 preview: true,
411 pause_resume: false,
412 snapshot: false,
413 domain_egress_rules: false,
414 egress_deny: true,
415 enforced_limits: true,
416 process_limit: true,
418 sandbox_lifetime: false,
419 supervisor_pid_namespace: false,
422 supervisor_isolation: true,
426 }),
427 Platform::Machines | Platform::Test => {
428 Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
429 platform: platform.to_string(),
430 }))
431 }
432 }
433 }
434
435 pub fn azure() -> Self {
437 Self {
438 files: true,
439 reconnect: true,
440 jobs: false,
442 interactive_commands: false,
445 preview: false,
450 pause_resume: true,
451 snapshot: false,
455 domain_egress_rules: true,
456 egress_deny: true,
457 enforced_limits: true,
461 process_limit: false,
462 sandbox_lifetime: false,
466 supervisor_pid_namespace: false,
468 supervisor_isolation: false,
471 }
472 }
473
474 pub fn gcp_agent_platform() -> Self {
476 Self {
477 files: true,
479 reconnect: true,
483 jobs: true,
484 interactive_commands: false,
487 preview: false,
489 pause_resume: false,
492 snapshot: false,
495 domain_egress_rules: false,
497 egress_deny: true,
499 enforced_limits: true,
503 process_limit: false,
505 sandbox_lifetime: true,
507 supervisor_pid_namespace: false,
509 supervisor_isolation: false,
512 }
513 }
514
515 pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
517 let available = match capability {
518 SandboxCapability::Files => self.files,
519 SandboxCapability::Reconnect => self.reconnect,
520 SandboxCapability::Jobs => self.jobs,
521 SandboxCapability::InteractiveCommands => self.interactive_commands,
522 SandboxCapability::Preview => self.preview,
523 SandboxCapability::PauseResume => self.pause_resume,
524 SandboxCapability::Snapshot => self.snapshot,
525 SandboxCapability::DomainEgressRules => self.domain_egress_rules,
526 SandboxCapability::EgressDeny => self.egress_deny,
527 SandboxCapability::EnforcedLimits => self.enforced_limits,
528 SandboxCapability::ProcessLimit => self.process_limit,
529 SandboxCapability::SandboxLifetime => self.sandbox_lifetime,
530 SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
531 SandboxCapability::SupervisorIsolation => self.supervisor_isolation,
532 };
533
534 if available {
535 return Ok(());
536 }
537
538 Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
539 capability: capability.as_str().to_string(),
540 platform: platform.to_string(),
541 }))
542 }
543}
544
545#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
547#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
548#[serde(rename_all = "camelCase")]
549pub enum SandboxCapability {
550 Files,
552 Reconnect,
554 Jobs,
556 InteractiveCommands,
558 Preview,
560 PauseResume,
562 Snapshot,
564 DomainEgressRules,
566 EgressDeny,
568 EnforcedLimits,
570 ProcessLimit,
572 SandboxLifetime,
574 SupervisorPidNamespace,
576 SupervisorIsolation,
578}
579
580impl SandboxCapability {
581 pub fn as_str(&self) -> &'static str {
583 match self {
584 Self::Files => "files",
585 Self::Reconnect => "reconnect",
586 Self::Jobs => "jobs",
587 Self::InteractiveCommands => "interactiveCommands",
588 Self::Preview => "preview",
589 Self::PauseResume => "pauseResume",
590 Self::Snapshot => "snapshot",
591 Self::DomainEgressRules => "domainEgressRules",
592 Self::EgressDeny => "egressDeny",
593 Self::EnforcedLimits => "enforcedLimits",
594 Self::ProcessLimit => "processLimit",
595 Self::SandboxLifetime => "sandboxLifetime",
596 Self::SupervisorPidNamespace => "supervisorPidNamespace",
597 Self::SupervisorIsolation => "supervisorIsolation",
598 }
599 }
600}
601
602#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
604#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
605#[serde(rename_all = "camelCase", deny_unknown_fields)]
606pub struct SandboxPrivilegedSupervisor {
607 pub command_uid: u32,
609}
610
611#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
613#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
614#[serde(rename_all = "camelCase", deny_unknown_fields)]
615#[builder(start_fn = new)]
616pub struct Sandbox {
617 #[builder(start_fn)]
620 pub id: String,
621 #[builder(field)]
624 #[serde(default, skip_serializing_if = "Vec::is_empty")]
625 #[cfg_attr(feature = "openapi", schema(ignore))]
626 pub links: Vec<ResourceRef>,
627 pub code: SandboxCode,
629 #[builder(skip)]
632 #[serde(default, skip_serializing_if = "Option::is_none")]
633 #[cfg_attr(feature = "openapi", schema(ignore))]
634 pub image_user: Option<u32>,
635 #[serde(skip_serializing_if = "Option::is_none")]
639 pub private_base_image: Option<String>,
640 #[serde(skip_serializing_if = "Option::is_none")]
646 pub limits: Option<SandboxLimits>,
647 pub egress: SandboxEgress,
649 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub default_policy: Option<EgressPolicy>,
652 #[builder(skip)]
656 #[serde(default, skip_serializing_if = "Option::is_none")]
657 pub privileged_supervisor: Option<SandboxPrivilegedSupervisor>,
658 #[serde(alias = "session")]
663 pub lifecycle: SandboxLifecyclePolicy,
664 #[builder(default)]
668 #[serde(default, skip_serializing_if = "Vec::is_empty")]
669 pub preview_ports: Vec<u16>,
670}
671
672pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
677 !targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
678}
679
680pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
686 stack.resources().any(|(_, entry)| {
687 entry
688 .config
689 .downcast_ref::<Sandbox>()
690 .is_some_and(|sandbox| crate::sandbox_egress::sandbox_needs_connector(stack, sandbox))
691 })
692}
693
694impl Sandbox {
695 pub(crate) fn setup_digest_value(&self) -> serde_json::Value {
696 match &self.egress {
697 SandboxEgress::None => serde_json::json!({"mode":"deny"}),
698 value => serde_json::to_value(value).expect("egress serializes"),
699 }
700 }
701
702 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
704
705 pub fn id(&self) -> &str {
707 &self.id
708 }
709
710 pub fn cloud_egress(&self) -> &SandboxEgress {
713 if self.privileged_supervisor.is_some() && self.egress != SandboxEgress::Internet {
714 &SandboxEgress::Allow
715 } else {
716 &self.egress
717 }
718 }
719
720 pub fn supervisor_environment(&self) -> std::collections::BTreeMap<String, String> {
722 let mut env = std::collections::BTreeMap::new();
723 if let Some(supervisor) = &self.privileged_supervisor {
724 env.insert(
725 "ALIEN_SANDBOX_EXPECTED_EXEC_UID".to_string(),
726 supervisor.command_uid.to_string(),
727 );
728 env.insert(
729 "ALIEN_SANDBOX_EGRESS".to_string(),
730 if self.egress == SandboxEgress::None {
732 r#"{"mode":"deny"}"#.to_string()
733 } else {
734 serde_json::to_string(&self.egress).expect("egress serializes")
735 },
736 );
737 }
738 env
739 }
740
741 pub fn resolved_limits(&self) -> SandboxLimits {
747 self.limits.clone().unwrap_or_else(default_limits)
748 }
749
750 pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
755 if let Some(policy) = &self.default_policy {
756 if self.egress != SandboxEgress::Internet {
757 return Err(AlienError::new(ErrorData::SandboxEgressInvalid {
758 target: "defaultPolicy".into(),
759 reason: "defaultPolicy requires the new internet declaration".into(),
760 }));
761 }
762 policy.validate()?;
763 }
764 if self.image_user == Some(0) && matches!(platform, Platform::Local | Platform::Kubernetes)
765 {
766 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
767 capability: "root image USER: this backend does not yet separate bounded root boot from non-root exec; use a non-root image USER".into(),
768 platform: platform.to_string(),
769 }));
770 }
771 let mut capabilities = SandboxCapabilities::for_platform(platform)?;
772 if let Some(supervisor) = &self.privileged_supervisor {
773 if platform != Platform::Aws {
774 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
775 capability: "privilegedSupervisor".to_string(),
776 platform: platform.to_string(),
777 }));
778 }
779 if supervisor.command_uid == 0 || supervisor.command_uid == u32::MAX {
780 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
781 resource_id: self.id.clone(),
782 field: "privilegedSupervisor.commandUid".to_string(),
783 value: supervisor.command_uid.to_string(),
784 reason: "must be a non-root Linux uid other than the invalid uid sentinel"
785 .to_string(),
786 }));
787 }
788 if let SandboxEgress::AllowDomains { domains } = &self.egress {
789 for domain in domains {
790 let hostname = domain.strip_suffix('.').unwrap_or(domain);
791 if hostname.len() > 253
792 || !hostname.split('.').all(|label| {
793 !label.is_empty()
794 && label.len() <= 63
795 && label
796 .bytes()
797 .all(|c| c.is_ascii_alphanumeric() || c == b'-')
798 && !label.starts_with('-')
799 && !label.ends_with('-')
800 })
801 {
802 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
803 resource_id: self.id.clone(), field: "egress.domains".to_string(), value: domain.clone(),
804 reason: "privileged supervisor allowlists require exact DNS hostnames; wildcards are unsupported".to_string(),
805 }));
806 }
807 }
808 }
809 capabilities.domain_egress_rules = true;
810 }
811
812 if matches!(&self.code, SandboxCode::Source { .. })
817 && !matches!(platform, Platform::Aws | Platform::Azure | Platform::Gcp)
818 {
819 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
820 resource_id: self.id.clone(),
821 field: "code".to_string(),
822 value: "source".to_string(),
823 reason: format!(
824 "no sandbox backend builds an image from source on {platform}; give \
825 code.image a prebuilt reference"
826 ),
827 }));
828 }
829
830 if self.private_base_image.is_some() && platform != Platform::Aws {
833 return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
834 capability: "privateBaseImage".to_string(),
835 platform: platform.to_string(),
836 }));
837 }
838
839 if platform == Platform::Azure && matches!(&self.code, SandboxCode::Image { .. }) {
842 self.azure_image()?;
843 }
844
845 if let Some(seconds) = self.lifecycle.max_lifetime_seconds {
848 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
850
851 if seconds == 0 {
852 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
853 resource_id: self.id.clone(),
854 field: "maxLifetimeSeconds".to_string(),
855 value: "0".to_string(),
856 reason: "a sandbox must be allowed to run for at least 1 second".to_string(),
857 }));
858 }
859
860 let ceiling = match platform {
865 Platform::Aws => Some((AWS_MAX_LIFETIME_SECONDS, "AWS runs a MicroVM for")),
866 Platform::Kubernetes => {
867 Some((KUBERNETES_MAX_LIFETIME_SECONDS, "Kubernetes runs a pod for"))
868 }
869 Platform::Gcp => None,
872 Platform::Azure | Platform::Local | Platform::Machines | Platform::Test => None,
875 };
876 if let Some((max, runs_for)) = ceiling {
877 if seconds > max {
878 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
879 resource_id: self.id.clone(),
880 field: "maxLifetimeSeconds".to_string(),
881 value: seconds.to_string(),
882 reason: format!("{runs_for} between 1 and {max} seconds"),
883 }));
884 }
885 }
886 }
887
888 let Some(limits) = self.limits.as_ref() else {
889 return self.validate_capabilities(&capabilities, platform);
891 };
892
893 validate_quantity(&self.id, "cpu", &limits.cpu)?;
894 validate_quantity(&self.id, "memory", &limits.memory)?;
895 validate_quantity(&self.id, "disk", &limits.disk)?;
896
897 if let Some(max_processes) = limits.max_processes {
898 if max_processes == 0 {
899 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
900 resource_id: self.id.clone(),
901 field: "maxProcesses".to_string(),
902 value: "0".to_string(),
903 reason: "a sandbox that may run no processes cannot run code".to_string(),
904 }));
905 }
906 capabilities.require(SandboxCapability::ProcessLimit, platform)?;
907 }
908
909 capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
912
913 if platform == Platform::Azure {
914 self.azure_sandbox_limits()?;
915 }
916
917 if platform == Platform::Aws {
918 self.microvm_tier()?;
921 }
922
923 self.validate_capabilities(&capabilities, platform)
924 }
925
926 pub fn azure_image(&self) -> Result<AzureSandboxImage<'_>> {
930 let SandboxCode::Image { image, .. } = &self.code else {
931 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
932 resource_id: self.id.clone(),
933 field: "code".to_string(),
934 value: "source".to_string(),
935 reason: "the sandbox still has unbuilt source code. Run 'alien build' first"
936 .to_string(),
937 }));
938 };
939
940 classify_azure_sandbox_image(image).ok_or_else(|| {
941 let image = image.trim();
942 AlienError::new(ErrorData::SandboxLimitInvalid {
943 resource_id: self.id.clone(),
944 field: "code.image".to_string(),
945 value: image.to_string(),
946 reason: if image.is_empty() {
947 "a sandbox has to name an image".to_string()
948 } else {
949 "Azure creates a sandbox from a catalog name such as 'ubuntu' or from a \
950 registry image such as 'docker.io/library/python:3.14-slim'"
951 .to_string()
952 },
953 })
954 })
955 }
956
957 pub fn azure_sandbox_limits(&self) -> Result<()> {
961 let Some(limits) = self.limits.as_ref() else {
962 return Ok(());
965 };
966
967 let refused = |field: &str, value: &str, reason: &str| {
968 AlienError::new(ErrorData::SandboxLimitInvalid {
969 resource_id: self.id.clone(),
970 field: field.to_string(),
971 value: value.to_string(),
972 reason: reason.to_string(),
973 })
974 };
975
976 let cpu_millicores = millicores(&limits.cpu)
977 .ok_or_else(|| refused("cpu", &limits.cpu, "expected cores or millicores"))?;
978
979 if cpu_millicores % AZURE_CPU_STEP_MILLICORES != 0
983 || !(AZURE_CPU_STEP_MILLICORES..=AZURE_MAX_CPU_MILLICORES).contains(&cpu_millicores)
984 {
985 return Err(refused(
986 "cpu",
987 &limits.cpu,
988 "Azure allocates cpu in steps of 250m from 250m to 16000m",
989 ));
990 }
991
992 let memory_ceiling_mib = cpu_millicores * AZURE_MEMORY_MIB_PER_CORE / 1000;
994 let disk_ceiling_mib = cpu_millicores * AZURE_DISK_MIB_PER_CORE / 1000;
995
996 let memory_mib = quantity_mib(&limits.memory)
997 .ok_or_else(|| refused("memory", &limits.memory, "Azure sizes memory in whole MiB"))?;
998 if memory_mib > memory_ceiling_mib {
999 return Err(refused(
1000 "memory",
1001 &limits.memory,
1002 &format!(
1003 "Azure allows at most 2Gi of memory per core, or {memory_ceiling_mib}Mi \
1004 at the declared cpu"
1005 ),
1006 ));
1007 }
1008
1009 let disk_mib = quantity_mib(&limits.disk)
1010 .ok_or_else(|| refused("disk", &limits.disk, "Azure sizes disk in whole MiB"))?;
1011 if disk_mib > disk_ceiling_mib {
1012 return Err(refused(
1013 "disk",
1014 &limits.disk,
1015 &format!(
1016 "Azure allows at most 20Gi of disk per core, or {disk_ceiling_mib}Mi at \
1017 the declared cpu"
1018 ),
1019 ));
1020 }
1021
1022 Ok(())
1023 }
1024
1025 pub fn microvm_tier(&self) -> Result<MicrovmTier> {
1032 let Some(limits) = self.limits.as_ref() else {
1033 return Ok(MICROVM_TIERS[2]);
1035 };
1036
1037 let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
1038 AlienError::new(ErrorData::SandboxLimitInvalid {
1039 resource_id: self.id.clone(),
1040 field: "memory".to_string(),
1041 value: limits.memory.clone(),
1042 reason: "AWS sizes a MicroVM in whole MiB".to_string(),
1043 })
1044 })?;
1045 let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
1046 AlienError::new(ErrorData::SandboxLimitInvalid {
1047 resource_id: self.id.clone(),
1048 field: "disk".to_string(),
1049 value: limits.disk.clone(),
1050 reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
1051 })
1052 })?;
1053 let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
1054 AlienError::new(ErrorData::SandboxLimitInvalid {
1055 resource_id: self.id.clone(),
1056 field: "cpu".to_string(),
1057 value: limits.cpu.clone(),
1058 reason: "expected cores or millicores".to_string(),
1059 })
1060 })?;
1061
1062 let sized = |tier: &&MicrovmTier| {
1067 tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
1068 };
1069
1070 let tier = MICROVM_TIERS
1071 .iter()
1072 .rev()
1073 .find(sized)
1074 .copied()
1075 .ok_or_else(|| {
1076 AlienError::new(ErrorData::SandboxLimitInvalid {
1077 resource_id: self.id.clone(),
1078 field: "memory".to_string(),
1079 value: limits.memory.clone(),
1080 reason: format!(
1081 "a Lambda MicroVM bursts to four times its baseline, so the smallest \
1082 ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
1083 disk fit no size",
1084 limits.memory, limits.disk
1085 ),
1086 })
1087 })?;
1088
1089 let required_millicores = i64::from(tier.peak_vcpu) * 1000;
1090 if cpu_millicores < required_millicores {
1091 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1092 resource_id: self.id.clone(),
1093 field: "cpu".to_string(),
1094 value: limits.cpu.clone(),
1095 reason: format!(
1096 "AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
1097 reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
1098 limits.memory, tier.peak_vcpu, tier.peak_vcpu
1099 ),
1100 }));
1101 }
1102
1103 Ok(tier)
1104 }
1105
1106 fn validate_capabilities(
1108 &self,
1109 capabilities: &SandboxCapabilities,
1110 platform: Platform,
1111 ) -> Result<()> {
1112 if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
1113 capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
1114 }
1115
1116 if let SandboxEgress::AllowDomains { domains } = &self.egress {
1122 if domains.is_empty() {
1123 return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1124 resource_id: self.id.clone(),
1125 field: "egress.domains".to_string(),
1126 value: "[]".to_string(),
1127 reason: "an allowlist naming no domain denies everything; declare \
1128 egress: deny if that is what was meant"
1129 .to_string(),
1130 }));
1131 }
1132 }
1133
1134 if matches!(self.egress, SandboxEgress::None) {
1135 capabilities.require(SandboxCapability::EgressDeny, platform)?;
1136 }
1137
1138 if !self.preview_ports.is_empty() {
1139 capabilities.require(SandboxCapability::Preview, platform)?;
1140 }
1141
1142 if self.lifecycle.idle_pause_seconds.is_some() {
1143 capabilities.require(SandboxCapability::PauseResume, platform)?;
1144 }
1145
1146 if self.lifecycle.max_lifetime_seconds.is_some() {
1147 capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
1148 }
1149
1150 Ok(())
1151 }
1152}
1153
1154fn default_limits() -> SandboxLimits {
1159 SandboxLimits {
1160 cpu: "1".to_string(),
1161 memory: "2Gi".to_string(),
1162 disk: "8Gi".to_string(),
1163 max_processes: None,
1164 }
1165}
1166
1167fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
1169 let invalid = |reason: &str| {
1170 AlienError::new(ErrorData::SandboxLimitInvalid {
1171 resource_id: resource_id.to_string(),
1172 field: field.to_string(),
1173 value: value.to_string(),
1174 reason: reason.to_string(),
1175 })
1176 };
1177
1178 let digits_end = value
1179 .find(|c: char| !c.is_ascii_digit() && c != '.')
1180 .unwrap_or(value.len());
1181 let (number, suffix) = value.split_at(digits_end);
1182
1183 let parsed: f64 = number
1184 .parse()
1185 .map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
1186
1187 if parsed <= 0.0 {
1188 return Err(invalid("must be greater than zero"));
1189 }
1190
1191 const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
1192 if !SUFFIXES.contains(&suffix) {
1193 return Err(invalid(
1194 "unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
1195 ));
1196 }
1197
1198 Ok(())
1199}
1200
1201fn split_quantity(value: &str) -> Option<(f64, &str)> {
1203 let trimmed = value.trim();
1204 let digits_end = trimmed
1205 .find(|c: char| !c.is_ascii_digit() && c != '.')
1206 .unwrap_or(trimmed.len());
1207 let (number, suffix) = trimmed.split_at(digits_end);
1208 number.parse().ok().map(|number| (number, suffix))
1209}
1210
1211pub fn quantity_mib(value: &str) -> Option<i64> {
1217 let (number, suffix) = split_quantity(value)?;
1218 let bytes = match suffix {
1219 "" => number,
1220 "k" => number * 1e3,
1221 "M" => number * 1e6,
1222 "G" => number * 1e9,
1223 "T" => number * 1e12,
1224 "Ki" => number * 1024.0,
1225 "Mi" => number * 1024.0 * 1024.0,
1226 "Gi" => number * 1024.0 * 1024.0 * 1024.0,
1227 "Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
1228 _ => return None,
1230 };
1231 Some((bytes / (1024.0 * 1024.0)) as i64)
1232}
1233
1234pub fn millicores(value: &str) -> Option<i64> {
1236 let (number, suffix) = split_quantity(value)?;
1237 match suffix {
1238 "" => Some((number * 1000.0) as i64),
1239 "m" => Some(number as i64),
1240 _ => None,
1241 }
1242}
1243
1244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1246#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1247#[serde(rename_all = "camelCase")]
1248pub struct SandboxOutputs {
1249 pub parent_name: String,
1251 #[serde(skip_serializing_if = "Option::is_none")]
1253 pub identifier: Option<String>,
1254 #[serde(skip_serializing_if = "Option::is_none")]
1256 pub endpoint: Option<String>,
1257}
1258
1259impl ResourceOutputsDefinition for SandboxOutputs {
1260 fn get_resource_type(&self) -> ResourceType {
1261 Sandbox::RESOURCE_TYPE
1262 }
1263
1264 fn as_any(&self) -> &dyn Any {
1265 self
1266 }
1267
1268 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
1269 Box::new(self.clone())
1270 }
1271
1272 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
1273 other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
1274 }
1275
1276 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1277 serde_json::to_value(self)
1278 }
1279}
1280
1281impl ResourceDefinition for Sandbox {
1282 fn get_resource_type(&self) -> ResourceType {
1283 Self::RESOURCE_TYPE
1284 }
1285
1286 fn id(&self) -> &str {
1287 &self.id
1288 }
1289
1290 fn replace_after_failed_create_is_safe(&self) -> bool {
1291 false
1294 }
1295
1296 fn get_dependencies(&self) -> Vec<ResourceRef> {
1297 Vec::new()
1298 }
1299
1300 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1301 let new_sandbox = new_config
1302 .as_any()
1303 .downcast_ref::<Sandbox>()
1304 .ok_or_else(|| {
1305 AlienError::new(ErrorData::UnexpectedResourceType {
1306 resource_id: self.id.clone(),
1307 expected: Self::RESOURCE_TYPE,
1308 actual: new_config.get_resource_type(),
1309 })
1310 })?;
1311
1312 if self.id != new_sandbox.id {
1313 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1314 resource_id: self.id.clone(),
1315 reason: "the 'id' field is immutable".to_string(),
1316 }));
1317 }
1318
1319 Ok(())
1320 }
1321
1322 fn as_any(&self) -> &dyn Any {
1323 self
1324 }
1325
1326 fn as_any_mut(&mut self) -> &mut dyn Any {
1327 self
1328 }
1329
1330 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1331 Box::new(self.clone())
1332 }
1333
1334 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1335 other.as_any().downcast_ref::<Sandbox>() == Some(self)
1336 }
1337
1338 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1339 serde_json::to_value(self)
1340 }
1341}
1342
1343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1345pub enum AzureSandboxImage<'a> {
1346 Catalog(&'a str),
1348 Registry(&'a str),
1351}
1352
1353impl<'a> AzureSandboxImage<'a> {
1354 pub fn as_str(&self) -> &'a str {
1356 match self {
1357 Self::Catalog(value) | Self::Registry(value) => value,
1358 }
1359 }
1360}
1361
1362pub const AZURE_DISK_IMAGE_LABEL: &str = "alienImage";
1364
1365pub fn classify_azure_sandbox_image(image: &str) -> Option<AzureSandboxImage<'_>> {
1369 let image = image.trim();
1370 if image.is_empty() {
1371 return None;
1372 }
1373 if image
1374 .chars()
1375 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1376 {
1377 return Some(AzureSandboxImage::Catalog(image));
1378 }
1379 (image.contains(|c| matches!(c, '/' | ':' | '@')) && OCI_REFERENCE.is_match(image))
1380 .then_some(AzureSandboxImage::Registry(image))
1381}
1382
1383pub fn azure_disk_image_label(reference: &str) -> String {
1386 let digest = format!("{:x}", Sha256::digest(reference.trim().as_bytes()));
1387 digest[..32].to_string()
1388}
1389
1390static OCI_REFERENCE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1392 let domain_component = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
1393 let domain = format!(r"{domain_component}(?:\.{domain_component})*(?::[0-9]+)?");
1394 let path_component = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
1395 let name = format!(r"(?:{domain}/)?{path_component}(?:/{path_component})*");
1396 let tag = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}";
1397 let digest = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
1398 regex::Regex::new(&format!(r"^{name}(?::{tag})?(?:@{digest})?$"))
1399 .expect("the OCI reference grammar compiles")
1400});
1401
1402pub const BUNDLE_REGION_TOKEN: &str = "{region}";
1407
1408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1410pub enum BundleUri<'a> {
1411 Literal(&'a str),
1413 Regional { before: &'a str, after: &'a str },
1416}
1417
1418pub fn stable_bundle_key_prefix(key: &str) -> Option<&str> {
1422 let (above_file, _) = key.rsplit_once('/')?;
1423 let (above_version, _) = above_file.rsplit_once('/')?;
1424 Some(above_version)
1425}
1426
1427pub fn parse_bundle_uri(uri: &str) -> std::result::Result<BundleUri<'_>, String> {
1433 let path = uri
1434 .strip_prefix("s3://")
1435 .ok_or_else(|| format!("'{uri}' is not an s3:// URI"))?;
1436 let (bucket, key) = path
1437 .split_once('/')
1438 .ok_or_else(|| format!("'{uri}' names a bucket with no object key"))?;
1439
1440 if path.contains('*') || path.contains('?') {
1444 return Err(format!(
1445 "'{uri}' carries an IAM wildcard; the bundle's path is interpolated into the build \
1446 role's grant, so '*' and '?' would widen it past the bundle"
1447 ));
1448 }
1449
1450 if key.contains('{') || key.contains('}') {
1451 return Err(format!(
1452 "'{uri}' places a token in the object key; {BUNDLE_REGION_TOKEN} is accepted in the \
1453 bucket name alone"
1454 ));
1455 }
1456
1457 let Some((before, after)) = bucket.split_once(BUNDLE_REGION_TOKEN) else {
1458 if bucket.contains('{') || bucket.contains('}') {
1459 return Err(format!(
1460 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the \
1461 only one"
1462 ));
1463 }
1464 return Ok(BundleUri::Literal(uri));
1465 };
1466
1467 if after.contains(BUNDLE_REGION_TOKEN) {
1468 return Err(format!("'{uri}' repeats {BUNDLE_REGION_TOKEN}"));
1469 }
1470 if before.contains('{') || before.contains('}') || after.contains('{') || after.contains('}') {
1471 return Err(format!(
1472 "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the only one"
1473 ));
1474 }
1475
1476 Ok(BundleUri::Regional {
1477 before: &uri[.."s3://".len() + before.len()],
1478 after: &uri["s3://".len() + before.len() + BUNDLE_REGION_TOKEN.len()..],
1479 })
1480}
1481
1482#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1484pub enum EcrImageRegion<'a> {
1485 Literal(&'a str),
1487 Deployment,
1489}
1490
1491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1493pub struct EcrImageRepository<'a> {
1494 pub account_id: &'a str,
1495 pub region: EcrImageRegion<'a>,
1496 pub repository: &'a str,
1498}
1499
1500impl EcrImageRepository<'_> {
1501 pub fn arn(&self, partition: &str, region: &str) -> String {
1504 let region = match self.region {
1505 EcrImageRegion::Literal(region) => region,
1506 EcrImageRegion::Deployment => region,
1507 };
1508 format!(
1509 "arn:{partition}:ecr:{region}:{}:repository/{}",
1510 self.account_id, self.repository
1511 )
1512 }
1513}
1514
1515pub fn parse_ecr_image_repository(
1521 image: &str,
1522) -> std::result::Result<EcrImageRepository<'_>, String> {
1523 let refuse = |reason: &str| format!("privateBaseImage '{image}' {reason}");
1524 let (host, path) = image
1525 .split_once('/')
1526 .ok_or_else(|| refuse("names no repository"))?;
1527 let (account_id, rest) = host.split_once(".dkr.ecr.").ok_or_else(|| {
1528 refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)")
1529 })?;
1530 let region = rest
1532 .strip_suffix(".amazonaws.com.cn")
1533 .or_else(|| rest.strip_suffix(".amazonaws.com"))
1534 .ok_or_else(|| refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)"))?;
1535 if account_id.len() != 12 || !account_id.bytes().all(|b| b.is_ascii_digit()) {
1536 return Err(refuse("names no 12-digit account in its registry host"));
1537 }
1538 let region = if region == BUNDLE_REGION_TOKEN {
1539 EcrImageRegion::Deployment
1540 } else if !region.is_empty()
1541 && region
1542 .bytes()
1543 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1544 {
1545 EcrImageRegion::Literal(region)
1546 } else {
1547 return Err(refuse(&format!(
1548 "names no region in its registry host; give one or {BUNDLE_REGION_TOKEN}"
1549 )));
1550 };
1551
1552 let repository = match path.split_once('@') {
1553 Some((repository, _digest)) => repository,
1554 None => match path.rsplit_once('/') {
1555 Some((parent, last)) => match last.split_once(':') {
1556 Some((name, _tag)) => &path[..parent.len() + 1 + name.len()],
1557 None => path,
1558 },
1559 None => path.split_once(':').map_or(path, |(name, _tag)| name),
1560 },
1561 };
1562 let valid_segment = |segment: &str| {
1563 !segment.is_empty()
1564 && segment.bytes().all(|b| {
1565 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
1566 })
1567 };
1568 if !repository.split('/').all(valid_segment) {
1569 return Err(refuse(
1570 "names a repository outside ECR's grammar (lowercase letters, digits, '.', '_', '-', and '/' between them)",
1571 ));
1572 }
1573 Ok(EcrImageRepository {
1574 account_id,
1575 region,
1576 repository,
1577 })
1578}
1579
1580#[cfg(test)]
1581mod tests {
1582 use super::*;
1583
1584 #[test]
1585 fn private_database_setup_accepts_the_default_network() {
1586 for lifecycle in [
1587 crate::ResourceLifecycle::Frozen,
1588 crate::ResourceLifecycle::Live,
1589 ] {
1590 let stack = crate::Stack::new("database".to_string())
1591 .add(
1592 crate::Postgres::new("metadata".to_string()).build(),
1593 lifecycle,
1594 )
1595 .build();
1596 assert!(!restricts_network_mode(&stack, false));
1597 assert!(!restricts_network_mode(&stack, true));
1598 }
1599 assert!(!restricts_network_mode(
1600 &crate::Stack::new("empty".to_string()).build(),
1601 false,
1602 ));
1603 }
1604
1605 fn repository_key(image: &str) -> String {
1608 match parse_ecr_image_repository(image) {
1609 Ok(parsed) => {
1610 let host = image.split_once('/').map_or(image, |(host, _)| host);
1611 format!("{host}/{}", parsed.repository)
1612 }
1613 Err(_) => image.to_string(),
1614 }
1615 }
1616
1617 #[test]
1618 fn a_private_base_image_names_one_repository() {
1619 let vectors: serde_json::Value = serde_json::from_str(include_str!(
1620 "../../tests/fixtures/ecr-image-repository-parity.json"
1621 ))
1622 .expect("the ECR repository vectors must be JSON");
1623 let field = |case: &serde_json::Value, name: &str| {
1624 case[name]
1625 .as_str()
1626 .unwrap_or_else(|| panic!("vector must carry {name}: {case}"))
1627 .to_string()
1628 };
1629
1630 for case in vectors["accepted"].as_array().expect("accepted vectors") {
1631 let image = field(case, "image");
1632 let region = field(case, "region");
1633 let region = if region == BUNDLE_REGION_TOKEN {
1634 EcrImageRegion::Deployment
1635 } else {
1636 EcrImageRegion::Literal(®ion)
1637 };
1638 assert_eq!(
1639 parse_ecr_image_repository(&image),
1640 Ok(EcrImageRepository {
1641 account_id: &field(case, "accountId"),
1642 region,
1643 repository: &field(case, "repository"),
1644 }),
1645 "{image}"
1646 );
1647 assert_eq!(
1648 repository_key(&image),
1649 field(case, "repositoryKey"),
1650 "{image}"
1651 );
1652 }
1653
1654 for case in vectors["refused"].as_array().expect("refused vectors") {
1655 let image = field(case, "image");
1656 assert!(
1657 parse_ecr_image_repository(&image).is_err(),
1658 "{image} must be refused"
1659 );
1660 assert_eq!(
1661 repository_key(&image),
1662 field(case, "repositoryKey"),
1663 "{image}"
1664 );
1665 }
1666 }
1667
1668 #[test]
1669 fn a_repository_arn_takes_the_deployment_region_only_where_the_host_leaves_it() {
1670 let regional =
1671 parse_ecr_image_repository("123456789012.dkr.ecr.{region}.amazonaws.com/team/base:1")
1672 .expect("parses");
1673 let pinned =
1674 parse_ecr_image_repository("123456789012.dkr.ecr.eu-west-1.amazonaws.com/team/base:1")
1675 .expect("parses");
1676 assert_eq!(
1677 regional.arn("aws-us-gov", "us-gov-west-1"),
1678 "arn:aws-us-gov:ecr:us-gov-west-1:123456789012:repository/team/base"
1679 );
1680 assert_eq!(
1681 pinned.arn("aws", "us-east-1"),
1682 "arn:aws:ecr:eu-west-1:123456789012:repository/team/base"
1683 );
1684 }
1685
1686 #[test]
1689 fn a_uri_carrying_an_iam_wildcard_is_refused() {
1690 for uri in [
1691 "s3://acme/team-*/v1/bundle.zip",
1692 "s3://acme/sandbox-bundle/f00d/bundle?.zip",
1693 "s3://acme-*/sandbox-bundle/f00d/bundle.zip",
1694 ] {
1695 let error = parse_bundle_uri(uri).expect_err("a wildcard must be refused");
1696 assert!(error.contains("IAM wildcard"), "for {uri}: {error}");
1697 }
1698
1699 parse_bundle_uri("s3://acme/sandbox-bundle/f00d/bundle.zip")
1700 .expect("an ordinary key still parses");
1701 }
1702
1703 #[test]
1707 fn a_grantable_prefix_stops_above_the_segment_that_moves() {
1708 assert_eq!(
1709 stable_bundle_key_prefix("sandbox-bundle/f00dcafe/bundle.zip"),
1710 Some("sandbox-bundle")
1711 );
1712 assert_eq!(
1713 stable_bundle_key_prefix("artifacts/team-a/sandbox/f00dcafe/bundle.zip"),
1714 Some("artifacts/team-a/sandbox"),
1715 "a deeper key narrows the prefix, it never widens to the first segment"
1716 );
1717
1718 assert_eq!(stable_bundle_key_prefix("agents/bundle.zip"), None);
1721 assert_eq!(stable_bundle_key_prefix("bundle.zip"), None);
1722 }
1723
1724 fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
1725 Sandbox::new("agent-sbx".to_string())
1726 .code(SandboxCode::Image {
1727 image: "ubuntu".to_string(),
1728 bundled_from: None,
1729 })
1730 .limits(SandboxLimits {
1731 cpu: "1".to_string(),
1732 memory: "2Gi".to_string(),
1733 disk: "20Gi".to_string(),
1734 max_processes: None,
1735 })
1736 .egress(egress)
1737 .lifecycle(SandboxLifecyclePolicy {
1738 max_lifetime_seconds: None,
1739 idle_pause_seconds: None,
1740 })
1741 .preview_ports(preview_ports)
1742 .build()
1743 }
1744
1745 #[test]
1748 fn a_uri_without_a_token_is_carried_whole() {
1749 assert_eq!(
1750 parse_bundle_uri("s3://acme-artifacts-us-east-2/agents/bundle.zip"),
1751 Ok(BundleUri::Literal(
1752 "s3://acme-artifacts-us-east-2/agents/bundle.zip"
1753 ))
1754 );
1755 }
1756
1757 #[test]
1760 fn a_regional_uri_splits_either_side_of_the_token() {
1761 let BundleUri::Regional { before, after } =
1762 parse_bundle_uri("s3://acme-artifacts-{region}/agents/bundle.zip")
1763 .expect("the token is accepted in the bucket")
1764 else {
1765 panic!("a bucket-position token must split");
1766 };
1767
1768 assert_eq!(before, "s3://acme-artifacts-");
1769 assert_eq!(after, "/agents/bundle.zip");
1770 assert_eq!(
1771 format!("{before}us-east-2{after}"),
1772 "s3://acme-artifacts-us-east-2/agents/bundle.zip",
1773 "the halves must rejoin to the URI the vendor meant"
1774 );
1775 }
1776
1777 #[test]
1780 fn a_token_this_build_cannot_resolve_is_refused() {
1781 for uri in [
1782 "s3://acme-artifacts-{regio}/bundle.zip",
1783 "s3://acme-artifacts/{region}/bundle.zip",
1784 "s3://acme-artifacts-{region}-{region}/bundle.zip",
1785 "s3://acme-artifacts/bundle-{version}.zip",
1786 "s3://acme}-artifacts-{region}/bundle.zip",
1787 "s3://acme{-artifacts-{region}/bundle.zip",
1788 ] {
1789 assert!(
1790 parse_bundle_uri(uri).is_err(),
1791 "'{uri}' must be refused before it can reach an image build"
1792 );
1793 }
1794 }
1795
1796 #[test]
1797 fn resource_type_is_stable() {
1798 assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
1799 }
1800
1801 #[test]
1802 fn capability_sets_are_per_platform() {
1803 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
1804 assert!(
1805 gcp.reconnect,
1806 "generation from the container boot id makes a sandbox reachable across processes"
1807 );
1808 assert!(!gcp.preview);
1809 assert!(gcp.enforced_limits);
1810
1811 let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
1812 assert!(azure.files, "every backend moves files");
1813 assert!(gcp.files);
1814 assert!(azure.domain_egress_rules);
1817 assert!(azure.egress_deny);
1818 assert!(azure.enforced_limits);
1821 assert!(azure.pause_resume);
1822 assert!(!azure.snapshot);
1826 assert!(!azure.preview);
1827
1828 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
1829 assert!(!aws.snapshot, "AWS has no user-callable sandbox snapshot");
1830 assert!(aws.pause_resume);
1831
1832 let k8s =
1833 SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
1834 assert!(
1835 !k8s.preview,
1836 "the sandbox-scoped ingress gateway does not exist yet"
1837 );
1838 }
1839
1840 #[test]
1849 fn supervisor_isolation_is_per_platform() {
1850 let value = |platform| {
1851 SandboxCapabilities::for_platform(platform)
1852 .expect("supported")
1853 .supervisor_isolation
1854 };
1855
1856 assert!(
1857 value(Platform::Aws),
1858 "root agent setuids the command to 60000"
1859 );
1860 assert!(
1861 value(Platform::Local),
1862 "the supervisor is on the host, outside the container"
1863 );
1864 assert!(
1865 !value(Platform::Kubernetes),
1866 "a single pinned uid cannot be split"
1867 );
1868 assert!(!value(Platform::Azure), "no Alien process runs the command");
1869 assert!(
1870 !value(Platform::Gcp),
1871 "no separate supervisor identity runs the command"
1872 );
1873 }
1874
1875 #[test]
1879 fn supervisor_isolation_separates_aws_from_a_subprocess_backend() {
1880 let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
1881 let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
1882
1883 assert_eq!(
1884 aws.supervisor_pid_namespace, gcp.supervisor_pid_namespace,
1885 "the older axis cannot tell them apart"
1886 );
1887 assert!(
1888 aws.supervisor_isolation,
1889 "AWS setuids the command off the supervisor"
1890 );
1891 assert!(
1892 !gcp.supervisor_isolation,
1893 "the command runs under no separate supervisor identity"
1894 );
1895 }
1896
1897 #[test]
1902 fn gcp_agent_platform_row_matches_measured_backend() {
1903 let row = SandboxCapabilities::gcp_agent_platform();
1904
1905 assert!(row.files, "agent file ops move over the sandbox envelope");
1906 assert!(
1907 row.reconnect,
1908 "generation is derived from the container boot id, so a sandbox is reachable across \
1909 processes"
1910 );
1911 assert!(
1912 !row.preview,
1913 "the only ingress is :execute; no port-scoped capability"
1914 );
1915 assert!(
1916 !row.pause_resume,
1917 ":resume can return a fresh container, so a pause keeps no state"
1918 );
1919 assert!(
1920 !row.snapshot,
1921 "the create path never sends a snapshot, so none is reachable through the trait"
1922 );
1923 assert!(
1924 !row.domain_egress_rules,
1925 "VPC and DNS peering is not a hostname allowlist"
1926 );
1927 assert!(
1928 row.egress_deny,
1929 "a declared deny blocks both egress and DNS"
1930 );
1931 assert!(
1932 row.enforced_limits,
1933 "ceilings are enforced, by terminating the sandbox on breach"
1934 );
1935 assert!(!row.process_limit, "no process-count ceiling is observed");
1936 assert!(row.sandbox_lifetime, "ttl maps to a sandbox expireTime");
1937 assert!(!row.supervisor_pid_namespace, "no PID-namespace isolation");
1938 assert!(
1939 !row.supervisor_isolation,
1940 "the command is not run under a separate supervisor identity"
1941 );
1942
1943 let live = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
1945 assert_eq!(
1946 live, row,
1947 "the Platform::Gcp arm is the Agent Platform capability row"
1948 );
1949 }
1950
1951 #[test]
1952 fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
1953 let error = SandboxCapabilities::for_platform(Platform::Machines)
1954 .expect_err("Machines has no sandbox backend");
1955 assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
1956 }
1957
1958 #[test]
1959 fn unsupported_capability_names_platform_and_capability() {
1960 let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
1961 let error = capabilities
1962 .require(SandboxCapability::Preview, Platform::Gcp)
1963 .expect_err("GCP has no preview");
1964
1965 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
1966 let rendered = error.to_string();
1967 assert!(
1968 rendered.contains("preview"),
1969 "names the capability: {rendered}"
1970 );
1971 assert!(rendered.contains("gcp"), "names the platform: {rendered}");
1972 }
1973
1974 #[test]
1978 fn a_hostname_allowlist_is_refused_everywhere_it_would_be_approximated() {
1979 let sandbox = sandbox_with(
1980 SandboxEgress::AllowDomains {
1981 domains: vec!["example.com".to_string()],
1982 },
1983 vec![],
1984 );
1985
1986 for platform in [
1987 Platform::Aws,
1988 Platform::Gcp,
1989 Platform::Kubernetes,
1990 Platform::Local,
1991 ] {
1992 let error = sandbox
1993 .validate_for_platform(platform)
1994 .expect_err("only Azure expresses a hostname allowlist");
1995 assert_eq!(
1996 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
1997 "on {platform:?}"
1998 );
1999 }
2000
2001 assert!(
2002 SandboxCapabilities::for_platform(Platform::Azure)
2003 .expect("supported")
2004 .domain_egress_rules,
2005 "Azure's egress policy matches on host pattern"
2006 );
2007 }
2008
2009 #[test]
2012 fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
2013 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2014
2015 assert!(
2018 SandboxCapabilities::for_platform(Platform::Gcp)
2019 .expect("supported")
2020 .egress_deny
2021 );
2022
2023 for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
2024 sandbox
2025 .validate_for_platform(platform)
2026 .expect("deny is enforced here");
2027 }
2028
2029 let egress_only = Sandbox::new("sbx".to_string())
2031 .code(SandboxCode::Image {
2032 image: "alpine".to_string(),
2033 bundled_from: None,
2034 })
2035 .egress(SandboxEgress::None)
2036 .lifecycle(SandboxLifecyclePolicy {
2037 max_lifetime_seconds: None,
2038 idle_pause_seconds: None,
2039 })
2040 .build();
2041
2042 egress_only
2043 .validate_for_platform(Platform::Azure)
2044 .expect("Azure creates the sandbox under a Deny policy with full inspection");
2045 }
2046
2047 #[test]
2051 fn a_sandbox_declaring_no_ceilings_takes_the_platforms_own() {
2052 let undeclared = Sandbox::new("sbx".to_string())
2053 .code(SandboxCode::Image {
2054 image: "alpine".to_string(),
2055 bundled_from: None,
2056 })
2057 .egress(SandboxEgress::None)
2058 .lifecycle(SandboxLifecyclePolicy {
2059 max_lifetime_seconds: None,
2060 idle_pause_seconds: None,
2061 })
2062 .build();
2063
2064 undeclared
2065 .validate_for_platform(Platform::Azure)
2066 .expect("a sandbox naming no ceilings takes the platform's own");
2067
2068 assert_eq!(undeclared.resolved_limits().cpu, "1");
2070 }
2071
2072 #[test]
2076 fn azure_sizes_follow_the_rule_the_data_plane_states() {
2077 let sized = |cpu: &str, memory: &str, disk: &str| {
2078 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2079 let limits = sandbox
2080 .limits
2081 .as_mut()
2082 .expect("the fixture declares limits");
2083 limits.cpu = cpu.to_string();
2084 limits.memory = memory.to_string();
2085 limits.disk = disk.to_string();
2086 sandbox.validate_for_platform(Platform::Azure)
2087 };
2088
2089 sized("250m", "512Mi", "5120Mi").expect("the smallest step the data plane accepts");
2090 sized("4000m", "8192Mi", "40960Mi").expect("cpu, memory and disk are all honoured");
2091 sized("16000m", "32Gi", "320Gi").expect("the top of the range");
2092
2093 let off_step = sized("333m", "512Mi", "5120Mi").expect_err("333m is not a step of 250m");
2095 assert_eq!(off_step.code, "SANDBOX_LIMIT_INVALID", "{off_step}");
2096 assert!(off_step.to_string().contains("cpu"), "{off_step}");
2097
2098 let too_big = sized("32000m", "64Gi", "640Gi").expect_err("32 cores is over the ceiling");
2099 assert_eq!(too_big.code, "SANDBOX_LIMIT_INVALID", "{too_big}");
2100
2101 sized("1000m", "2Gi", "20Gi").expect("2Gi is exactly one core's worth");
2104 let over_memory = sized("250m", "2Gi", "5120Mi").expect_err("2Gi needs a full core");
2105 assert_eq!(over_memory.code, "SANDBOX_LIMIT_INVALID", "{over_memory}");
2106 assert!(over_memory.to_string().contains("memory"), "{over_memory}");
2107
2108 let over_disk = sized("250m", "512Mi", "20Gi").expect_err("20Gi needs a full core");
2109 assert!(over_disk.to_string().contains("disk"), "{over_disk}");
2110 }
2111
2112 #[test]
2113 fn preview_ports_require_the_preview_capability() {
2114 let sandbox = sandbox_with(SandboxEgress::None, vec![8080]);
2115
2116 sandbox
2117 .validate_for_platform(Platform::Aws)
2118 .expect("AWS mints a port-scoped JWE");
2119
2120 let error = sandbox
2121 .validate_for_platform(Platform::Kubernetes)
2122 .expect_err("Kubernetes preview is deferred");
2123 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2124 }
2125
2126 #[test]
2130 fn a_private_base_image_is_refused_off_aws() {
2131 let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2132 sandbox.code = SandboxCode::Image {
2133 image: "s3://acme-artifacts/agents/bundle.zip".to_string(),
2134 bundled_from: None,
2135 };
2136 sandbox.private_base_image =
2137 Some("123456789012.dkr.ecr.{region}.amazonaws.com/acme:tag".to_string());
2138
2139 sandbox
2140 .validate_for_platform(Platform::Aws)
2141 .expect("AWS builds its image from a bundle, so a base image sits behind code.image");
2142
2143 for platform in [
2144 Platform::Gcp,
2145 Platform::Azure,
2146 Platform::Kubernetes,
2147 Platform::Local,
2148 ] {
2149 let error = sandbox
2150 .validate_for_platform(platform)
2151 .expect_err("a backend that builds no image must refuse a base image for one");
2152 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2153 assert!(
2154 error.to_string().contains("privateBaseImage"),
2155 "the refusal must name the field the user declared: {error}"
2156 );
2157 }
2158 }
2159
2160 #[test]
2161 fn gcp_accepts_a_sandbox_declaring_enforced_limits() {
2162 let sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2163 sandbox
2164 .validate_for_platform(Platform::Gcp)
2165 .expect("Agent Platform enforces declared ceilings, by terminating on breach");
2166 }
2167
2168 #[test]
2169 fn invalid_quantities_are_rejected_with_the_offending_field() {
2170 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2171 sandbox
2172 .limits
2173 .as_mut()
2174 .expect("the fixture declares limits")
2175 .memory = "2Gb".to_string();
2176
2177 let error = sandbox
2178 .validate_for_platform(Platform::Aws)
2179 .expect_err("Gb is not a valid suffix");
2180 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2181 assert!(error.to_string().contains("memory"));
2182
2183 sandbox
2184 .limits
2185 .as_mut()
2186 .expect("the fixture declares limits")
2187 .memory = "2Gi".to_string();
2188 sandbox
2189 .limits
2190 .as_mut()
2191 .expect("the fixture declares limits")
2192 .cpu = "0".to_string();
2193 let error = sandbox
2194 .validate_for_platform(Platform::Aws)
2195 .expect_err("zero cpu is not a ceiling");
2196 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2197 }
2198
2199 #[test]
2200 fn zero_max_processes_is_rejected() {
2201 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2202 sandbox
2203 .limits
2204 .as_mut()
2205 .expect("the fixture declares limits")
2206 .max_processes = Some(0);
2207
2208 let error = sandbox
2209 .validate_for_platform(Platform::Local)
2210 .expect_err("a sandbox must be able to run at least one process");
2211 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2212 assert!(error.to_string().contains("maxProcesses"));
2213 }
2214
2215 #[test]
2219 fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
2220 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2221 sandbox
2222 .limits
2223 .as_mut()
2224 .expect("the fixture declares limits")
2225 .max_processes = Some(256);
2226
2227 sandbox
2228 .validate_for_platform(Platform::Local)
2229 .expect("Docker takes a pids limit");
2230
2231 for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
2232 let error = sandbox
2233 .validate_for_platform(platform)
2234 .expect_err("a process ceiling nothing applies must be refused");
2235 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2236 }
2237 }
2238
2239 #[test]
2244 fn a_lifetime_aws_would_reject_is_refused_while_planning() {
2245 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2246 let mut without_limits = with_limits.clone();
2247 without_limits.limits = None;
2248
2249 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2250 for seconds in [28_801, 30_000, 100_000] {
2251 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2252 let error = sandbox
2253 .validate_for_platform(Platform::Aws)
2254 .expect_err("a lifetime above what AWS runs is refused");
2255 assert_eq!(
2256 error.code, "SANDBOX_LIMIT_INVALID",
2257 "{seconds}s {declared} limits"
2258 );
2259
2260 sandbox
2262 .validate_for_platform(Platform::Kubernetes)
2263 .expect("Kubernetes takes an activeDeadlineSeconds above 28,800");
2264 }
2265
2266 sandbox.lifecycle.max_lifetime_seconds = Some(28_800);
2267 sandbox
2268 .validate_for_platform(Platform::Aws)
2269 .expect("the ceiling itself is allowed");
2270 }
2271 }
2272
2273 #[test]
2277 fn a_zero_lifetime_is_refused_while_planning() {
2278 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2279 let mut without_limits = with_limits.clone();
2280 without_limits.limits = None;
2281
2282 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2283 sandbox.lifecycle.max_lifetime_seconds = Some(0);
2284 for platform in [Platform::Aws, Platform::Kubernetes, Platform::Gcp] {
2285 let error = sandbox
2286 .validate_for_platform(platform)
2287 .expect_err("a zero lifetime is refused");
2288 assert_eq!(
2289 error.code, "SANDBOX_LIMIT_INVALID",
2290 "{platform} {declared} limits"
2291 );
2292 assert!(
2293 error.to_string().contains("maxLifetimeSeconds"),
2294 "{platform} {declared} limits"
2295 );
2296 }
2297
2298 for platform in [Platform::Azure, Platform::Local] {
2300 let error = sandbox
2301 .validate_for_platform(platform)
2302 .expect_err("a lifetime is refused where nothing applies it");
2303 assert_eq!(
2304 error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2305 "{platform} {declared} limits"
2306 );
2307 }
2308
2309 sandbox.lifecycle.max_lifetime_seconds = Some(1);
2310 sandbox
2311 .validate_for_platform(Platform::Kubernetes)
2312 .expect("one second is the API server's floor");
2313 }
2314 }
2315
2316 #[test]
2320 fn a_lifetime_kubernetes_would_reject_is_refused_while_planning() {
2321 let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2322 let mut without_limits = with_limits.clone();
2323 without_limits.limits = None;
2324
2325 for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2326 for seconds in [2_147_483_648, u32::MAX] {
2327 sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2328 let error = sandbox
2329 .validate_for_platform(Platform::Kubernetes)
2330 .expect_err("a lifetime above what the API server takes is refused");
2331 assert_eq!(
2332 error.code, "SANDBOX_LIMIT_INVALID",
2333 "{seconds}s {declared} limits"
2334 );
2335 assert!(
2336 error.to_string().contains("maxLifetimeSeconds"),
2337 "{seconds}s {declared} limits"
2338 );
2339 }
2340
2341 sandbox.lifecycle.max_lifetime_seconds = Some(2_147_483_647);
2342 sandbox
2343 .validate_for_platform(Platform::Kubernetes)
2344 .expect("the ceiling itself is allowed");
2345 }
2346 }
2347
2348 #[test]
2351 fn an_image_azure_cannot_pull_is_refused_while_planning() {
2352 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2353 sandbox.limits = None;
2356
2357 for image in ["ubuntu@sha256:abc", "", " ", "ubuntu latest", "ubuntu?x"] {
2359 sandbox.code = SandboxCode::Image {
2360 image: image.to_string(),
2361 bundled_from: None,
2362 };
2363 let error = sandbox
2364 .validate_for_platform(Platform::Azure)
2365 .expect_err("an image Azure has nowhere to put is refused");
2366 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "image '{image}'");
2367 }
2368
2369 for image in ["ubuntu", "ubuntu-22.04", "debian_slim"] {
2370 sandbox.code = SandboxCode::Image {
2371 image: image.to_string(),
2372 bundled_from: None,
2373 };
2374 sandbox
2375 .validate_for_platform(Platform::Azure)
2376 .unwrap_or_else(|error| panic!("'{image}' is a catalog name: {error}"));
2377 }
2378
2379 for image in [
2380 "ubuntu:24.04",
2381 "ghcr.io/myorg/sandbox:latest",
2382 "docker.io/library/python:3.14-slim",
2383 "localhost:5000/team/agent@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d",
2384 ] {
2385 sandbox.code = SandboxCode::Image {
2386 image: image.to_string(),
2387 bundled_from: None,
2388 };
2389 sandbox
2390 .validate_for_platform(Platform::Azure)
2391 .unwrap_or_else(|error| panic!("'{image}' is a registry image: {error}"));
2392 }
2393
2394 sandbox.code = SandboxCode::Image {
2396 image: " ubuntu ".to_string(),
2397 bundled_from: None,
2398 };
2399 assert_eq!(
2400 sandbox
2401 .azure_image()
2402 .expect("a padded name is still a name"),
2403 AzureSandboxImage::Catalog("ubuntu")
2404 );
2405 }
2406
2407 #[test]
2411 fn every_value_the_catalog_allowlist_accepted_is_still_a_catalog_name() {
2412 const ALPHABET: &[u8] =
2413 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
2414
2415 let assert_catalog = |value: &str| {
2416 assert_eq!(
2417 classify_azure_sandbox_image(value),
2418 Some(AzureSandboxImage::Catalog(value.trim())),
2419 "'{value}'"
2420 );
2421 };
2422
2423 for a in ALPHABET {
2424 assert_catalog(&String::from_utf8(vec![*a]).unwrap());
2425 for b in ALPHABET {
2426 assert_catalog(&String::from_utf8(vec![*a, *b]).unwrap());
2427 for c in ALPHABET {
2428 assert_catalog(&String::from_utf8(vec![*a, *b, *c]).unwrap());
2429 }
2430 }
2431 }
2432
2433 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
2434 let mut next = || {
2435 state ^= state << 13;
2436 state ^= state >> 7;
2437 state ^= state << 17;
2438 state
2439 };
2440 for _ in 0..20_000 {
2441 let len = 4 + (next() % 60) as usize;
2442 let mut value: String = (0..len)
2443 .map(|_| ALPHABET[(next() % ALPHABET.len() as u64) as usize] as char)
2444 .collect();
2445 if next() % 4 == 0 {
2446 value = format!(" {value}\t");
2447 }
2448 assert_catalog(&value);
2449 }
2450 }
2451
2452 #[test]
2455 fn the_disk_image_label_is_stable_and_label_safe() {
2456 let label = azure_disk_image_label("docker.io/library/python:3.14-slim");
2457 assert_eq!(
2458 label,
2459 azure_disk_image_label(" docker.io/library/python:3.14-slim ")
2460 );
2461 assert_ne!(
2462 label,
2463 azure_disk_image_label("docker.io/library/python:3.13-slim")
2464 );
2465 assert_eq!(label.len(), 32);
2466 assert!(label.chars().all(|c| c.is_ascii_hexdigit()), "{label}");
2467 }
2468
2469 #[test]
2473 fn a_sandbox_deadline_is_accepted_only_where_the_platform_applies_it() {
2474 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2475 sandbox.lifecycle.max_lifetime_seconds = Some(3600);
2476
2477 sandbox
2478 .validate_for_platform(Platform::Kubernetes)
2479 .expect("the kubelet enforces activeDeadlineSeconds");
2480 sandbox
2481 .validate_for_platform(Platform::Aws)
2482 .expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
2483
2484 for platform in [Platform::Azure, Platform::Local] {
2485 let error = sandbox
2486 .validate_for_platform(platform)
2487 .expect_err("a deadline nothing applies must be refused");
2488 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2489 }
2490 }
2491
2492 #[test]
2496 fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
2497 let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2498 let tier = sandbox
2499 .microvm_tier()
2500 .expect("2Gi/1cpu/20Gi is satisfiable");
2501
2502 assert_eq!(
2503 tier.peak_memory_mib, 2048,
2504 "the peak is the declared ceiling"
2505 );
2506 assert_eq!(
2507 tier.baseline_memory_mib, 512,
2508 "which is a quarter of it as the baseline"
2509 );
2510 assert!(tier.max_disk_mib <= 20 * 1024);
2511 }
2512
2513 #[test]
2517 fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
2518 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2519 {
2520 let limits = sandbox
2521 .limits
2522 .as_mut()
2523 .expect("the fixture declares limits");
2524 limits.cpu = "1".to_string();
2525 limits.memory = "8Gi".to_string();
2526 }
2527
2528 let error = sandbox
2529 .microvm_tier()
2530 .expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
2531 assert!(
2532 error.to_string().contains("4 vCPU"),
2533 "the refusal must say what the memory ceiling implies: {error}"
2534 );
2535
2536 sandbox
2537 .limits
2538 .as_mut()
2539 .expect("the fixture declares limits")
2540 .cpu = "4".to_string();
2541 let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
2542 assert_eq!(tier.peak_memory_mib, 8192);
2543 }
2544
2545 #[test]
2548 fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
2549 let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2550 sandbox
2551 .limits
2552 .as_mut()
2553 .expect("the fixture declares limits")
2554 .memory = "1Gi".to_string();
2555
2556 let error = sandbox
2557 .validate_for_platform(Platform::Aws)
2558 .expect_err("no MicroVM size peaks at or below 1Gi");
2559 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2560 assert!(
2561 error.to_string().contains("2Gi"),
2562 "the refusal must say what the smallest holdable ceiling is: {error}"
2563 );
2564 }
2565
2566 #[test]
2569 fn source_code_is_refused_where_no_backend_builds_it() {
2570 let sandbox = Sandbox::new("agent".to_string())
2571 .code(SandboxCode::Source {
2572 src: "./sandbox".to_string(),
2573 toolchain: ToolchainConfig::Docker {
2574 dockerfile: None,
2575 build_args: None,
2576 target: None,
2577 },
2578 })
2579 .egress(SandboxEgress::None)
2580 .lifecycle(SandboxLifecyclePolicy {
2581 max_lifetime_seconds: None,
2582 idle_pause_seconds: None,
2583 })
2584 .build();
2585
2586 sandbox
2587 .validate_for_platform(Platform::Aws)
2588 .expect("an AWS sandbox base image is built by `alien build`");
2589 sandbox
2590 .validate_for_platform(Platform::Azure)
2591 .expect("an Azure sandbox base image is built by `alien build`");
2592 sandbox
2593 .validate_for_platform(Platform::Gcp)
2594 .expect("a GCP sandbox base image is built by `alien build`");
2595
2596 for platform in [Platform::Kubernetes, Platform::Local] {
2597 let error = sandbox
2598 .validate_for_platform(platform)
2599 .expect_err("no backend builds a sandbox image from source here");
2600 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2601 assert!(
2602 error.to_string().contains("code.image"),
2603 "the refusal must say what to write instead: {error}"
2604 );
2605 assert!(
2606 error.to_string().contains(&platform.to_string()),
2607 "the refusal must name the platform that cannot build it: {error}"
2608 );
2609 }
2610 }
2611
2612 #[test]
2615 fn every_accepted_unit_converts_rather_than_falling_back() {
2616 assert_eq!(quantity_mib("2Gi"), Some(2048));
2617 assert_eq!(quantity_mib("512Mi"), Some(512));
2618 assert_eq!(quantity_mib("4G"), Some(3814));
2619 assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
2620 assert_eq!(millicores("1"), Some(1000));
2621 assert_eq!(millicores("500m"), Some(500));
2622 }
2623
2624 #[test]
2625 fn privileged_supervisor_fixes_identity_and_requires_an_enforceable_backend() {
2626 let mut sandbox = sandbox_with(
2627 SandboxEgress::AllowDomains {
2628 domains: vec!["example.com".to_string()],
2629 },
2630 vec![],
2631 );
2632 sandbox.privileged_supervisor = Some(SandboxPrivilegedSupervisor { command_uid: 60001 });
2633 sandbox
2634 .validate_for_platform(Platform::Aws)
2635 .expect("AWS can enforce the policy in the agent");
2636 assert_eq!(sandbox.cloud_egress(), &SandboxEgress::Allow);
2637 assert_eq!(
2638 sandbox.supervisor_environment()["ALIEN_SANDBOX_EXPECTED_EXEC_UID"],
2639 "60001"
2640 );
2641 for platform in [
2642 Platform::Local,
2643 Platform::Kubernetes,
2644 Platform::Azure,
2645 Platform::Gcp,
2646 ] {
2647 let error = sandbox
2648 .validate_for_platform(platform)
2649 .expect_err("cannot grant a privilege boundary the backend lacks");
2650 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2651 assert!(error.message.contains("privilegedSupervisor"));
2652 }
2653 for uid in [0, u32::MAX] {
2654 sandbox.privileged_supervisor.as_mut().unwrap().command_uid = uid;
2655 let error = sandbox
2656 .validate_for_platform(Platform::Aws)
2657 .expect_err("invalid uid must fail at plan time");
2658 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2659 }
2660 }
2661
2662 #[test]
2663 fn unknown_fields_are_rejected() {
2664 let json = r#"{
2665 "id": "sbx",
2666 "code": {"type": "image", "image": "ubuntu:24.04"},
2667 "limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
2668 "egress": {"mode": "deny"},
2669 "lifecycle": {},
2670 "unexpected": true
2671 }"#;
2672
2673 serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
2674 }
2675
2676 #[test]
2677 fn serialization_roundtrips() {
2678 let sandbox = sandbox_with(
2679 SandboxEgress::AllowDomains {
2680 domains: vec!["example.com".to_string()],
2681 },
2682 vec![8080, 9090],
2683 );
2684
2685 let json = serde_json::to_string(&sandbox).expect("serializes");
2686 let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
2687 assert_eq!(sandbox, restored);
2688 }
2689
2690 #[test]
2691 fn id_is_immutable_across_updates() {
2692 let original = sandbox_with(SandboxEgress::None, vec![]);
2693 let renamed = Sandbox::new("other".to_string())
2694 .code(SandboxCode::Image {
2695 image: "ubuntu".to_string(),
2696 bundled_from: None,
2697 })
2698 .limits(
2699 original
2700 .limits
2701 .clone()
2702 .expect("the fixture declares limits"),
2703 )
2704 .egress(SandboxEgress::None)
2705 .lifecycle(SandboxLifecyclePolicy {
2706 max_lifetime_seconds: None,
2707 idle_pause_seconds: None,
2708 })
2709 .build();
2710
2711 original
2712 .validate_update(&original.clone())
2713 .expect("an unchanged config is a valid update");
2714 original
2715 .validate_update(&renamed)
2716 .expect_err("renaming a sandbox is not an update");
2717 }
2718
2719 #[test]
2725 fn azure_takes_an_idle_policy_and_still_refuses_a_lifetime_ceiling() {
2726 let with_policy = |lifecycle: SandboxLifecyclePolicy| {
2727 Sandbox::new("sbx".to_string())
2728 .code(SandboxCode::Image {
2729 image: "ubuntu".to_string(),
2730 bundled_from: None,
2731 })
2732 .egress(SandboxEgress::Allow)
2733 .lifecycle(lifecycle)
2734 .build()
2735 .validate_for_platform(Platform::Azure)
2736 };
2737
2738 with_policy(SandboxLifecyclePolicy {
2739 max_lifetime_seconds: None,
2740 idle_pause_seconds: Some(900),
2741 })
2742 .expect("Azure pauses a sandbox on idle");
2743
2744 let error = with_policy(SandboxLifecyclePolicy {
2745 max_lifetime_seconds: Some(3600),
2746 idle_pause_seconds: None,
2747 })
2748 .expect_err("Azure has no wall-clock ceiling to enforce one with");
2749 assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2750 assert!(
2751 error.message.contains("sandboxLifetime"),
2752 "names the capability: {}",
2753 error.message
2754 );
2755 }
2756
2757 #[test]
2763 fn an_allowlist_with_no_domains_is_refused() {
2764 let declared = |domains: Vec<String>| {
2765 Sandbox::new("sbx".to_string())
2766 .code(SandboxCode::Image {
2767 image: "ubuntu".to_string(),
2768 bundled_from: None,
2769 })
2770 .egress(SandboxEgress::AllowDomains { domains })
2771 .lifecycle(SandboxLifecyclePolicy {
2772 max_lifetime_seconds: None,
2773 idle_pause_seconds: None,
2774 })
2775 .build()
2776 .validate_for_platform(Platform::Azure)
2777 };
2778
2779 let error = declared(vec![]).expect_err("an empty allowlist must be refused");
2780 assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2781
2782 declared(vec!["api.example.com".to_string()])
2783 .expect("a named domain is what an allowlist is for");
2784 }
2785
2786 #[test]
2789 fn internet_access_switch_maps_only_the_two_expressible_modes() {
2790 assert_eq!(SandboxEgress::Allow.internet_access_switch(), Some(true));
2791 assert_eq!(SandboxEgress::None.internet_access_switch(), Some(false));
2792 assert_eq!(
2793 SandboxEgress::AllowDomains {
2794 domains: vec!["api.example.com".to_string()]
2795 }
2796 .internet_access_switch(),
2797 None,
2798 "a host list has no boolean and must not be approximated"
2799 );
2800 }
2801
2802 #[test]
2806 fn stack_state_written_before_the_lifecycle_rename_still_reads() {
2807 let stored: crate::StackResourceState = serde_json::from_value(serde_json::json!({
2808 "type": "sandbox",
2809 "config": {
2810 "id": "sandbox",
2811 "code": {
2812 "type": "image",
2813 "image": "s3://example-bundles/analysis/v1/bundle.zip"
2814 },
2815 "type": "sandbox",
2816 "egress": { "mode": "allow" },
2817 "session": { "maxLifetimeSeconds": 28800, "idleSuspendSeconds": 600 }
2818 },
2819 "status": "running",
2820 "outputs": {
2821 "type": "sandbox",
2822 "identifier": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox",
2823 "parentName": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox"
2824 },
2825 "lifecycle": "frozen",
2826 "dependencies": [
2827 { "id": "management", "type": "remote-stack-management" },
2828 { "id": "access", "type": "resource-access" }
2829 ],
2830 "controllerPlatform": "aws"
2831 }))
2832 .expect("a stack state written before the rename must still deserialize");
2833
2834 let expected = Sandbox::new("sandbox".to_string())
2835 .code(SandboxCode::Image {
2836 image: "s3://example-bundles/analysis/v1/bundle.zip".to_string(),
2837 bundled_from: None,
2838 })
2839 .egress(SandboxEgress::Allow)
2840 .lifecycle(SandboxLifecyclePolicy {
2841 max_lifetime_seconds: Some(28_800),
2842 idle_pause_seconds: Some(600),
2843 })
2844 .build();
2845 assert_eq!(stored.config.downcast_ref::<Sandbox>(), Some(&expected));
2846
2847 let rewritten = serde_json::to_value(&stored.config).expect("the sandbox serializes");
2848 assert_eq!(
2849 rewritten["lifecycle"],
2850 serde_json::json!({ "maxLifetimeSeconds": 28800, "idlePauseSeconds": 600 }),
2851 "the next write stores the current names"
2852 );
2853 assert!(rewritten.get("session").is_none());
2854 }
2855}