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