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