Skip to main content

alien_core/resources/
sandbox.rs

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