Skip to main content

alien_core/resources/
sandbox.rs

1//! Sandbox resource for running untrusted code in an isolated environment.
2//!
3//! The declaration provisions a durable parent, and the application creates and destroys
4//! individual sandboxes through its binding at runtime.
5//!
6//! The capability set differs per platform and is published rather than assumed. Calling an
7//! unsupported capability is a typed error naming both the platform and the capability, so a
8//! portable application can branch on `SandboxCapabilities` before it calls.
9
10use 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/// Specifies where the sandbox's root filesystem comes from.
22#[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    /// A prebuilt container image used as the sandbox root filesystem.
27    #[serde(rename_all = "camelCase")]
28    Image {
29        /// Image reference (e.g. `ubuntu:24.04`, `ghcr.io/myorg/sandbox:latest`). AWS wants an
30        /// `s3://` bundle; Azure takes a catalog name such as `ubuntu` or an amd64 registry
31        /// image, told apart by syntax. Each refuses what it cannot take while planning.
32        image: String,
33        /// The container image a publisher built the `s3://` bundle in `image` from. An AWS
34        /// deployment with a bundle Storage of its own renders its bundle from this image; one
35        /// whose setup granted the publisher's store builds from `image`. Set by a publisher,
36        /// never by authoring. Kept inside `code` so a controller that predates it ignores it.
37        #[serde(default, skip_serializing_if = "Option::is_none")]
38        #[cfg_attr(feature = "openapi", schema(ignore))]
39        bundled_from: Option<String>,
40    },
41    /// A Dockerfile `alien build` builds into the sandbox's base image.
42    ///
43    /// AWS, Azure and GCP, and docker only: the base image is a root filesystem, not a binary laid
44    /// on one. `alien release` pushes it; on AWS the bundle layers the sandbox agent on afterwards,
45    /// and on GCP the release layers it on and pushes the result.
46    #[serde(rename_all = "camelCase")]
47    Source {
48        /// The source directory to build from
49        src: String,
50        /// Toolchain configuration with type-safe options
51        toolchain: ToolchainConfig,
52    },
53}
54
55/// Hard ceilings enforced on a sandbox.
56///
57/// These are limits, not scheduling requests. Untrusted code does not respect a hint, so every
58/// field is enforced by the platform and a platform that cannot enforce one is rejected at plan
59/// time rather than silently ignoring it.
60#[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    /// CPU ceiling in cores or millicores (e.g. `"1"`, `"500m"`)
65    pub cpu: String,
66    /// Memory ceiling (e.g. `"2Gi"`, `"512Mi"`)
67    pub memory: String,
68    /// Disk ceiling (e.g. `"20Gi"`)
69    pub disk: String,
70    /// Maximum number of processes, which bounds fork bombs.
71    ///
72    /// Optional because only a container runtime has the primitive: Kubernetes sets a pid ceiling
73    /// per node, not per pod, and neither AWS MicroVMs nor Azure sandboxes expose one. Declaring
74    /// it on a platform that cannot apply it is refused at plan time.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub max_processes: Option<u32>,
77}
78
79/// One of the five sizes a Lambda MicroVM can be built at.
80///
81/// AWS has no ceiling knob: `minimumMemoryInMiB` sets a *baseline* and a running MicroVM bursts
82/// vertically to four times it with no way to opt out. A declared ceiling is therefore honoured by
83/// picking the tier whose **peak** stays inside it, not the tier whose baseline matches it.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct MicrovmTier {
86    /// What `minimumMemoryInMiB` is set to.
87    pub baseline_memory_mib: i64,
88    /// The most memory the MicroVM can reach, in MiB.
89    pub peak_memory_mib: i64,
90    /// The most vCPU the MicroVM can reach.
91    pub peak_vcpu: u32,
92    /// The most disk the MicroVM can use, in MiB.
93    pub max_disk_mib: i64,
94}
95
96/// The published sizes, smallest first. Baseline memory to vCPU is 2 GB per vCPU, peak is four
97/// times baseline, and disk is fixed per tier rather than independently selectable.
98/// Longest life AWS will run a MicroVM for, from `RunMicrovm`'s `maximumDurationInSeconds`.
99const AWS_MAX_LIFETIME_SECONDS: u32 = 28_800;
100
101/// Longest `activeDeadlineSeconds` the Kubernetes API server accepts on a pod. The field is an
102/// int64, but pod validation caps it at the largest i32.
103const KUBERNETES_MAX_LIFETIME_SECONDS: u32 = i32::MAX as u32;
104
105/// Azure's sandbox sizing rule, quoted from the data plane's own refusal of an oversized request:
106/// *CPU must be n×250m for n=1..64 (0.25–16 cores); Memory ≤ cores × 2Gi; Disk ≤ cores × 20Gi*.
107const 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, non_public_ipv4_ranges, EgressPolicy};
146
147/// Outbound policy. Only the new Internet value opts into gateway enforcement.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum SandboxEgress {
150    None,
151    Internet,
152    /// Deprecated direct backend access, unchanged from released deployments.
153    Allow,
154    /// Deprecated backend hostname allowlist, unchanged from released deployments.
155    AllowDomains {
156        domains: Vec<String>,
157    },
158}
159
160/// Deprecated object declarations preserve their released backend behavior.
161#[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    /// Deprecated alias of "none".
166    Deny,
167    /// Deprecated direct backend access. Use "internet" to opt into the gateway,
168    /// fixed outbound IP, connection logs and per-sandbox runtime policies.
169    Allow,
170    /// Deprecated backend hostname rules. Use "internet" and runtime policies
171    /// to opt into gateway enforcement instead.
172    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    /// Deprecated spelling retained for Rust callers of the released API.
241    #[allow(non_upper_case_globals)]
242    #[deprecated(note = "use SandboxEgress::None")]
243    pub const Deny: Self = Self::None;
244
245    /// Backend switch; hostname rules must be handled by a backend matcher.
246    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
255/// Per-session deadline metadata read by the external lifecycle reaper.
256pub const SANDBOX_EXPIRY_LABEL: &str = "alienExpiresAtMs";
257
258/// Azure gateway identities cannot renew without an in-guest agent.
259pub const AZURE_GATEWAY_MAX_LIFETIME_SECONDS: u32 = 24 * 60 * 60;
260
261/// How long a sandbox may live and when it is paused.
262///
263/// Declaration-time ceilings, not per-request values: every sandbox created through this
264/// declaration's binding is held to them, whatever a caller asks for at runtime.
265#[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    /// Wall-clock ceiling on a single sandbox, after which the platform terminates it.
270    ///
271    /// Optional because not every backend has the primitive: Kubernetes has
272    /// `activeDeadlineSeconds` and AWS `maximumDurationInSeconds`, while neither Azure nor Local
273    /// expose one, so declaring a ceiling there is refused at plan time rather than accepted and
274    /// never applied. AWS caps it at 8 hours.
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub max_lifetime_seconds: Option<u32>,
277    /// Idle period after which the sandbox is paused, where the platform supports it.
278    ///
279    /// Stored state written before the rename calls this `idleSuspendSeconds`.
280    #[serde(alias = "idleSuspendSeconds", skip_serializing_if = "Option::is_none")]
281    pub idle_pause_seconds: Option<u32>,
282}
283
284/// What a platform's sandbox backend can actually do.
285///
286/// Published so portable code can branch before calling rather than discovering a gap through
287/// an error. Every field here corresponds to a capability that at least one platform lacks;
288/// create, exec and terminate are the guaranteed floor and are therefore not listed.
289#[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    /// Files can be moved in and out of a sandbox
294    pub files: bool,
295    /// A later call can reach a sandbox created by an earlier one
296    pub reconnect: bool,
297    /// A command can be started, polled and cancelled across separate calls, so it outlives the
298    /// one that started it. False where nothing inside the sandbox owns the process in between.
299    pub jobs: bool,
300    /// A running command takes input on stdin, can be signalled, and streams its output as it is
301    /// written, so a caller can drive a REPL, a language server or a tool protocol over it.
302    pub interactive_commands: bool,
303    /// An authenticated, port-scoped capability to reach a service inside the sandbox
304    pub preview: bool,
305    /// Sandbox state can be paused and resumed
306    pub pause_resume: bool,
307    /// A sandbox's full state can be captured and used to create another
308    pub snapshot: bool,
309    /// Egress can be restricted to a hostname allowlist
310    pub domain_egress_rules: bool,
311    /// Whether a declared `deny` is actually enforced, rather than accepted and dropped.
312    /// It covers routed traffic; the `deny` mode says where DNS still resolves.
313    pub egress_deny: bool,
314    /// The platform enforces the declared cpu, memory and disk ceilings
315    pub enforced_limits: bool,
316    /// The platform can cap how many processes a sandbox runs
317    pub process_limit: bool,
318    /// The platform terminates a sandbox at a declared wall-clock deadline
319    pub sandbox_lifetime: bool,
320    /// A command runs in its own PID namespace and cannot see or signal the agent's processes.
321    ///
322    /// Only where an agent runs as root. Creating the namespace needs `CAP_SYS_ADMIN`, and the
323    /// Kubernetes sandbox pod drops every capability — which is also what denies `ptrace` by
324    /// construction, so granting it there would remove a lock to add one.
325    pub supervisor_pid_namespace: bool,
326    /// The process supervising a command is a different identity from the command.
327    ///
328    /// False where a command runs as the agent's own user: it can then read the supervisor's
329    /// environment and signal it. Separate from `supervisorPidNamespace`, which is about
330    /// visibility rather than identity — a backend can have one without the other.
331    pub supervisor_isolation: bool,
332}
333
334impl SandboxCapabilities {
335    /// Returns what the given platform's sandbox backend supports.
336    ///
337    /// Errors for platforms with no sandbox backend, rather than returning an all-false set —
338    /// "every capability is missing" and "this platform has no sandboxes" are different
339    /// conditions and an application should not have to tell them apart by inspection.
340    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                // The in-guest agent owns the process and its pipes, and the MicroVM proxy
347                // streams a response while separate requests carry input and signals.
348                interactive_commands: true,
349                preview: true,
350                pause_resume: true,
351                snapshot: false,
352                domain_egress_rules: false,
353                // Routed egress only: while the connector VPC has DNS support on, a session
354                // resolves names through its resolver, which no security group filters.
355                egress_deny: true,
356                enforced_limits: true,
357                // Nothing in the API bounds process count.
358                process_limit: false,
359                // `maximumDurationInSeconds` on `RunMicrovm`, which Lambda enforces by
360                // terminating the MicroVM. Capped at 8 hours by the service.
361                sandbox_lifetime: true,
362                // Measured, not assumed: the agent inside a Lambda MicroVM runs as uid 0 with
363                // `CapEff: 00000000a80425fb`, the standard container default set, which excludes
364                // `CAP_SYS_ADMIN`. It can drop privilege (`CAP_SETUID`/`CAP_SETGID` are held) and
365                // it cannot create a namespace. No backend offers this today.
366                supervisor_pid_namespace: false,
367                // The agent runs as uid 0 and `setuid`s the command to uid 60000, so the command
368                // runs under a different identity than the process supervising it.
369                supervisor_isolation: true,
370            }),
371            Platform::Azure => Ok(Self::azure()),
372            Platform::Gcp => Ok(Self::gcp_agent_platform()),
373            Platform::Kubernetes => Ok(Self {
374                files: true,
375                reconnect: true,
376                jobs: true,
377                // The pod runs the same agent and the client drives its `/v1/interactive` stream
378                // through the shared agent-protocol module. The client asks the broker for a new
379                // capability before the one it holds expires, so a command outlives any single
380                // capability.
381                interactive_commands: true,
382                // In-cluster callers (workloads that link the sandbox) only; external preview is
383                // not yet supported. `preview` returns the sandbox agent's in-cluster URL and a
384                // bearer capability for one declared port of one session. The agent checks the
385                // capability against its own pod and forwards to 127.0.0.1 on that port, so the
386                // port is reachable by nothing else, and the agent's own port never is.
387                preview: true,
388                // Nitro Sandboxes, gVisor and Kata pods cannot checkpoint a running pod, so a
389                // paused session would lose its state. `resume` on a running sandbox is a no-op.
390                pause_resume: false,
391                // The same reason: there is no way to capture a pod's filesystem and memory.
392                snapshot: false,
393                domain_egress_rules: false,
394                egress_deny: true,
395                enforced_limits: true,
396                // A pid ceiling is a kubelet setting per node (`podPidsLimit`), not a pod field,
397                // and the agent does not apply `RLIMIT_NPROC` because that counts every process
398                // of the uid, the agent's own threads included. `maxProcesses` is refused with
399                // `SANDBOX_CAPABILITY_UNSUPPORTED` rather than accepted and ignored.
400                process_limit: false,
401                // A create may name `timeoutMs` up to the declared `maxLifetimeSeconds`. The broker
402                // records the deadline on the pod at the claim and the Operator ends the session
403                // at it. The kubelet's `activeDeadlineSeconds` is not used: it counts from the
404                // pod's start, so an idle pool pod would spend a session's time before it was
405                // claimed.
406                sandbox_lifetime: true,
407                // The pod drops every capability, including the `CAP_SYS_ADMIN` the agent would
408                // need to unshare. That is also what denies `ptrace`, so this stays false rather
409                // than the pod being weakened to make it true.
410                supervisor_pid_namespace: false,
411                // The pod runs as the image's one non-root user with `capabilities.drop: [ALL]`
412                // and `allow_privilege_escalation: false`, so no process can setuid to split the
413                // command off from a supervisor. No uid split is possible, so none exists.
414                supervisor_isolation: false,
415            }),
416            Platform::Local => Ok(Self {
417                files: true,
418                reconnect: true,
419                // Nothing runs inside the sandbox: the manager drives Docker from outside it.
420                jobs: false,
421                // The manager holds the exec's attached stdin for as long as the output stream
422                // is open, so an interactive command needs nothing inside the sandbox.
423                interactive_commands: true,
424                preview: true,
425                pause_resume: false,
426                snapshot: false,
427                domain_egress_rules: false,
428                egress_deny: true,
429                enforced_limits: true,
430                // Docker's `--pids-limit`.
431                process_limit: true,
432                sandbox_lifetime: false,
433                // Local has no in-sandbox agent: the manager drives Docker from outside, so
434                // there is no supervisor inside the sandbox to isolate from.
435                supervisor_pid_namespace: false,
436                // The supervisor is the manager on the host, outside the container entirely, and
437                // `docker exec` runs the command as the workload uid — a different identity by
438                // construction.
439                supervisor_isolation: true,
440            }),
441            Platform::Machines | Platform::Test => {
442                Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
443                    platform: platform.to_string(),
444                }))
445            }
446        }
447    }
448
449    /// What the Azure sandbox backend supports; the body of the `Platform::Azure` arm.
450    pub fn azure() -> Self {
451        Self {
452            files: true,
453            reconnect: true,
454            // No Alien process runs inside the sandbox to own a command between two calls.
455            jobs: false,
456            // Not claimed: the agent-mode client does not drive the agent's interactive routes
457            // yet, and the platform's own exec takes no stdin.
458            interactive_commands: false,
459            // A sandbox port carries a URL and an auth config, and the auth config offers two
460            // things: anonymous, or Entra ID with an allowlist of human email addresses.
461            // Neither is a credential scoped to a port for a fixed time, which is what a
462            // preview capability is. Returning the anonymous URL would publish the port.
463            preview: false,
464            pause_resume: true,
465            // False for a client reason, not a cloud one: this client has no snapshot call, and
466            // `CreateSandboxRequest` has no field to consume the id it would return. Also
467            // unclaimed: Microsoft does not garbage-collect snapshots, so an id is a bill that grows.
468            snapshot: false,
469            domain_egress_rules: true,
470            egress_deny: true,
471            // Enforced inside the sandbox, not at create: an over-allocation raises `MemoryError`
472            // while the sandbox keeps running. `azure_sandbox_limits` checks the continuous
473            // sizing rule at plan time instead of matching a tier.
474            enforced_limits: true,
475            process_limit: false,
476            // Auto-suspend and auto-delete exist; a wall-clock ceiling does not. Accepting
477            // `maxLifetimeSeconds` here would be the silent no-op the capability set exists
478            // to prevent, so this is a decision rather than a gap.
479            sandbox_lifetime: false,
480            // No Alien process inside an Azure sandbox, so there is no supervisor to isolate.
481            supervisor_pid_namespace: false,
482            // No Alien process runs the command at all — the platform's own data plane does,
483            // so there is no separate supervisor identity to speak of.
484            supervisor_isolation: false,
485        }
486    }
487
488    /// What the GCP Agent Platform sandbox backend supports; the body of the `Platform::Gcp` arm.
489    pub fn gcp_agent_platform() -> Self {
490        Self {
491            // Agent file operations move over the sandbox envelope.
492            files: true,
493            // Reaching a sandbox across processes is safe because `generation` is derived from the
494            // container boot id read through the agent's health op, so a caller detects a container
495            // replaced under a stable sandbox name rather than reconnecting to a blank one.
496            reconnect: true,
497            jobs: true,
498            // `:execute` is one request with one answer, capped at about 30 seconds. Input
499            // cannot reach a command after its call has answered, so there is no stream to drive.
500            interactive_commands: false,
501            // No method mints a port-scoped ingress capability; the only ingress is `:execute`.
502            preview: false,
503            // `:resume` can return a fresh container while reporting success, so a pause does not
504            // keep the sandbox's state.
505            pause_resume: false,
506            // The create path never sends `sandbox_environment_snapshot`, so no sandbox state is
507            // reachable through the trait; declared false until the client carries it.
508            snapshot: false,
509            // Egress is shaped by VPC and DNS peering, which is not a hostname allowlist.
510            domain_egress_rules: false,
511            // A declared `deny` blocks both routed egress and DNS.
512            egress_deny: true,
513            // The declared ceilings are enforced, but by terminating the sandbox on breach rather
514            // than by refusing the allocation — a caller reading `true` should expect the sandbox
515            // to die, not a clean error at the point of the request.
516            enforced_limits: true,
517            // No ceiling on process count is observed.
518            process_limit: false,
519            // `ttl` maps to a sandbox `expireTime` the platform terminates at.
520            sandbox_lifetime: true,
521            // No PID-namespace isolation between the command and anything supervising it.
522            supervisor_pid_namespace: false,
523            // No separate supervisor identity: the command is not run under a different identity
524            // than the process supervising it.
525            supervisor_isolation: false,
526        }
527    }
528
529    /// Returns a typed error if the named capability is absent on this platform.
530    pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
531        let available = match capability {
532            SandboxCapability::Files => self.files,
533            SandboxCapability::Reconnect => self.reconnect,
534            SandboxCapability::Jobs => self.jobs,
535            SandboxCapability::InteractiveCommands => self.interactive_commands,
536            SandboxCapability::Preview => self.preview,
537            SandboxCapability::PauseResume => self.pause_resume,
538            SandboxCapability::Snapshot => self.snapshot,
539            SandboxCapability::DomainEgressRules => self.domain_egress_rules,
540            SandboxCapability::EgressDeny => self.egress_deny,
541            SandboxCapability::EnforcedLimits => self.enforced_limits,
542            SandboxCapability::ProcessLimit => self.process_limit,
543            SandboxCapability::SandboxLifetime => self.sandbox_lifetime,
544            SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
545            SandboxCapability::SupervisorIsolation => self.supervisor_isolation,
546        };
547
548        if available {
549            return Ok(());
550        }
551
552        Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
553            capability: capability.as_str().to_string(),
554            platform: platform.to_string(),
555        }))
556    }
557}
558
559/// Names a single sandbox capability, so an unsupported call can report which one it needed.
560#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
561#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
562#[serde(rename_all = "camelCase")]
563pub enum SandboxCapability {
564    /// Moving files in and out of a sandbox
565    Files,
566    /// Reaching a sandbox created by an earlier call
567    Reconnect,
568    /// Starting, polling and cancelling a command across separate calls
569    Jobs,
570    /// Writing to, signalling and streaming a running command
571    InteractiveCommands,
572    /// An authenticated, port-scoped ingress capability
573    Preview,
574    /// Pausing and resuming sandbox state
575    PauseResume,
576    /// Capturing full sandbox state
577    Snapshot,
578    /// Restricting egress to a hostname allowlist
579    DomainEgressRules,
580    /// Refusing outbound access when a sandbox declares none
581    EgressDeny,
582    /// Platform-enforced resource ceilings
583    EnforcedLimits,
584    /// A ceiling on the number of processes a sandbox may run
585    ProcessLimit,
586    /// A wall-clock ceiling on a sandbox, applied by the platform rather than by a caller
587    SandboxLifetime,
588    /// A command runs in its own PID namespace, isolated from the agent supervising it
589    SupervisorPidNamespace,
590    /// A command runs under a different identity than the process supervising it
591    SupervisorIsolation,
592}
593
594impl SandboxCapability {
595    /// Returns the stable identifier used in errors and capability queries.
596    pub fn as_str(&self) -> &'static str {
597        match self {
598            Self::Files => "files",
599            Self::Reconnect => "reconnect",
600            Self::Jobs => "jobs",
601            Self::InteractiveCommands => "interactiveCommands",
602            Self::Preview => "preview",
603            Self::PauseResume => "pauseResume",
604            Self::Snapshot => "snapshot",
605            Self::DomainEgressRules => "domainEgressRules",
606            Self::EgressDeny => "egressDeny",
607            Self::EnforcedLimits => "enforcedLimits",
608            Self::ProcessLimit => "processLimit",
609            Self::SandboxLifetime => "sandboxLifetime",
610            Self::SupervisorPidNamespace => "supervisorPidNamespace",
611            Self::SupervisorIsolation => "supervisorIsolation",
612        }
613    }
614}
615
616/// Opt-in supervisor-owned network enforcement. Caller requests cannot change this identity.
617#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
618#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
619#[serde(rename_all = "camelCase", deny_unknown_fields)]
620pub struct SandboxPrivilegedSupervisor {
621    /// Nonzero numeric uid and primary gid for every command, including the image entrypoint.
622    pub command_uid: u32,
623}
624
625/// An isolated environment for running untrusted code, created at runtime.
626#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
627#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
628#[serde(rename_all = "camelCase", deny_unknown_fields)]
629#[builder(start_fn = new)]
630pub struct Sandbox {
631    /// Identifier for the sandbox. Must be DNS-compatible: lowercase letters, digits and hyphens,
632    /// starting and ending with a letter or digit, with no consecutive hyphens.
633    #[builder(start_fn)]
634    pub id: String,
635    /// Runtime network links authored by preflight, not parent lifecycle dependencies.
636    /// Sandbox has no public link builder; gateway reach is wired during planning.
637    #[builder(field)]
638    #[serde(default, skip_serializing_if = "Vec::is_empty")]
639    #[cfg_attr(feature = "openapi", schema(ignore))]
640    pub links: Vec<ResourceRef>,
641    /// Where the sandbox's root filesystem comes from
642    pub code: SandboxCode,
643    /// Original image uid resolved from the built OCI archives. Absent on released artifacts
644    /// that retain the legacy boot contract. This is build output, not an authoring option.
645    #[builder(skip)]
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    #[cfg_attr(feature = "openapi", schema(ignore))]
648    pub image_user: Option<u32>,
649    /// Private ECR base image an AWS build pulls; `code.image` names only the S3 bundle, so this is
650    /// what the cross-account grant opens. Live only: the grant needs the customer account,
651    /// which registration reports. Absent means the base image is pulled anonymously.
652    #[serde(skip_serializing_if = "Option::is_none")]
653    pub private_base_image: Option<String>,
654    /// Enforced resource ceilings.
655    ///
656    /// Optional because not every platform can enforce them, and a declaration that names none
657    /// takes the platform's own defaults. Naming them on a platform that cannot enforce them is
658    /// rejected at plan time rather than silently ignored.
659    #[serde(skip_serializing_if = "Option::is_none")]
660    pub limits: Option<SandboxLimits>,
661    /// Outbound network policy
662    pub egress: SandboxEgress,
663    /// Default runtime policy for creates that omit one.
664    #[serde(default, skip_serializing_if = "Option::is_none")]
665    pub default_policy: Option<EgressPolicy>,
666    /// Have Alien's agent install the declared egress policy before running any image code.
667    /// Unsupported backends refuse this at plan time.
668    // Keep released declarations readable without offering a new authoring knob.
669    #[builder(skip)]
670    #[serde(default, skip_serializing_if = "Option::is_none")]
671    pub privileged_supervisor: Option<SandboxPrivilegedSupervisor>,
672    /// Sandbox lifetime ceiling and idle behaviour.
673    ///
674    /// Stored state written before the rename calls this `session`. A stack state or release
675    /// that old must stay readable, otherwise its deployment can no longer be updated or deleted.
676    #[serde(alias = "session")]
677    pub lifecycle: SandboxLifecyclePolicy,
678    /// Ports eligible for a preview capability. An application reaches its sandbox through the
679    /// provider, so it cannot widen its own ingress at runtime; a holder of a remote binding's
680    /// credentials is bounded by no port condition, which is why a remote sandbox declares none.
681    #[builder(default)]
682    #[serde(default, skip_serializing_if = "Vec::is_empty")]
683    pub preview_ports: Vec<u16>,
684}
685
686/// Whether the artifact being rendered restricts which network modes it accepts.
687///
688/// Cloud setup needs explicit subnets for restricted sandbox connectors. Kubernetes targets do
689/// not emit these cloud backends.
690pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
691    !targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
692}
693
694/// Whether any setup-owned resource forces setup to name subnets.
695///
696/// Restricted sandbox connectors require subnet IDs. Callers rendering an artifact want
697/// [`restricts_network_mode`] instead:
698/// this one answers for the declaration, which on a Kubernetes target is not what gets emitted.
699pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
700    stack.resources().any(|(_, entry)| {
701        entry
702            .config
703            .downcast_ref::<Sandbox>()
704            .is_some_and(|sandbox| crate::sandbox_egress::sandbox_needs_connector(stack, sandbox))
705    })
706}
707
708impl Sandbox {
709    pub(crate) fn setup_digest_value(&self) -> serde_json::Value {
710        match &self.egress {
711            SandboxEgress::None => serde_json::json!({"mode":"deny"}),
712            value => serde_json::to_value(value).expect("egress serializes"),
713        }
714    }
715
716    /// The resource type identifier for Sandbox
717    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
718
719    /// Returns the sandbox's unique identifier.
720    pub fn id(&self) -> &str {
721        &self.id
722    }
723
724    /// Released supervisor declarations retain their direct cloud route; only
725    /// the new Internet declaration uses the deployment gateway.
726    pub fn cloud_egress(&self) -> &SandboxEgress {
727        if self.privileged_supervisor.is_some() && self.egress != SandboxEgress::Internet {
728            &SandboxEgress::Allow
729        } else {
730            &self.egress
731        }
732    }
733
734    /// Startup contract for the privileged agent; never supplied by an exec caller.
735    pub fn supervisor_environment(&self) -> std::collections::BTreeMap<String, String> {
736        let mut env = std::collections::BTreeMap::new();
737        if let Some(supervisor) = &self.privileged_supervisor {
738            env.insert(
739                "ALIEN_SANDBOX_EXPECTED_EXEC_UID".to_string(),
740                supervisor.command_uid.to_string(),
741            );
742            env.insert(
743                "ALIEN_SANDBOX_EGRESS".to_string(),
744                // A runtime default is mutable gateway policy, never a startup allowlist.
745                if self.egress == SandboxEgress::None {
746                    r#"{"mode":"deny"}"#.to_string()
747                } else {
748                    serde_json::to_string(&self.egress).expect("egress serializes")
749                },
750            );
751        }
752        env
753    }
754
755    /// The declared ceilings, or the defaults a platform applies when none were named.
756    ///
757    /// Backends want a concrete set: a sandbox with no declared ceilings still runs inside
758    /// whatever the platform gives it, and a backend that had to branch on `None` would end up
759    /// inventing its own default anyway.
760    pub fn resolved_limits(&self) -> SandboxLimits {
761        self.limits.clone().unwrap_or_else(default_limits)
762    }
763
764    /// Validates the declaration against what the target platform can enforce.
765    ///
766    /// Runs at plan time so an unenforceable limit or an unsupported egress mode fails before
767    /// anything is provisioned, rather than at the first exec.
768    pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
769        if let Some(policy) = &self.default_policy {
770            if self.egress != SandboxEgress::Internet {
771                return Err(AlienError::new(ErrorData::SandboxEgressInvalid {
772                    target: "defaultPolicy".into(),
773                    reason: "defaultPolicy requires the new internet declaration".into(),
774                }));
775            }
776            policy.validate()?;
777        }
778        if self.image_user == Some(0) && matches!(platform, Platform::Local | Platform::Kubernetes)
779        {
780            return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
781                capability: "root image USER: this backend does not yet separate bounded root boot from non-root exec; use a non-root image USER".into(),
782                platform: platform.to_string(),
783            }));
784        }
785        let mut capabilities = SandboxCapabilities::for_platform(platform)?;
786        if let Some(supervisor) = &self.privileged_supervisor {
787            if platform != Platform::Aws {
788                return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
789                    capability: "privilegedSupervisor".to_string(),
790                    platform: platform.to_string(),
791                }));
792            }
793            if supervisor.command_uid == 0 || supervisor.command_uid == u32::MAX {
794                return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
795                    resource_id: self.id.clone(),
796                    field: "privilegedSupervisor.commandUid".to_string(),
797                    value: supervisor.command_uid.to_string(),
798                    reason: "must be a non-root Linux uid other than the invalid uid sentinel"
799                        .to_string(),
800                }));
801            }
802            if let SandboxEgress::AllowDomains { domains } = &self.egress {
803                for domain in domains {
804                    let hostname = domain.strip_suffix('.').unwrap_or(domain);
805                    if hostname.len() > 253
806                        || !hostname.split('.').all(|label| {
807                            !label.is_empty()
808                                && label.len() <= 63
809                                && label
810                                    .bytes()
811                                    .all(|c| c.is_ascii_alphanumeric() || c == b'-')
812                                && !label.starts_with('-')
813                                && !label.ends_with('-')
814                        })
815                    {
816                        return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
817                            resource_id: self.id.clone(), field: "egress.domains".to_string(), value: domain.clone(),
818                            reason: "privileged supervisor allowlists require exact DNS hostnames; wildcards are unsupported".to_string(),
819                        }));
820                    }
821                }
822            }
823            capabilities.domain_egress_rules = true;
824        }
825
826        // `alien build` builds an AWS, Azure, GCP or Kubernetes sandbox's base image, so source is a
827        // declaration there and the emitters refuse it only if it reaches them unbuilt. Everywhere
828        // else the image is pulled as declared, and an empty image string would schedule a pod
829        // that can never run.
830        if matches!(&self.code, SandboxCode::Source { .. })
831            && !matches!(
832                platform,
833                Platform::Aws | Platform::Azure | Platform::Gcp | Platform::Kubernetes
834            )
835        {
836            return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
837                resource_id: self.id.clone(),
838                field: "code".to_string(),
839                value: "source".to_string(),
840                reason: format!(
841                    "no sandbox backend builds an image from source on {platform}; give \
842                     code.image a prebuilt reference"
843                ),
844            }));
845        }
846
847        // Elsewhere `code.image` is pulled directly, so a second reference would be a grant
848        // nothing reads.
849        if self.private_base_image.is_some() && platform != Platform::Aws {
850            return Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
851                capability: "privateBaseImage".to_string(),
852                platform: platform.to_string(),
853            }));
854        }
855
856        // Read before the limits, because the image is declared whether or not any are. A source
857        // declaration has no image until `alien build` writes one.
858        if platform == Platform::Azure && matches!(&self.code, SandboxCode::Image { .. }) {
859            self.azure_image()?;
860        }
861
862        // Read before the limits, like the image, because a lifetime is declared whether or not
863        // any limits are.
864        if let Some(seconds) = self.lifecycle.max_lifetime_seconds {
865            // First, so a platform with no deadline says so before any complaint about the value.
866            capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
867
868            if seconds == 0 {
869                return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
870                    resource_id: self.id.clone(),
871                    field: "maxLifetimeSeconds".to_string(),
872                    value: "0".to_string(),
873                    reason: "a sandbox must be allowed to run for at least 1 second".to_string(),
874                }));
875            }
876
877            // Each ceiling is the platform's own, and the platform rejects a value above it
878            // rather than clamping, so it would pass planning, render into the package, and fail
879            // at the first sandbox. The ceilings differ, which is why they sit under a platform
880            // match rather than on the type.
881            let ceiling = match platform {
882                Platform::Aws => Some((AWS_MAX_LIFETIME_SECONDS, "AWS runs a MicroVM for")),
883                Platform::Kubernetes => {
884                    Some((KUBERNETES_MAX_LIFETIME_SECONDS, "Kubernetes runs a pod for"))
885                }
886                // The Agent Platform documents `ttl` without a valid range, so a value it refuses
887                // still fails at the first sandbox rather than here.
888                Platform::Gcp => None,
889                // Never reached: the capability check above refuses Azure and Local, and
890                // `for_platform` refuses Machines and Test at the top of this function.
891                Platform::Azure | Platform::Local | Platform::Machines | Platform::Test => None,
892            };
893            if let Some((max, runs_for)) = ceiling {
894                if seconds > max {
895                    return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
896                        resource_id: self.id.clone(),
897                        field: "maxLifetimeSeconds".to_string(),
898                        value: seconds.to_string(),
899                        reason: format!("{runs_for} between 1 and {max} seconds"),
900                    }));
901                }
902            }
903        }
904
905        let Some(limits) = self.limits.as_ref() else {
906            // Nothing declared, so nothing to enforce and nothing to reject.
907            return self.validate_capabilities(&capabilities, platform);
908        };
909
910        validate_quantity(&self.id, "cpu", &limits.cpu)?;
911        validate_quantity(&self.id, "memory", &limits.memory)?;
912        validate_quantity(&self.id, "disk", &limits.disk)?;
913
914        if let Some(max_processes) = limits.max_processes {
915            if max_processes == 0 {
916                return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
917                    resource_id: self.id.clone(),
918                    field: "maxProcesses".to_string(),
919                    value: "0".to_string(),
920                    reason: "a sandbox that may run no processes cannot run code".to_string(),
921                }));
922            }
923            capabilities.require(SandboxCapability::ProcessLimit, platform)?;
924        }
925
926        // Declaring limits a platform ignores is worse than not declaring them: the stack reads
927        // as bounded while the sandbox is not.
928        capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
929
930        if platform == Platform::Azure {
931            self.azure_sandbox_limits()?;
932        }
933
934        if platform == Platform::Aws {
935            // Refused here rather than at emit so a customer sees it while planning, and so both
936            // package formats inherit the same answer.
937            self.microvm_tier()?;
938        }
939
940        self.validate_capabilities(&capabilities, platform)
941    }
942
943    /// What Azure creates this sandbox from: a catalog name or a registry image, told apart by
944    /// [`classify_azure_sandbox_image`]. Refused while planning, because a value the data plane
945    /// rejects would otherwise surface at the first sandbox, long after the apply.
946    pub fn azure_image(&self) -> Result<AzureSandboxImage<'_>> {
947        let SandboxCode::Image { image, .. } = &self.code else {
948            return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
949                resource_id: self.id.clone(),
950                field: "code".to_string(),
951                value: "source".to_string(),
952                reason: "the sandbox still has unbuilt source code. Run 'alien build' first"
953                    .to_string(),
954            }));
955        };
956
957        classify_azure_sandbox_image(image).ok_or_else(|| {
958            let image = image.trim();
959            AlienError::new(ErrorData::SandboxLimitInvalid {
960                resource_id: self.id.clone(),
961                field: "code.image".to_string(),
962                value: image.to_string(),
963                reason: if image.is_empty() {
964                    "a sandbox has to name an image".to_string()
965                } else {
966                    "Azure creates a sandbox from a catalog name such as 'ubuntu' or from a \
967                     registry image such as 'docker.io/library/python:3.14-slim'"
968                        .to_string()
969                },
970            })
971        })
972    }
973
974    /// Checks the declared ceilings against Azure's sizing rule (the `AZURE_*` constants above).
975    /// Refused at plan time, like [`Self::microvm_tier`], so a bad value is a declaration to fix
976    /// rather than a runtime fault at create.
977    pub fn azure_sandbox_limits(&self) -> Result<()> {
978        let Some(limits) = self.limits.as_ref() else {
979            // Nothing declared means the binding substitutes Alien's own default sizing, which is
980            // inside the rule — asserted where those constants live, since this cannot see them.
981            return Ok(());
982        };
983
984        let refused = |field: &str, value: &str, reason: &str| {
985            AlienError::new(ErrorData::SandboxLimitInvalid {
986                resource_id: self.id.clone(),
987                field: field.to_string(),
988                value: value.to_string(),
989                reason: reason.to_string(),
990            })
991        };
992
993        let cpu_millicores = millicores(&limits.cpu)
994            .ok_or_else(|| refused("cpu", &limits.cpu, "expected cores or millicores"))?;
995
996        // The multiple is checked, not just the range: `333m` sits inside 0.25–16 cores and is
997        // still refused on the wire, so a bounds-only check would pass a declaration that fails
998        // at create.
999        if cpu_millicores % AZURE_CPU_STEP_MILLICORES != 0
1000            || !(AZURE_CPU_STEP_MILLICORES..=AZURE_MAX_CPU_MILLICORES).contains(&cpu_millicores)
1001        {
1002            return Err(refused(
1003                "cpu",
1004                &limits.cpu,
1005                "Azure allocates cpu in steps of 250m from 250m to 16000m",
1006            ));
1007        }
1008
1009        // Both ceilings are derived from the cpu, so they cannot be checked before it is known.
1010        let memory_ceiling_mib = cpu_millicores * AZURE_MEMORY_MIB_PER_CORE / 1000;
1011        let disk_ceiling_mib = cpu_millicores * AZURE_DISK_MIB_PER_CORE / 1000;
1012
1013        let memory_mib = quantity_mib(&limits.memory)
1014            .ok_or_else(|| refused("memory", &limits.memory, "Azure sizes memory in whole MiB"))?;
1015        if memory_mib > memory_ceiling_mib {
1016            return Err(refused(
1017                "memory",
1018                &limits.memory,
1019                &format!(
1020                    "Azure allows at most 2Gi of memory per core, or {memory_ceiling_mib}Mi \
1021                          at the declared cpu"
1022                ),
1023            ));
1024        }
1025
1026        let disk_mib = quantity_mib(&limits.disk)
1027            .ok_or_else(|| refused("disk", &limits.disk, "Azure sizes disk in whole MiB"))?;
1028        if disk_mib > disk_ceiling_mib {
1029            return Err(refused(
1030                "disk",
1031                &limits.disk,
1032                &format!(
1033                    "Azure allows at most 20Gi of disk per core, or {disk_ceiling_mib}Mi at \
1034                          the declared cpu"
1035                ),
1036            ));
1037        }
1038
1039        Ok(())
1040    }
1041
1042    /// The MicroVM size that keeps every declared ceiling, or why none does.
1043    ///
1044    /// AWS sizes are discrete and a running MicroVM bursts to four times its baseline, so the
1045    /// only tier that honours a ceiling is one whose peak fits inside it. A declaration no tier
1046    /// satisfies is refused: shipping the nearest size would give the customer a sandbox that
1047    /// exceeds the bound they wrote down.
1048    pub fn microvm_tier(&self) -> Result<MicrovmTier> {
1049        let Some(limits) = self.limits.as_ref() else {
1050            // Nothing declared: AWS's own default size, a 2 GiB baseline that bursts to 8 GiB and
1051            // 4 vCPU. This is larger than `default_limits`, which the other backends use; picked
1052            // by the rule below, `default_limits` would select the 512 MiB tier (#1474).
1053            return Ok(MICROVM_TIERS[2]);
1054        };
1055
1056        let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
1057            AlienError::new(ErrorData::SandboxLimitInvalid {
1058                resource_id: self.id.clone(),
1059                field: "memory".to_string(),
1060                value: limits.memory.clone(),
1061                reason: "AWS sizes a MicroVM in whole MiB".to_string(),
1062            })
1063        })?;
1064        let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
1065            AlienError::new(ErrorData::SandboxLimitInvalid {
1066                resource_id: self.id.clone(),
1067                field: "disk".to_string(),
1068                value: limits.disk.clone(),
1069                reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
1070            })
1071        })?;
1072        let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
1073            AlienError::new(ErrorData::SandboxLimitInvalid {
1074                resource_id: self.id.clone(),
1075                field: "cpu".to_string(),
1076                value: limits.cpu.clone(),
1077                reason: "expected cores or millicores".to_string(),
1078            })
1079        })?;
1080
1081        // Memory and disk choose the size; cpu is then checked rather than used to choose.
1082        // AWS couples cpu to memory at 2 GB per vCPU, so letting a low cpu ceiling select the
1083        // size too would quietly hand back a machine four times smaller than the memory ceiling
1084        // asked for, with nothing to indicate it.
1085        let sized = |tier: &&MicrovmTier| {
1086            tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
1087        };
1088
1089        let tier = MICROVM_TIERS
1090            .iter()
1091            .rev()
1092            .find(sized)
1093            .copied()
1094            .ok_or_else(|| {
1095                AlienError::new(ErrorData::SandboxLimitInvalid {
1096                    resource_id: self.id.clone(),
1097                    field: "memory".to_string(),
1098                    value: limits.memory.clone(),
1099                    reason: format!(
1100                        "a Lambda MicroVM bursts to four times its baseline, so the smallest \
1101                         ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
1102                         disk fit no size",
1103                        limits.memory, limits.disk
1104                    ),
1105                })
1106            })?;
1107
1108        let required_millicores = i64::from(tier.peak_vcpu) * 1000;
1109        if cpu_millicores < required_millicores {
1110            return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1111                resource_id: self.id.clone(),
1112                field: "cpu".to_string(),
1113                value: limits.cpu.clone(),
1114                reason: format!(
1115                    "AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
1116                     reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
1117                    limits.memory, tier.peak_vcpu, tier.peak_vcpu
1118                ),
1119            }));
1120        }
1121
1122        Ok(tier)
1123    }
1124
1125    /// The capability checks that do not depend on declared limits.
1126    fn validate_capabilities(
1127        &self,
1128        capabilities: &SandboxCapabilities,
1129        platform: Platform,
1130    ) -> Result<()> {
1131        if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
1132            capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
1133        }
1134
1135        // `allow` asks for no restriction, so a backend that ignores it fails loudly on the first
1136        // blocked connection. `deny` asks for one, and a backend that ignores it puts untrusted
1137        // code on the internet with nothing to notice — so only this direction is gated.
1138        // An empty list is not a restriction anyone wrote down: it renders as a deny-all wearing
1139        // an allowlist's label, which reads at a glance as the opposite of what it does.
1140        if let SandboxEgress::AllowDomains { domains } = &self.egress {
1141            if domains.is_empty() {
1142                return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
1143                    resource_id: self.id.clone(),
1144                    field: "egress.domains".to_string(),
1145                    value: "[]".to_string(),
1146                    reason: "an allowlist naming no domain denies everything; declare \
1147                             egress: deny if that is what was meant"
1148                        .to_string(),
1149                }));
1150            }
1151        }
1152
1153        if matches!(self.egress, SandboxEgress::None) {
1154            capabilities.require(SandboxCapability::EgressDeny, platform)?;
1155        }
1156
1157        if !self.preview_ports.is_empty() {
1158            capabilities.require(SandboxCapability::Preview, platform)?;
1159        }
1160
1161        if self.lifecycle.idle_pause_seconds.is_some() {
1162            capabilities.require(SandboxCapability::PauseResume, platform)?;
1163        }
1164
1165        if self.lifecycle.max_lifetime_seconds.is_some() {
1166            capabilities.require(SandboxCapability::SandboxLifetime, platform)?;
1167        }
1168
1169        Ok(())
1170    }
1171}
1172
1173/// Ceilings applied when a declaration names none.
1174///
1175/// Modest on purpose: an undeclared sandbox is one whose author did not think about sizing, and
1176/// the safe reading of that is a small box rather than a generous one.
1177fn default_limits() -> SandboxLimits {
1178    SandboxLimits {
1179        cpu: "1".to_string(),
1180        memory: "2Gi".to_string(),
1181        disk: "8Gi".to_string(),
1182        max_processes: None,
1183    }
1184}
1185
1186/// Validates a Kubernetes-style resource quantity such as `500m`, `2Gi` or `1`.
1187fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
1188    let invalid = |reason: &str| {
1189        AlienError::new(ErrorData::SandboxLimitInvalid {
1190            resource_id: resource_id.to_string(),
1191            field: field.to_string(),
1192            value: value.to_string(),
1193            reason: reason.to_string(),
1194        })
1195    };
1196
1197    let digits_end = value
1198        .find(|c: char| !c.is_ascii_digit() && c != '.')
1199        .unwrap_or(value.len());
1200    let (number, suffix) = value.split_at(digits_end);
1201
1202    let parsed: f64 = number
1203        .parse()
1204        .map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
1205
1206    if parsed <= 0.0 {
1207        return Err(invalid("must be greater than zero"));
1208    }
1209
1210    const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
1211    if !SUFFIXES.contains(&suffix) {
1212        return Err(invalid(
1213            "unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
1214        ));
1215    }
1216
1217    Ok(())
1218}
1219
1220/// Splits a quantity into its number and unit suffix.
1221fn split_quantity(value: &str) -> Option<(f64, &str)> {
1222    let trimmed = value.trim();
1223    let digits_end = trimmed
1224        .find(|c: char| !c.is_ascii_digit() && c != '.')
1225        .unwrap_or(trimmed.len());
1226    let (number, suffix) = trimmed.split_at(digits_end);
1227    number.parse().ok().map(|number| (number, suffix))
1228}
1229
1230/// A memory or disk quantity in whole MiB, rounded down.
1231///
1232/// Every suffix `validate_quantity` accepts is handled here. Reading only `Gi` and `Mi` and
1233/// falling back for the rest would turn a declared `4G` into a different size than the customer
1234/// asked for, which for a ceiling means a sandbox larger than its bound.
1235pub fn quantity_mib(value: &str) -> Option<i64> {
1236    let (number, suffix) = split_quantity(value)?;
1237    let bytes = match suffix {
1238        "" => number,
1239        "k" => number * 1e3,
1240        "M" => number * 1e6,
1241        "G" => number * 1e9,
1242        "T" => number * 1e12,
1243        "Ki" => number * 1024.0,
1244        "Mi" => number * 1024.0 * 1024.0,
1245        "Gi" => number * 1024.0 * 1024.0 * 1024.0,
1246        "Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
1247        // `m` is a millicore suffix; memory has no use for it.
1248        _ => return None,
1249    };
1250    Some((bytes / (1024.0 * 1024.0)) as i64)
1251}
1252
1253/// A CPU quantity in millicores.
1254pub fn millicores(value: &str) -> Option<i64> {
1255    let (number, suffix) = split_quantity(value)?;
1256    match suffix {
1257        "" => Some((number * 1000.0) as i64),
1258        "m" => Some(number as i64),
1259        _ => None,
1260    }
1261}
1262
1263/// Outputs generated by a successfully provisioned Sandbox parent.
1264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1265#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
1266#[serde(rename_all = "camelCase")]
1267pub struct SandboxOutputs {
1268    /// Name of the durable parent that sandboxes are created inside
1269    pub parent_name: String,
1270    /// Platform-specific identifier for the parent (image ARN, sandbox group id, namespace)
1271    #[serde(skip_serializing_if = "Option::is_none")]
1272    pub identifier: Option<String>,
1273    /// Data-plane endpoint sandboxes are created through, where the platform has one
1274    #[serde(skip_serializing_if = "Option::is_none")]
1275    pub endpoint: Option<String>,
1276}
1277
1278impl ResourceOutputsDefinition for SandboxOutputs {
1279    fn get_resource_type(&self) -> ResourceType {
1280        Sandbox::RESOURCE_TYPE
1281    }
1282
1283    fn as_any(&self) -> &dyn Any {
1284        self
1285    }
1286
1287    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
1288        Box::new(self.clone())
1289    }
1290
1291    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
1292        other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
1293    }
1294
1295    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1296        serde_json::to_value(self)
1297    }
1298}
1299
1300impl ResourceDefinition for Sandbox {
1301    fn get_resource_type(&self) -> ResourceType {
1302        Self::RESOURCE_TYPE
1303    }
1304
1305    fn id(&self) -> &str {
1306        &self.id
1307    }
1308
1309    fn replace_after_failed_create_is_safe(&self) -> bool {
1310        // A create adopts an existing image with the same name, and deleting it deletes that image,
1311        // which this deployment may never have built.
1312        false
1313    }
1314
1315    fn get_dependencies(&self) -> Vec<ResourceRef> {
1316        Vec::new()
1317    }
1318
1319    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
1320        let new_sandbox = new_config
1321            .as_any()
1322            .downcast_ref::<Sandbox>()
1323            .ok_or_else(|| {
1324                AlienError::new(ErrorData::UnexpectedResourceType {
1325                    resource_id: self.id.clone(),
1326                    expected: Self::RESOURCE_TYPE,
1327                    actual: new_config.get_resource_type(),
1328                })
1329            })?;
1330
1331        if self.id != new_sandbox.id {
1332            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
1333                resource_id: self.id.clone(),
1334                reason: "the 'id' field is immutable".to_string(),
1335            }));
1336        }
1337
1338        Ok(())
1339    }
1340
1341    fn as_any(&self) -> &dyn Any {
1342        self
1343    }
1344
1345    fn as_any_mut(&mut self) -> &mut dyn Any {
1346        self
1347    }
1348
1349    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
1350        Box::new(self.clone())
1351    }
1352
1353    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
1354        other.as_any().downcast_ref::<Sandbox>() == Some(self)
1355    }
1356
1357    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
1358        serde_json::to_value(self)
1359    }
1360}
1361
1362/// What an Azure sandbox starts from.
1363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1364pub enum AzureSandboxImage<'a> {
1365    /// A public catalog disk image, such as `ubuntu`, which the data plane names directly.
1366    Catalog(&'a str),
1367    /// A registry image, which the controller builds into a disk image in the sandbox's group
1368    /// before any sandbox can start from it.
1369    Registry(&'a str),
1370}
1371
1372impl<'a> AzureSandboxImage<'a> {
1373    /// The declared value, trimmed.
1374    pub fn as_str(&self) -> &'a str {
1375        match self {
1376            Self::Catalog(value) | Self::Registry(value) => value,
1377        }
1378    }
1379}
1380
1381/// Label key the controller writes on every disk image it builds, and the provider finds it by.
1382pub const AZURE_DISK_IMAGE_LABEL: &str = "alienImage";
1383
1384/// Classifies a declared `code.image` for Azure, or `None` when it is neither kind. A bare
1385/// `[A-Za-z0-9._-]+` is checked first and always a catalog name; anything else must carry `/`,
1386/// `:` or `@` and parse as an OCI reference.
1387pub fn classify_azure_sandbox_image(image: &str) -> Option<AzureSandboxImage<'_>> {
1388    let image = image.trim();
1389    if image.is_empty() {
1390        return None;
1391    }
1392    if image
1393        .chars()
1394        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
1395    {
1396        return Some(AzureSandboxImage::Catalog(image));
1397    }
1398    (image.contains(|c| matches!(c, '/' | ':' | '@')) && OCI_REFERENCE.is_match(image))
1399        .then_some(AzureSandboxImage::Registry(image))
1400}
1401
1402/// The label value naming the disk image built from `reference`: a digest, since a label value
1403/// may not carry a reference's `/`, `:` and `@`.
1404pub fn azure_disk_image_label(reference: &str) -> String {
1405    let digest = format!("{:x}", Sha256::digest(reference.trim().as_bytes()));
1406    digest[..32].to_string()
1407}
1408
1409/// The distribution reference grammar: `[host[:port]/]path[:tag][@digest]`.
1410static OCI_REFERENCE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
1411    let domain_component = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
1412    let domain = format!(r"{domain_component}(?:\.{domain_component})*(?::[0-9]+)?");
1413    let path_component = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*";
1414    let name = format!(r"(?:{domain}/)?{path_component}(?:/{path_component})*");
1415    let tag = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}";
1416    let digest = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}";
1417    regex::Regex::new(&format!(r"^{name}(?::{tag})?(?:@{digest})?$"))
1418        .expect("the OCI reference grammar compiles")
1419});
1420
1421/// The one token a sandbox bundle URI may carry, replaced with the deploying region.
1422///
1423/// AWS builds a MicroVM image only from a bucket in the image's own region, so a vendor
1424/// publishing to every supported region needs one stored URI that resolves per region.
1425pub const BUNDLE_REGION_TOKEN: &str = "{region}";
1426
1427/// A bundle URI split around its region token, or carried whole when it has none.
1428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1429pub enum BundleUri<'a> {
1430    /// No token: emitted exactly as it is today.
1431    Literal(&'a str),
1432    /// The text either side of the token, for an emitter to rejoin around its own region
1433    /// expression.
1434    Regional { before: &'a str, after: &'a str },
1435}
1436
1437/// The prefix a rebuild's new key still sits under: everything above the file name and the
1438/// version segment beneath it. `None` when nothing sits there, meaning no prefix can be granted
1439/// without also granting objects a rebuild never reads. Shared so both emitters agree on it.
1440pub fn stable_bundle_key_prefix(key: &str) -> Option<&str> {
1441    let (above_file, _) = key.rsplit_once('/')?;
1442    let (above_version, _) = above_file.rsplit_once('/')?;
1443    Some(above_version)
1444}
1445
1446/// Reads a sandbox bundle URI, refusing anything an image build would only reject later.
1447///
1448/// The token is accepted in the bucket alone. A key-position token would name an object that does
1449/// not exist, and any other brace is a typo that would otherwise reach S3 verbatim and fail ~160s
1450/// into the build — which is the failure this whole check exists to move to plan time.
1451pub fn parse_bundle_uri(uri: &str) -> std::result::Result<BundleUri<'_>, String> {
1452    let path = uri
1453        .strip_prefix("s3://")
1454        .ok_or_else(|| format!("'{uri}' is not an s3:// URI"))?;
1455    let (bucket, key) = path
1456        .split_once('/')
1457        .ok_or_else(|| format!("'{uri}' names a bucket with no object key"))?;
1458
1459    // Both emitters interpolate this path into the build role's resource ARN, where `*` and `?`
1460    // are IAM wildcards rather than literal characters. S3 accepts them in a key, so a bundle
1461    // published under one would silently widen the grant past the bundle it names.
1462    if path.contains('*') || path.contains('?') {
1463        return Err(format!(
1464            "'{uri}' carries an IAM wildcard; the bundle's path is interpolated into the build \
1465             role's grant, so '*' and '?' would widen it past the bundle"
1466        ));
1467    }
1468
1469    if key.contains('{') || key.contains('}') {
1470        return Err(format!(
1471            "'{uri}' places a token in the object key; {BUNDLE_REGION_TOKEN} is accepted in the \
1472             bucket name alone"
1473        ));
1474    }
1475
1476    let Some((before, after)) = bucket.split_once(BUNDLE_REGION_TOKEN) else {
1477        if bucket.contains('{') || bucket.contains('}') {
1478            return Err(format!(
1479                "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the \
1480                 only one"
1481            ));
1482        }
1483        return Ok(BundleUri::Literal(uri));
1484    };
1485
1486    if after.contains(BUNDLE_REGION_TOKEN) {
1487        return Err(format!("'{uri}' repeats {BUNDLE_REGION_TOKEN}"));
1488    }
1489    if before.contains('{') || before.contains('}') || after.contains('{') || after.contains('}') {
1490        return Err(format!(
1491            "'{uri}' carries a token this build does not know; {BUNDLE_REGION_TOKEN} is the only one"
1492        ));
1493    }
1494
1495    Ok(BundleUri::Regional {
1496        before: &uri[.."s3://".len() + before.len()],
1497        after: &uri["s3://".len() + before.len() + BUNDLE_REGION_TOKEN.len()..],
1498    })
1499}
1500
1501/// Where a private ECR image's region comes from.
1502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1503pub enum EcrImageRegion<'a> {
1504    /// A region named in the host.
1505    Literal(&'a str),
1506    /// [`BUNDLE_REGION_TOKEN`] in the host: the region the deployment renders.
1507    Deployment,
1508}
1509
1510/// The ECR repository a private image reference is pulled from.
1511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1512pub struct EcrImageRepository<'a> {
1513    pub account_id: &'a str,
1514    pub region: EcrImageRegion<'a>,
1515    /// The repository name, which may carry `/`; never a tag or digest.
1516    pub repository: &'a str,
1517}
1518
1519impl EcrImageRepository<'_> {
1520    /// The repository's ARN, with `region` standing in for a region the host leaves to the
1521    /// deployment. The partition is the deployment's: a GovCloud host ends `.amazonaws.com` too.
1522    pub fn arn(&self, partition: &str, region: &str) -> String {
1523        let region = match self.region {
1524            EcrImageRegion::Literal(region) => region,
1525            EcrImageRegion::Deployment => region,
1526        };
1527        format!(
1528            "arn:{partition}:ecr:{region}:{}:repository/{}",
1529            self.account_id, self.repository
1530        )
1531    }
1532}
1533
1534/// Reads `privateBaseImage` as the one repository a build role may pull from.
1535///
1536/// The name is interpolated into an IAM ARN, so it is held to ECR's own repository grammar: that
1537/// refuses `*` and `?`, which would widen the grant, and `$` and braces, which a CloudFormation
1538/// `Sub` or a Terraform template would read as an expression.
1539pub fn parse_ecr_image_repository(
1540    image: &str,
1541) -> std::result::Result<EcrImageRepository<'_>, String> {
1542    let refuse = |reason: &str| format!("privateBaseImage '{image}' {reason}");
1543    let (host, path) = image
1544        .split_once('/')
1545        .ok_or_else(|| refuse("names no repository"))?;
1546    let (account_id, rest) = host.split_once(".dkr.ecr.").ok_or_else(|| {
1547        refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)")
1548    })?;
1549    // `.com.cn` first: a China host ends with the shorter suffix too.
1550    let region = rest
1551        .strip_suffix(".amazonaws.com.cn")
1552        .or_else(|| rest.strip_suffix(".amazonaws.com"))
1553        .ok_or_else(|| refuse("is not served by a private ECR registry (<account>.dkr.ecr.<region>.amazonaws.com)"))?;
1554    if account_id.len() != 12 || !account_id.bytes().all(|b| b.is_ascii_digit()) {
1555        return Err(refuse("names no 12-digit account in its registry host"));
1556    }
1557    let region = if region == BUNDLE_REGION_TOKEN {
1558        EcrImageRegion::Deployment
1559    } else if !region.is_empty()
1560        && region
1561            .bytes()
1562            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1563    {
1564        EcrImageRegion::Literal(region)
1565    } else {
1566        return Err(refuse(&format!(
1567            "names no region in its registry host; give one or {BUNDLE_REGION_TOKEN}"
1568        )));
1569    };
1570
1571    let repository = match path.split_once('@') {
1572        Some((repository, _digest)) => repository,
1573        None => match path.rsplit_once('/') {
1574            Some((parent, last)) => match last.split_once(':') {
1575                Some((name, _tag)) => &path[..parent.len() + 1 + name.len()],
1576                None => path,
1577            },
1578            None => path.split_once(':').map_or(path, |(name, _tag)| name),
1579        },
1580    };
1581    let valid_segment = |segment: &str| {
1582        !segment.is_empty()
1583            && segment.bytes().all(|b| {
1584                b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
1585            })
1586    };
1587    if !repository.split('/').all(valid_segment) {
1588        return Err(refuse(
1589            "names a repository outside ECR's grammar (lowercase letters, digits, '.', '_', '-', and '/' between them)",
1590        ));
1591    }
1592    Ok(EcrImageRepository {
1593        account_id,
1594        region,
1595        repository,
1596    })
1597}
1598
1599#[cfg(test)]
1600mod tests {
1601    use super::*;
1602
1603    #[test]
1604    fn private_database_setup_accepts_the_default_network() {
1605        for lifecycle in [
1606            crate::ResourceLifecycle::Frozen,
1607            crate::ResourceLifecycle::Live,
1608        ] {
1609            let stack = crate::Stack::new("database".to_string())
1610                .add(
1611                    crate::Postgres::new("metadata".to_string()).build(),
1612                    lifecycle,
1613                )
1614                .build();
1615            assert!(!restricts_network_mode(&stack, false));
1616            assert!(!restricts_network_mode(&stack, true));
1617        }
1618        assert!(!restricts_network_mode(
1619            &crate::Stack::new("empty".to_string()).build(),
1620            false,
1621        ));
1622    }
1623
1624    /// The vectors' `repositoryKey`: registry host and repository, never the tag or digest, so a
1625    /// new tag keeps the key. A reference the parser refuses stays whole.
1626    fn repository_key(image: &str) -> String {
1627        match parse_ecr_image_repository(image) {
1628            Ok(parsed) => {
1629                let host = image.split_once('/').map_or(image, |(host, _)| host);
1630                format!("{host}/{}", parsed.repository)
1631            }
1632            Err(_) => image.to_string(),
1633        }
1634    }
1635
1636    #[test]
1637    fn a_private_base_image_names_one_repository() {
1638        let vectors: serde_json::Value = serde_json::from_str(include_str!(
1639            "../../tests/fixtures/ecr-image-repository-parity.json"
1640        ))
1641        .expect("the ECR repository vectors must be JSON");
1642        let field = |case: &serde_json::Value, name: &str| {
1643            case[name]
1644                .as_str()
1645                .unwrap_or_else(|| panic!("vector must carry {name}: {case}"))
1646                .to_string()
1647        };
1648
1649        for case in vectors["accepted"].as_array().expect("accepted vectors") {
1650            let image = field(case, "image");
1651            let region = field(case, "region");
1652            let region = if region == BUNDLE_REGION_TOKEN {
1653                EcrImageRegion::Deployment
1654            } else {
1655                EcrImageRegion::Literal(&region)
1656            };
1657            assert_eq!(
1658                parse_ecr_image_repository(&image),
1659                Ok(EcrImageRepository {
1660                    account_id: &field(case, "accountId"),
1661                    region,
1662                    repository: &field(case, "repository"),
1663                }),
1664                "{image}"
1665            );
1666            assert_eq!(
1667                repository_key(&image),
1668                field(case, "repositoryKey"),
1669                "{image}"
1670            );
1671        }
1672
1673        for case in vectors["refused"].as_array().expect("refused vectors") {
1674            let image = field(case, "image");
1675            assert!(
1676                parse_ecr_image_repository(&image).is_err(),
1677                "{image} must be refused"
1678            );
1679            assert_eq!(
1680                repository_key(&image),
1681                field(case, "repositoryKey"),
1682                "{image}"
1683            );
1684        }
1685    }
1686
1687    #[test]
1688    fn a_repository_arn_takes_the_deployment_region_only_where_the_host_leaves_it() {
1689        let regional =
1690            parse_ecr_image_repository("123456789012.dkr.ecr.{region}.amazonaws.com/team/base:1")
1691                .expect("parses");
1692        let pinned =
1693            parse_ecr_image_repository("123456789012.dkr.ecr.eu-west-1.amazonaws.com/team/base:1")
1694                .expect("parses");
1695        assert_eq!(
1696            regional.arn("aws-us-gov", "us-gov-west-1"),
1697            "arn:aws-us-gov:ecr:us-gov-west-1:123456789012:repository/team/base"
1698        );
1699        assert_eq!(
1700            pinned.arn("aws", "us-east-1"),
1701            "arn:aws:ecr:eu-west-1:123456789012:repository/team/base"
1702        );
1703    }
1704
1705    /// A wildcard reaching the grant would widen it past the bundle, and it widens the Frozen
1706    /// object grant as readily as the Live prefix — both interpolate the path into the ARN.
1707    #[test]
1708    fn a_uri_carrying_an_iam_wildcard_is_refused() {
1709        for uri in [
1710            "s3://acme/team-*/v1/bundle.zip",
1711            "s3://acme/sandbox-bundle/f00d/bundle?.zip",
1712            "s3://acme-*/sandbox-bundle/f00d/bundle.zip",
1713        ] {
1714            let error = parse_bundle_uri(uri).expect_err("a wildcard must be refused");
1715            assert!(error.contains("IAM wildcard"), "for {uri}: {error}");
1716        }
1717
1718        parse_bundle_uri("s3://acme/sandbox-bundle/f00d/bundle.zip")
1719            .expect("an ordinary key still parses");
1720    }
1721
1722    /// The rule both package formats grant by, pinned here rather than in either. The
1723    /// near-misses the cases separate: the key's first segment grants objects a rebuild never
1724    /// reads, and the object's own directory pins the version segment that moves.
1725    #[test]
1726    fn a_grantable_prefix_ends_above_the_segment_that_moves() {
1727        assert_eq!(
1728            stable_bundle_key_prefix("sandbox-bundle/f00dcafe/bundle.zip"),
1729            Some("sandbox-bundle")
1730        );
1731        assert_eq!(
1732            stable_bundle_key_prefix("artifacts/team-a/sandbox/f00dcafe/bundle.zip"),
1733            Some("artifacts/team-a/sandbox"),
1734            "a deeper key narrows the prefix, it never widens to the first segment"
1735        );
1736
1737        // Nothing sits above the version segment, so no prefix a moved bundle stays inside
1738        // exists. Emitting the object grant instead installs a role that denies the next rebuild.
1739        assert_eq!(stable_bundle_key_prefix("agents/bundle.zip"), None);
1740        assert_eq!(stable_bundle_key_prefix("bundle.zip"), None);
1741    }
1742
1743    fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
1744        Sandbox::new("agent-sbx".to_string())
1745            .code(SandboxCode::Image {
1746                image: "ubuntu".to_string(),
1747                bundled_from: None,
1748            })
1749            .limits(SandboxLimits {
1750                cpu: "1".to_string(),
1751                memory: "2Gi".to_string(),
1752                disk: "20Gi".to_string(),
1753                max_processes: None,
1754            })
1755            .egress(egress)
1756            .lifecycle(SandboxLifecyclePolicy {
1757                max_lifetime_seconds: None,
1758                idle_pause_seconds: None,
1759            })
1760            .preview_ports(preview_ports)
1761            .build()
1762    }
1763
1764    /// A URI with no token must come back whole, because every bundle configured today has none
1765    /// and emitting one differently would change every existing customer's template.
1766    #[test]
1767    fn a_uri_without_a_token_is_carried_whole() {
1768        assert_eq!(
1769            parse_bundle_uri("s3://acme-artifacts-us-east-2/agents/bundle.zip"),
1770            Ok(BundleUri::Literal(
1771                "s3://acme-artifacts-us-east-2/agents/bundle.zip"
1772            ))
1773        );
1774    }
1775
1776    /// The split has to rejoin to the original with the region in place, or an emitter builds a
1777    /// URI that is subtly not the one the vendor configured.
1778    #[test]
1779    fn a_regional_uri_splits_either_side_of_the_token() {
1780        let BundleUri::Regional { before, after } =
1781            parse_bundle_uri("s3://acme-artifacts-{region}/agents/bundle.zip")
1782                .expect("the token is accepted in the bucket")
1783        else {
1784            panic!("a bucket-position token must split");
1785        };
1786
1787        assert_eq!(before, "s3://acme-artifacts-");
1788        assert_eq!(after, "/agents/bundle.zip");
1789        assert_eq!(
1790            format!("{before}us-east-2{after}"),
1791            "s3://acme-artifacts-us-east-2/agents/bundle.zip",
1792            "the halves must rejoin to the URI the vendor meant"
1793        );
1794    }
1795
1796    /// Each of these reaches S3 verbatim and dies ~160s into an image build if it is not refused
1797    /// here, which is the whole reason this runs at plan time.
1798    #[test]
1799    fn a_token_this_build_cannot_resolve_is_refused() {
1800        for uri in [
1801            "s3://acme-artifacts-{regio}/bundle.zip",
1802            "s3://acme-artifacts/{region}/bundle.zip",
1803            "s3://acme-artifacts-{region}-{region}/bundle.zip",
1804            "s3://acme-artifacts/bundle-{version}.zip",
1805            "s3://acme}-artifacts-{region}/bundle.zip",
1806            "s3://acme{-artifacts-{region}/bundle.zip",
1807        ] {
1808            assert!(
1809                parse_bundle_uri(uri).is_err(),
1810                "'{uri}' must be refused before it can reach an image build"
1811            );
1812        }
1813    }
1814
1815    #[test]
1816    fn resource_type_is_stable() {
1817        assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
1818    }
1819
1820    #[test]
1821    fn capability_sets_are_per_platform() {
1822        let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
1823        assert!(
1824            gcp.reconnect,
1825            "generation from the container boot id makes a sandbox reachable across processes"
1826        );
1827        assert!(!gcp.preview);
1828        assert!(gcp.enforced_limits);
1829
1830        let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
1831        assert!(azure.files, "every backend moves files");
1832        assert!(gcp.files);
1833        // Azure is the only backend whose egress policy matches on host pattern, and the only
1834        // one where `deny` and a hostname list are the same object.
1835        assert!(azure.domain_egress_rules);
1836        assert!(azure.egress_deny);
1837        // The data plane honours a continuous cpu/memory/disk surface and refuses anything
1838        // outside `n×250m`, with the rule in the message.
1839        assert!(azure.enforced_limits);
1840        assert!(azure.pause_resume);
1841        // Both stay false for reasons that are not "unbuilt": a snapshot id has nothing to
1842        // consume it on any backend, and an Azure port's auth is anonymous or a human allowlist,
1843        // neither of which is a port-scoped credential.
1844        assert!(!azure.snapshot);
1845        assert!(!azure.preview);
1846
1847        let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
1848        assert!(!aws.snapshot, "AWS has no user-callable sandbox snapshot");
1849        assert!(aws.pause_resume);
1850
1851        let k8s =
1852            SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
1853        assert!(
1854            k8s.preview,
1855            "an in-cluster caller previews through the agent route"
1856        );
1857    }
1858
1859    /// Whether the process supervising a command is a separate identity from the command.
1860    ///
1861    /// Values are measured, not inferred. AWS: the agent runs as uid 0 with
1862    /// `CapEff: 00000000a80425fb` and `setuid`s the command to uid 60000, so the two differ.
1863    /// Kubernetes: the sandbox pod pins `run_as_user: 65534` on both pod and container with
1864    /// `capabilities.drop: [ALL]` and `allow_privilege_escalation: false`, so no uid split is
1865    /// possible (`kubernetes_spec.rs`). Local: `docker exec` runs as the workload uid while the
1866    /// manager supervises from the host. Azure and Agent Platform have no in-sandbox supervisor.
1867    #[test]
1868    fn supervisor_isolation_is_per_platform() {
1869        let value = |platform| {
1870            SandboxCapabilities::for_platform(platform)
1871                .expect("supported")
1872                .supervisor_isolation
1873        };
1874
1875        assert!(
1876            value(Platform::Aws),
1877            "root agent setuids the command to 60000"
1878        );
1879        assert!(
1880            value(Platform::Local),
1881            "the supervisor is on the host, outside the container"
1882        );
1883        assert!(
1884            !value(Platform::Kubernetes),
1885            "a single pinned uid cannot be split"
1886        );
1887        assert!(!value(Platform::Azure), "no Alien process runs the command");
1888        assert!(
1889            !value(Platform::Gcp),
1890            "no separate supervisor identity runs the command"
1891        );
1892    }
1893
1894    /// The point of the field: AWS and GCP report the *same* `supervisor_pid_namespace` (neither
1895    /// has `CAP_SYS_ADMIN`), so that axis alone reads them as equivalent. They are not — AWS
1896    /// separates the command's identity from the supervisor's and Agent Platform does not.
1897    #[test]
1898    fn supervisor_isolation_separates_aws_from_a_subprocess_backend() {
1899        let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
1900        let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
1901
1902        assert_eq!(
1903            aws.supervisor_pid_namespace, gcp.supervisor_pid_namespace,
1904            "the older axis cannot tell them apart"
1905        );
1906        assert!(
1907            aws.supervisor_isolation,
1908            "AWS setuids the command off the supervisor"
1909        );
1910        assert!(
1911            !gcp.supervisor_isolation,
1912            "the command runs under no separate supervisor identity"
1913        );
1914    }
1915
1916    /// The Agent Platform row, each value against the behaviour it was measured from. `reconnect`
1917    /// is the tripwire: it is `true` only because `generation` is derived from the container boot
1918    /// id read through the agent's health op, so a caller detects a replaced container instead of
1919    /// reconnecting to a blank one. It is also the body of the `Platform::Gcp` arm, asserted below.
1920    #[test]
1921    fn gcp_agent_platform_row_matches_measured_backend() {
1922        let row = SandboxCapabilities::gcp_agent_platform();
1923
1924        assert!(row.files, "agent file ops move over the sandbox envelope");
1925        assert!(
1926            row.reconnect,
1927            "generation is derived from the container boot id, so a sandbox is reachable across \
1928             processes"
1929        );
1930        assert!(
1931            !row.preview,
1932            "the only ingress is :execute; no port-scoped capability"
1933        );
1934        assert!(
1935            !row.pause_resume,
1936            ":resume can return a fresh container, so a pause keeps no state"
1937        );
1938        assert!(
1939            !row.snapshot,
1940            "the create path never sends a snapshot, so none is reachable through the trait"
1941        );
1942        assert!(
1943            !row.domain_egress_rules,
1944            "VPC and DNS peering is not a hostname allowlist"
1945        );
1946        assert!(
1947            row.egress_deny,
1948            "a declared deny blocks both egress and DNS"
1949        );
1950        assert!(
1951            row.enforced_limits,
1952            "ceilings are enforced, by terminating the sandbox on breach"
1953        );
1954        assert!(!row.process_limit, "no process-count ceiling is observed");
1955        assert!(row.sandbox_lifetime, "ttl maps to a sandbox expireTime");
1956        assert!(!row.supervisor_pid_namespace, "no PID-namespace isolation");
1957        assert!(
1958            !row.supervisor_isolation,
1959            "the command is not run under a separate supervisor identity"
1960        );
1961
1962        // Agent Platform is the registered GCP backend, so the arm returns exactly this row.
1963        let live = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
1964        assert_eq!(
1965            live, row,
1966            "the Platform::Gcp arm is the Agent Platform capability row"
1967        );
1968    }
1969
1970    #[test]
1971    fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
1972        let error = SandboxCapabilities::for_platform(Platform::Machines)
1973            .expect_err("Machines has no sandbox backend");
1974        assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
1975    }
1976
1977    #[test]
1978    fn unsupported_capability_names_platform_and_capability() {
1979        let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
1980        let error = capabilities
1981            .require(SandboxCapability::Preview, Platform::Gcp)
1982            .expect_err("GCP has no preview");
1983
1984        assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
1985        let rendered = error.to_string();
1986        assert!(
1987            rendered.contains("preview"),
1988            "names the capability: {rendered}"
1989        );
1990        assert!(rendered.contains("gcp"), "names the platform: {rendered}");
1991    }
1992
1993    /// Azure matches on hostname; AWS and Kubernetes match CIDRs, and Local and GCP have a
1994    /// switch rather than a filter. Accepting a hostname list on those four would leave a stack
1995    /// reading as restricted while the sandbox reaches the whole internet.
1996    #[test]
1997    fn a_hostname_allowlist_is_refused_everywhere_it_would_be_approximated() {
1998        let sandbox = sandbox_with(
1999            SandboxEgress::AllowDomains {
2000                domains: vec!["example.com".to_string()],
2001            },
2002            vec![],
2003        );
2004
2005        for platform in [
2006            Platform::Aws,
2007            Platform::Gcp,
2008            Platform::Kubernetes,
2009            Platform::Local,
2010        ] {
2011            let error = sandbox
2012                .validate_for_platform(platform)
2013                .expect_err("only Azure expresses a hostname allowlist");
2014            assert_eq!(
2015                error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2016                "on {platform:?}"
2017            );
2018        }
2019
2020        assert!(
2021            SandboxCapabilities::for_platform(Platform::Azure)
2022                .expect("supported")
2023                .domain_egress_rules,
2024            "Azure's egress policy matches on host pattern"
2025        );
2026    }
2027
2028    /// `deny` is the declaration that carries a security promise, so a backend that cannot keep
2029    /// it has to refuse rather than accept it and run the code with open egress.
2030    #[test]
2031    fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
2032        let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2033
2034        // GCP is asserted at the capability rather than through validation: this sandbox declares
2035        // ceilings GCP cannot enforce, so it is refused for a reason unrelated to egress.
2036        assert!(
2037            SandboxCapabilities::for_platform(Platform::Gcp)
2038                .expect("supported")
2039                .egress_deny
2040        );
2041
2042        for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
2043            sandbox
2044                .validate_for_platform(platform)
2045                .expect("deny is enforced here");
2046        }
2047
2048        // Declares no ceilings, which Azure refuses for its own reason, so this isolates egress.
2049        let egress_only = Sandbox::new("sbx".to_string())
2050            .code(SandboxCode::Image {
2051                image: "alpine".to_string(),
2052                bundled_from: None,
2053            })
2054            .egress(SandboxEgress::None)
2055            .lifecycle(SandboxLifecyclePolicy {
2056                max_lifetime_seconds: None,
2057                idle_pause_seconds: None,
2058            })
2059            .build();
2060
2061        egress_only
2062            .validate_for_platform(Platform::Azure)
2063            .expect("Azure creates the sandbox under a Deny policy with full inspection");
2064    }
2065
2066    /// A sandbox naming no ceilings is valid on every platform and still resolves to a concrete
2067    /// set. The rule Azure applies to ceilings that *are* declared is pinned separately, by
2068    /// `azure_sizes_follow_the_rule_the_data_plane_states`.
2069    #[test]
2070    fn a_sandbox_declaring_no_ceilings_takes_the_platforms_own() {
2071        let undeclared = Sandbox::new("sbx".to_string())
2072            .code(SandboxCode::Image {
2073                image: "alpine".to_string(),
2074                bundled_from: None,
2075            })
2076            .egress(SandboxEgress::None)
2077            .lifecycle(SandboxLifecyclePolicy {
2078                max_lifetime_seconds: None,
2079                idle_pause_seconds: None,
2080            })
2081            .build();
2082
2083        undeclared
2084            .validate_for_platform(Platform::Azure)
2085            .expect("a sandbox naming no ceilings takes the platform's own");
2086
2087        // A backend still gets a concrete set, so nothing downstream has to invent one.
2088        assert_eq!(undeclared.resolved_limits().cpu, "1");
2089    }
2090
2091    /// Pins Azure's own sizing rule: `250m`, `1500m` and `4000m` are valid, `32000m` and `333m`
2092    /// are refused. Checked at plan time so a bad value is a declaration to fix, not a package
2093    /// that renders without error and dies at the first sandbox.
2094    #[test]
2095    fn azure_sizes_follow_the_rule_the_data_plane_states() {
2096        let sized = |cpu: &str, memory: &str, disk: &str| {
2097            let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2098            let limits = sandbox
2099                .limits
2100                .as_mut()
2101                .expect("the fixture declares limits");
2102            limits.cpu = cpu.to_string();
2103            limits.memory = memory.to_string();
2104            limits.disk = disk.to_string();
2105            sandbox.validate_for_platform(Platform::Azure)
2106        };
2107
2108        sized("250m", "512Mi", "5120Mi").expect("the smallest step the data plane accepts");
2109        sized("4000m", "8192Mi", "40960Mi").expect("cpu, memory and disk are all honoured");
2110        sized("16000m", "32Gi", "320Gi").expect("the top of the range");
2111
2112        // Same off-step case `azure_sandbox_limits` checks the multiple for, not just the range.
2113        let off_step = sized("333m", "512Mi", "5120Mi").expect_err("333m is not a step of 250m");
2114        assert_eq!(off_step.code, "SANDBOX_LIMIT_INVALID", "{off_step}");
2115        assert!(off_step.to_string().contains("cpu"), "{off_step}");
2116
2117        let too_big = sized("32000m", "64Gi", "640Gi").expect_err("32 cores is over the ceiling");
2118        assert_eq!(too_big.code, "SANDBOX_LIMIT_INVALID", "{too_big}");
2119
2120        // Both ceilings are derived from the cpu, so the same memory passes at one size and fails
2121        // at another - which is what makes them worth checking rather than bounding absolutely.
2122        sized("1000m", "2Gi", "20Gi").expect("2Gi is exactly one core's worth");
2123        let over_memory = sized("250m", "2Gi", "5120Mi").expect_err("2Gi needs a full core");
2124        assert_eq!(over_memory.code, "SANDBOX_LIMIT_INVALID", "{over_memory}");
2125        assert!(over_memory.to_string().contains("memory"), "{over_memory}");
2126
2127        let over_disk = sized("250m", "512Mi", "20Gi").expect_err("20Gi needs a full core");
2128        assert!(over_disk.to_string().contains("disk"), "{over_disk}");
2129    }
2130
2131    #[test]
2132    fn preview_ports_require_the_preview_capability() {
2133        let sandbox = sandbox_with(SandboxEgress::None, vec![8080]);
2134
2135        sandbox
2136            .validate_for_platform(Platform::Aws)
2137            .expect("AWS mints a port-scoped JWE");
2138
2139        sandbox
2140            .validate_for_platform(Platform::Kubernetes)
2141            .expect("Kubernetes serves preview to in-cluster callers through the agent");
2142
2143        for platform in [Platform::Azure, Platform::Gcp] {
2144            let error = sandbox
2145                .validate_for_platform(platform)
2146                .expect_err("these backends have no port-scoped credential");
2147            assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2148        }
2149    }
2150
2151    /// A grant nothing reads is the silent no-op the capability contract exists to prevent, and
2152    /// here it is worse than useless: the reader would take it for a base image that needs
2153    /// authenticating while the platform pulls `code.image` itself.
2154    #[test]
2155    fn a_private_base_image_is_refused_off_aws() {
2156        let mut sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2157        sandbox.code = SandboxCode::Image {
2158            image: "s3://acme-artifacts/agents/bundle.zip".to_string(),
2159            bundled_from: None,
2160        };
2161        sandbox.private_base_image =
2162            Some("123456789012.dkr.ecr.{region}.amazonaws.com/acme:tag".to_string());
2163
2164        sandbox
2165            .validate_for_platform(Platform::Aws)
2166            .expect("AWS builds its image from a bundle, so a base image sits behind code.image");
2167
2168        for platform in [
2169            Platform::Gcp,
2170            Platform::Azure,
2171            Platform::Kubernetes,
2172            Platform::Local,
2173        ] {
2174            let error = sandbox
2175                .validate_for_platform(platform)
2176                .expect_err("a backend that builds no image must refuse a base image for one");
2177            assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2178            assert!(
2179                error.to_string().contains("privateBaseImage"),
2180                "the refusal must name the field the user declared: {error}"
2181            );
2182        }
2183    }
2184
2185    #[test]
2186    fn gcp_accepts_a_sandbox_declaring_enforced_limits() {
2187        let sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
2188        sandbox
2189            .validate_for_platform(Platform::Gcp)
2190            .expect("Agent Platform enforces declared ceilings, by terminating on breach");
2191    }
2192
2193    #[test]
2194    fn invalid_quantities_are_rejected_with_the_offending_field() {
2195        let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2196        sandbox
2197            .limits
2198            .as_mut()
2199            .expect("the fixture declares limits")
2200            .memory = "2Gb".to_string();
2201
2202        let error = sandbox
2203            .validate_for_platform(Platform::Aws)
2204            .expect_err("Gb is not a valid suffix");
2205        assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2206        assert!(error.to_string().contains("memory"));
2207
2208        sandbox
2209            .limits
2210            .as_mut()
2211            .expect("the fixture declares limits")
2212            .memory = "2Gi".to_string();
2213        sandbox
2214            .limits
2215            .as_mut()
2216            .expect("the fixture declares limits")
2217            .cpu = "0".to_string();
2218        let error = sandbox
2219            .validate_for_platform(Platform::Aws)
2220            .expect_err("zero cpu is not a ceiling");
2221        assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2222    }
2223
2224    #[test]
2225    fn zero_max_processes_is_rejected() {
2226        let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2227        sandbox
2228            .limits
2229            .as_mut()
2230            .expect("the fixture declares limits")
2231            .max_processes = Some(0);
2232
2233        let error = sandbox
2234            .validate_for_platform(Platform::Local)
2235            .expect_err("a sandbox must be able to run at least one process");
2236        assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2237        assert!(error.to_string().contains("maxProcesses"));
2238    }
2239
2240    /// A process ceiling needs a container runtime. Kubernetes sets one per node rather than per
2241    /// pod, and neither MicroVMs nor Azure sandboxes expose one, so accepting the declaration
2242    /// anywhere else would mean carrying a bound nothing applies.
2243    #[test]
2244    fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
2245        let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2246        sandbox
2247            .limits
2248            .as_mut()
2249            .expect("the fixture declares limits")
2250            .max_processes = Some(256);
2251
2252        sandbox
2253            .validate_for_platform(Platform::Local)
2254            .expect("Docker takes a pids limit");
2255
2256        for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
2257            let error = sandbox
2258                .validate_for_platform(platform)
2259                .expect_err("a process ceiling nothing applies must be refused");
2260            assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2261        }
2262    }
2263
2264    /// Lambda rejects a run above 28,800 seconds rather than clamping it, so a value beyond that
2265    /// would pass planning, render into the package, and fail at the first sandbox. Kubernetes
2266    /// takes the same field with a far higher ceiling, so 28,800 is AWS's alone. The lifetime is a
2267    /// lifecycle field, so a sandbox that declares no limits is held to it too.
2268    #[test]
2269    fn a_lifetime_aws_would_reject_is_refused_while_planning() {
2270        let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2271        let mut without_limits = with_limits.clone();
2272        without_limits.limits = None;
2273
2274        for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2275            for seconds in [28_801, 30_000, 100_000] {
2276                sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2277                let error = sandbox
2278                    .validate_for_platform(Platform::Aws)
2279                    .expect_err("a lifetime above what AWS runs is refused");
2280                assert_eq!(
2281                    error.code, "SANDBOX_LIMIT_INVALID",
2282                    "{seconds}s {declared} limits"
2283                );
2284
2285                // Kubernetes' ceiling is far higher, so the same declaration is fine there.
2286                sandbox
2287                    .validate_for_platform(Platform::Kubernetes)
2288                    .expect("Kubernetes takes an activeDeadlineSeconds above 28,800");
2289            }
2290
2291            sandbox.lifecycle.max_lifetime_seconds = Some(28_800);
2292            sandbox
2293                .validate_for_platform(Platform::Aws)
2294                .expect("the ceiling itself is allowed");
2295        }
2296    }
2297
2298    /// A zero lifetime is a sandbox that may not run at all. The Kubernetes API server refuses an
2299    /// `activeDeadlineSeconds` below 1 when the pod is created, so planning refuses it on every
2300    /// platform, with or without limits declared.
2301    #[test]
2302    fn a_zero_lifetime_is_refused_while_planning() {
2303        let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2304        let mut without_limits = with_limits.clone();
2305        without_limits.limits = None;
2306
2307        for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2308            sandbox.lifecycle.max_lifetime_seconds = Some(0);
2309            for platform in [Platform::Aws, Platform::Kubernetes, Platform::Gcp] {
2310                let error = sandbox
2311                    .validate_for_platform(platform)
2312                    .expect_err("a zero lifetime is refused");
2313                assert_eq!(
2314                    error.code, "SANDBOX_LIMIT_INVALID",
2315                    "{platform} {declared} limits"
2316                );
2317                assert!(
2318                    error.to_string().contains("maxLifetimeSeconds"),
2319                    "{platform} {declared} limits"
2320                );
2321            }
2322
2323            // Where the field is unsupported, that is the answer, not the value.
2324            for platform in [Platform::Azure, Platform::Local] {
2325                let error = sandbox
2326                    .validate_for_platform(platform)
2327                    .expect_err("a lifetime is refused where nothing applies it");
2328                assert_eq!(
2329                    error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
2330                    "{platform} {declared} limits"
2331                );
2332            }
2333
2334            sandbox.lifecycle.max_lifetime_seconds = Some(1);
2335            sandbox
2336                .validate_for_platform(Platform::Kubernetes)
2337                .expect("one second is the API server's floor");
2338        }
2339    }
2340
2341    /// The API server caps `activeDeadlineSeconds` at the largest i32 although the field is an
2342    /// int64, and `maxLifetimeSeconds` is a u32, so without this check the top half of its
2343    /// range would plan fine and be refused when the pod is created.
2344    #[test]
2345    fn a_lifetime_kubernetes_would_reject_is_refused_while_planning() {
2346        let with_limits = sandbox_with(SandboxEgress::None, vec![]);
2347        let mut without_limits = with_limits.clone();
2348        without_limits.limits = None;
2349
2350        for (declared, mut sandbox) in [("with", with_limits), ("without", without_limits)] {
2351            for seconds in [2_147_483_648, u32::MAX] {
2352                sandbox.lifecycle.max_lifetime_seconds = Some(seconds);
2353                let error = sandbox
2354                    .validate_for_platform(Platform::Kubernetes)
2355                    .expect_err("a lifetime above what the API server takes is refused");
2356                assert_eq!(
2357                    error.code, "SANDBOX_LIMIT_INVALID",
2358                    "{seconds}s {declared} limits"
2359                );
2360                assert!(
2361                    error.to_string().contains("maxLifetimeSeconds"),
2362                    "{seconds}s {declared} limits"
2363                );
2364            }
2365
2366            sandbox.lifecycle.max_lifetime_seconds = Some(2_147_483_647);
2367            sandbox
2368                .validate_for_platform(Platform::Kubernetes)
2369                .expect("the ceiling itself is allowed");
2370        }
2371    }
2372
2373    /// An image Azure can take neither as a catalog name nor as a registry image is refused while
2374    /// planning, not at the first sandbox.
2375    #[test]
2376    fn an_image_azure_cannot_pull_is_refused_while_planning() {
2377        let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2378        // Azure enforces no declared ceiling, so a sandbox carrying limits is refused before the
2379        // image is ever read.
2380        sandbox.limits = None;
2381
2382        // A digest too short to be one, blanks, a space and a query string.
2383        for image in ["ubuntu@sha256:abc", "", "   ", "ubuntu latest", "ubuntu?x"] {
2384            sandbox.code = SandboxCode::Image {
2385                image: image.to_string(),
2386                bundled_from: None,
2387            };
2388            let error = sandbox
2389                .validate_for_platform(Platform::Azure)
2390                .expect_err("an image Azure has nowhere to put is refused");
2391            assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "image '{image}'");
2392        }
2393
2394        for image in ["ubuntu", "ubuntu-22.04", "debian_slim"] {
2395            sandbox.code = SandboxCode::Image {
2396                image: image.to_string(),
2397                bundled_from: None,
2398            };
2399            sandbox
2400                .validate_for_platform(Platform::Azure)
2401                .unwrap_or_else(|error| panic!("'{image}' is a catalog name: {error}"));
2402        }
2403
2404        for image in [
2405            "ubuntu:24.04",
2406            "ghcr.io/myorg/sandbox:latest",
2407            "docker.io/library/python:3.14-slim",
2408            "localhost:5000/team/agent@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d",
2409        ] {
2410            sandbox.code = SandboxCode::Image {
2411                image: image.to_string(),
2412                bundled_from: None,
2413            };
2414            sandbox
2415                .validate_for_platform(Platform::Azure)
2416                .unwrap_or_else(|error| panic!("'{image}' is a registry image: {error}"));
2417        }
2418
2419        // Surrounding space is trimmed rather than carried into the create body.
2420        sandbox.code = SandboxCode::Image {
2421            image: " ubuntu ".to_string(),
2422            bundled_from: None,
2423        };
2424        assert_eq!(
2425            sandbox
2426                .azure_image()
2427                .expect("a padded name is still a name"),
2428            AzureSandboxImage::Catalog("ubuntu")
2429        );
2430    }
2431
2432    /// Every value the catalog allowlist `[A-Za-z0-9._-]+` accepts stays a catalog name, so a
2433    /// declaration that planned under it keeps its meaning. Exhaustive to three characters, then a
2434    /// fixed-seed sample of longer ones, some with surrounding space.
2435    #[test]
2436    fn every_value_the_catalog_allowlist_accepted_is_still_a_catalog_name() {
2437        const ALPHABET: &[u8] =
2438            b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
2439
2440        let assert_catalog = |value: &str| {
2441            assert_eq!(
2442                classify_azure_sandbox_image(value),
2443                Some(AzureSandboxImage::Catalog(value.trim())),
2444                "'{value}'"
2445            );
2446        };
2447
2448        for a in ALPHABET {
2449            assert_catalog(&String::from_utf8(vec![*a]).unwrap());
2450            for b in ALPHABET {
2451                assert_catalog(&String::from_utf8(vec![*a, *b]).unwrap());
2452                for c in ALPHABET {
2453                    assert_catalog(&String::from_utf8(vec![*a, *b, *c]).unwrap());
2454                }
2455            }
2456        }
2457
2458        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
2459        let mut next = || {
2460            state ^= state << 13;
2461            state ^= state >> 7;
2462            state ^= state << 17;
2463            state
2464        };
2465        for _ in 0..20_000 {
2466            let len = 4 + (next() % 60) as usize;
2467            let mut value: String = (0..len)
2468                .map(|_| ALPHABET[(next() % ALPHABET.len() as u64) as usize] as char)
2469                .collect();
2470            if next() % 4 == 0 {
2471                value = format!("  {value}\t");
2472            }
2473            assert_catalog(&value);
2474        }
2475    }
2476
2477    /// The label is how the provider finds the image the controller built, so both must derive
2478    /// the same one; it also has to fit a label value, which a raw reference does not.
2479    #[test]
2480    fn the_disk_image_label_is_stable_and_label_safe() {
2481        let label = azure_disk_image_label("docker.io/library/python:3.14-slim");
2482        assert_eq!(
2483            label,
2484            azure_disk_image_label(" docker.io/library/python:3.14-slim ")
2485        );
2486        assert_ne!(
2487            label,
2488            azure_disk_image_label("docker.io/library/python:3.13-slim")
2489        );
2490        assert_eq!(label.len(), 32);
2491        assert!(label.chars().all(|c| c.is_ascii_hexdigit()), "{label}");
2492    }
2493
2494    /// A deadline is accepted only where the platform itself terminates on it — the kubelet's
2495    /// `activeDeadlineSeconds` and Lambda's `maximumDurationInSeconds`. Everywhere else it would
2496    /// need a reaper that does not exist, so it is refused rather than accepted and dropped.
2497    #[test]
2498    fn a_sandbox_deadline_is_accepted_only_where_the_platform_applies_it() {
2499        let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2500        sandbox.lifecycle.max_lifetime_seconds = Some(3600);
2501
2502        sandbox
2503            .validate_for_platform(Platform::Kubernetes)
2504            .expect("the kubelet enforces activeDeadlineSeconds");
2505        sandbox
2506            .validate_for_platform(Platform::Aws)
2507            .expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
2508
2509        for platform in [Platform::Azure, Platform::Local] {
2510            let error = sandbox
2511                .validate_for_platform(platform)
2512                .expect_err("a deadline nothing applies must be refused");
2513            assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2514        }
2515    }
2516
2517    /// A MicroVM bursts to four times its baseline with no way to opt out, so a ceiling is kept
2518    /// by choosing the size whose *peak* fits inside it. Sizing by baseline would hand back a
2519    /// sandbox that can reach four times what the customer declared.
2520    #[test]
2521    fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
2522        let sandbox = sandbox_with(SandboxEgress::None, vec![]);
2523        let tier = sandbox
2524            .microvm_tier()
2525            .expect("2Gi/1cpu/20Gi is satisfiable");
2526
2527        assert_eq!(
2528            tier.peak_memory_mib, 2048,
2529            "the peak is the declared ceiling"
2530        );
2531        assert_eq!(
2532            tier.baseline_memory_mib, 512,
2533            "which is a quarter of it as the baseline"
2534        );
2535        assert!(tier.max_disk_mib <= 20 * 1024);
2536    }
2537
2538    /// AWS allocates one vCPU per 2GB, so a cpu ceiling below what the memory ceiling implies
2539    /// cannot be honoured together with it. Letting cpu choose the size instead would hand back a
2540    /// machine four times smaller than the memory asked for, with nothing to indicate it.
2541    #[test]
2542    fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
2543        let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2544        {
2545            let limits = sandbox
2546                .limits
2547                .as_mut()
2548                .expect("the fixture declares limits");
2549            limits.cpu = "1".to_string();
2550            limits.memory = "8Gi".to_string();
2551        }
2552
2553        let error = sandbox
2554            .microvm_tier()
2555            .expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
2556        assert!(
2557            error.to_string().contains("4 vCPU"),
2558            "the refusal must say what the memory ceiling implies: {error}"
2559        );
2560
2561        sandbox
2562            .limits
2563            .as_mut()
2564            .expect("the fixture declares limits")
2565            .cpu = "4".to_string();
2566        let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
2567        assert_eq!(tier.peak_memory_mib, 8192);
2568    }
2569
2570    /// Below AWS's smallest peak there is no size that holds the ceiling, and rounding up to the
2571    /// nearest one would silently exceed it.
2572    #[test]
2573    fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
2574        let mut sandbox = sandbox_with(SandboxEgress::None, vec![]);
2575        sandbox
2576            .limits
2577            .as_mut()
2578            .expect("the fixture declares limits")
2579            .memory = "1Gi".to_string();
2580
2581        let error = sandbox
2582            .validate_for_platform(Platform::Aws)
2583            .expect_err("no MicroVM size peaks at or below 1Gi");
2584        assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2585        assert!(
2586            error.to_string().contains("2Gi"),
2587            "the refusal must say what the smallest holdable ceiling is: {error}"
2588        );
2589    }
2590
2591    /// Source is refused at plan time on every platform whose sandbox image `alien build` does
2592    /// not build (the reason is at the check in `validate_for_platform`).
2593    #[test]
2594    fn source_code_is_refused_where_no_backend_builds_it() {
2595        let sandbox = Sandbox::new("agent".to_string())
2596            .code(SandboxCode::Source {
2597                src: "./sandbox".to_string(),
2598                toolchain: ToolchainConfig::Docker {
2599                    dockerfile: None,
2600                    build_args: None,
2601                    target: None,
2602                },
2603            })
2604            .egress(SandboxEgress::None)
2605            .lifecycle(SandboxLifecyclePolicy {
2606                max_lifetime_seconds: None,
2607                idle_pause_seconds: None,
2608            })
2609            .build();
2610
2611        sandbox
2612            .validate_for_platform(Platform::Aws)
2613            .expect("an AWS sandbox base image is built by `alien build`");
2614        sandbox
2615            .validate_for_platform(Platform::Azure)
2616            .expect("an Azure sandbox base image is built by `alien build`");
2617        sandbox
2618            .validate_for_platform(Platform::Gcp)
2619            .expect("a GCP sandbox base image is built by `alien build`");
2620        sandbox
2621            .validate_for_platform(Platform::Kubernetes)
2622            .expect("a Kubernetes sandbox base image is built by `alien build`");
2623
2624        for platform in [Platform::Local] {
2625            let error = sandbox
2626                .validate_for_platform(platform)
2627                .expect_err("no backend builds a sandbox image from source here");
2628            assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2629            assert!(
2630                error.to_string().contains("code.image"),
2631                "the refusal must say what to write instead: {error}"
2632            );
2633            assert!(
2634                error.to_string().contains(&platform.to_string()),
2635                "the refusal must name the platform that cannot build it: {error}"
2636            );
2637        }
2638    }
2639
2640    /// `validate_quantity` accepts nine suffixes. Reading only `Gi` and `Mi` would size a
2641    /// declared `4G` as though it were `4Gi`, which for a ceiling means exceeding it.
2642    #[test]
2643    fn every_accepted_unit_converts_rather_than_falling_back() {
2644        assert_eq!(quantity_mib("2Gi"), Some(2048));
2645        assert_eq!(quantity_mib("512Mi"), Some(512));
2646        assert_eq!(quantity_mib("4G"), Some(3814));
2647        assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
2648        assert_eq!(millicores("1"), Some(1000));
2649        assert_eq!(millicores("500m"), Some(500));
2650    }
2651
2652    #[test]
2653    fn privileged_supervisor_fixes_identity_and_requires_an_enforceable_backend() {
2654        let mut sandbox = sandbox_with(
2655            SandboxEgress::AllowDomains {
2656                domains: vec!["example.com".to_string()],
2657            },
2658            vec![],
2659        );
2660        sandbox.privileged_supervisor = Some(SandboxPrivilegedSupervisor { command_uid: 60001 });
2661        sandbox
2662            .validate_for_platform(Platform::Aws)
2663            .expect("AWS can enforce the policy in the agent");
2664        assert_eq!(sandbox.cloud_egress(), &SandboxEgress::Allow);
2665        assert_eq!(
2666            sandbox.supervisor_environment()["ALIEN_SANDBOX_EXPECTED_EXEC_UID"],
2667            "60001"
2668        );
2669        for platform in [
2670            Platform::Local,
2671            Platform::Kubernetes,
2672            Platform::Azure,
2673            Platform::Gcp,
2674        ] {
2675            let error = sandbox
2676                .validate_for_platform(platform)
2677                .expect_err("cannot grant a privilege boundary the backend lacks");
2678            assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2679            assert!(error.message.contains("privilegedSupervisor"));
2680        }
2681        for uid in [0, u32::MAX] {
2682            sandbox.privileged_supervisor.as_mut().unwrap().command_uid = uid;
2683            let error = sandbox
2684                .validate_for_platform(Platform::Aws)
2685                .expect_err("invalid uid must fail at plan time");
2686            assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2687        }
2688    }
2689
2690    #[test]
2691    fn unknown_fields_are_rejected() {
2692        let json = r#"{
2693            "id": "sbx",
2694            "code": {"type": "image", "image": "ubuntu:24.04"},
2695            "limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
2696            "egress": {"mode": "deny"},
2697            "lifecycle": {},
2698            "unexpected": true
2699        }"#;
2700
2701        serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
2702    }
2703
2704    #[test]
2705    fn serialization_roundtrips() {
2706        let sandbox = sandbox_with(
2707            SandboxEgress::AllowDomains {
2708                domains: vec!["example.com".to_string()],
2709            },
2710            vec![8080, 9090],
2711        );
2712
2713        let json = serde_json::to_string(&sandbox).expect("serializes");
2714        let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
2715        assert_eq!(sandbox, restored);
2716    }
2717
2718    #[test]
2719    fn id_is_immutable_across_updates() {
2720        let original = sandbox_with(SandboxEgress::None, vec![]);
2721        let renamed = Sandbox::new("other".to_string())
2722            .code(SandboxCode::Image {
2723                image: "ubuntu".to_string(),
2724                bundled_from: None,
2725            })
2726            .limits(
2727                original
2728                    .limits
2729                    .clone()
2730                    .expect("the fixture declares limits"),
2731            )
2732            .egress(SandboxEgress::None)
2733            .lifecycle(SandboxLifecyclePolicy {
2734                max_lifetime_seconds: None,
2735                idle_pause_seconds: None,
2736            })
2737            .build();
2738
2739        original
2740            .validate_update(&original.clone())
2741            .expect("an unchanged config is a valid update");
2742        original
2743            .validate_update(&renamed)
2744            .expect_err("renaming a sandbox is not an update");
2745    }
2746
2747    /// Azure declares an idle-pause policy but not a wall-clock ceiling.
2748    ///
2749    /// The two travel together in `SandboxLifecyclePolicy` and are gated separately on purpose:
2750    /// Azure pauses on idle and has no maximum lifetime, so accepting one and refusing the
2751    /// other is the honest split rather than an inconsistency.
2752    #[test]
2753    fn azure_takes_an_idle_policy_and_still_refuses_a_lifetime_ceiling() {
2754        let with_policy = |lifecycle: SandboxLifecyclePolicy| {
2755            Sandbox::new("sbx".to_string())
2756                .code(SandboxCode::Image {
2757                    image: "ubuntu".to_string(),
2758                    bundled_from: None,
2759                })
2760                .egress(SandboxEgress::Allow)
2761                .lifecycle(lifecycle)
2762                .build()
2763                .validate_for_platform(Platform::Azure)
2764        };
2765
2766        with_policy(SandboxLifecyclePolicy {
2767            max_lifetime_seconds: None,
2768            idle_pause_seconds: Some(900),
2769        })
2770        .expect("Azure pauses a sandbox on idle");
2771
2772        let error = with_policy(SandboxLifecyclePolicy {
2773            max_lifetime_seconds: Some(3600),
2774            idle_pause_seconds: None,
2775        })
2776        .expect_err("Azure has no wall-clock ceiling to enforce one with");
2777        assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
2778        assert!(
2779            error.message.contains("sandboxLifetime"),
2780            "names the capability: {}",
2781            error.message
2782        );
2783    }
2784
2785    /// An allowlist naming nothing is a deny-all wearing an allowlist's label.
2786    ///
2787    /// It renders as a `Deny` default with no rules — the shape the Azure provider adds a
2788    /// catch-all to avoid — and a reader scanning the declaration sees "allowDomains" and reads
2789    /// the opposite of what it does.
2790    #[test]
2791    fn an_allowlist_with_no_domains_is_refused() {
2792        let declared = |domains: Vec<String>| {
2793            Sandbox::new("sbx".to_string())
2794                .code(SandboxCode::Image {
2795                    image: "ubuntu".to_string(),
2796                    bundled_from: None,
2797                })
2798                .egress(SandboxEgress::AllowDomains { domains })
2799                .lifecycle(SandboxLifecyclePolicy {
2800                    max_lifetime_seconds: None,
2801                    idle_pause_seconds: None,
2802                })
2803                .build()
2804                .validate_for_platform(Platform::Azure)
2805        };
2806
2807        let error = declared(vec![]).expect_err("an empty allowlist must be refused");
2808        assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
2809
2810        declared(vec!["api.example.com".to_string()])
2811            .expect("a named domain is what an allowlist is for");
2812    }
2813
2814    /// The two expressible modes map to the boolean; a host list maps to nothing so the caller has
2815    /// to refuse rather than silently pick a side.
2816    #[test]
2817    fn internet_access_switch_maps_only_the_two_expressible_modes() {
2818        assert_eq!(SandboxEgress::Allow.internet_access_switch(), Some(true));
2819        assert_eq!(SandboxEgress::None.internet_access_switch(), Some(false));
2820        assert_eq!(
2821            SandboxEgress::AllowDomains {
2822                domains: vec!["api.example.com".to_string()]
2823            }
2824            .internet_access_switch(),
2825            None,
2826            "a host list has no boolean and must not be approximated"
2827        );
2828    }
2829
2830    /// A sandbox resource as a stack state recorded it before `session` became `lifecycle` and
2831    /// `idleSuspendSeconds` became `idlePauseSeconds`. Such a state is still what a deployment
2832    /// that old holds, and reading it is the first step of updating or deleting that deployment.
2833    #[test]
2834    fn stack_state_written_before_the_lifecycle_rename_still_reads() {
2835        let stored: crate::StackResourceState = serde_json::from_value(serde_json::json!({
2836            "type": "sandbox",
2837            "config": {
2838                "id": "sandbox",
2839                "code": {
2840                    "type": "image",
2841                    "image": "s3://example-bundles/analysis/v1/bundle.zip"
2842                },
2843                "type": "sandbox",
2844                "egress": { "mode": "allow" },
2845                "session": { "maxLifetimeSeconds": 28800, "idleSuspendSeconds": 600 }
2846            },
2847            "status": "running",
2848            "outputs": {
2849                "type": "sandbox",
2850                "identifier": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox",
2851                "parentName": "arn:aws:lambda:us-east-2:123456789012:microvm-image:example-sandbox"
2852            },
2853            "lifecycle": "frozen",
2854            "dependencies": [
2855                { "id": "management", "type": "remote-stack-management" },
2856                { "id": "access", "type": "resource-access" }
2857            ],
2858            "controllerPlatform": "aws"
2859        }))
2860        .expect("a stack state written before the rename must still deserialize");
2861
2862        let expected = Sandbox::new("sandbox".to_string())
2863            .code(SandboxCode::Image {
2864                image: "s3://example-bundles/analysis/v1/bundle.zip".to_string(),
2865                bundled_from: None,
2866            })
2867            .egress(SandboxEgress::Allow)
2868            .lifecycle(SandboxLifecyclePolicy {
2869                max_lifetime_seconds: Some(28_800),
2870                idle_pause_seconds: Some(600),
2871            })
2872            .build();
2873        assert_eq!(stored.config.downcast_ref::<Sandbox>(), Some(&expected));
2874
2875        let rewritten = serde_json::to_value(&stored.config).expect("the sandbox serializes");
2876        assert_eq!(
2877            rewritten["lifecycle"],
2878            serde_json::json!({ "maxLifetimeSeconds": 28800, "idlePauseSeconds": 600 }),
2879            "the next write stores the current names"
2880        );
2881        assert!(rewritten.get("session").is_none());
2882    }
2883}