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