Skip to main content

alien_core/bindings/
sandbox.rs

1//! Sandbox binding definitions.
2//!
3//! Carries what a provider needs to reach the durable parent and create sandboxes inside it.
4//! Sandbox identity is never in here — sandboxes are created at runtime and the provider is the
5//! record, so a binding describes the parent only.
6
7use super::BindingValue;
8use crate::{EgressPolicy, SandboxEgress};
9use serde::{Deserialize, Serialize};
10
11/// Represents a sandbox binding for creating and reaching sandboxes.
12///
13/// Service tags are prefixed with `sandbox-` because serde selects the variant on the `service`
14/// field alone. An unprefixed `local` would deserialize as another resource's local binding by
15/// silently dropping the fields that differ.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(tag = "service")]
18pub enum SandboxBinding {
19    /// AWS Lambda MicroVM sandboxes
20    #[serde(rename = "sandbox-aws")]
21    Aws(AwsSandboxBinding),
22    /// Azure Container Apps Sandboxes
23    #[serde(rename = "sandbox-azure")]
24    Azure(AzureSandboxBinding),
25    /// GCP Agent Platform sandboxes, created under a durable Agent Engine
26    #[serde(rename = "sandbox-gcp-agent-platform")]
27    GcpAgentPlatform(GcpAgentPlatformSandboxBinding),
28    /// Sandbox pods under a sandboxed runtime class
29    #[serde(rename = "sandbox-kubernetes")]
30    Kubernetes(KubernetesSandboxBinding),
31    /// Local Docker sandboxes managed by the local sandbox manager
32    #[serde(rename = "sandbox-local")]
33    Local(LocalSandboxBinding),
34}
35
36/// Gateway handoff, or a policy-only binding from deployments without a gateway.
37/// Policy-only bindings remain readable but cannot enforce per-sandbox changes.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
39#[serde(untagged)]
40pub enum SandboxEgressBinding {
41    /// Complete gateway configuration from the deployment controller.
42    Gateway(SandboxEgressGateway),
43    /// Legacy declaration; no runtime enforcement capability is implied.
44    Policy(SandboxEgress),
45    /// Default policy for a new Internet declaration, retained in controller state.
46    Defaults {
47        #[serde(rename = "defaultPolicy")]
48        default_policy: EgressPolicy,
49    },
50}
51
52impl SandboxEgressBinding {
53    /// Declaration used for validation before any backend call.
54    pub fn declaration(&self) -> &SandboxEgress {
55        match self {
56            Self::Gateway(_) => &SandboxEgress::Internet,
57            Self::Policy(value) => value,
58            Self::Defaults { .. } => &SandboxEgress::Internet,
59        }
60    }
61    /// Default runtime policy for an Internet declaration.
62    pub fn default_policy(&self) -> Option<&EgressPolicy> {
63        match self {
64            Self::Defaults { default_policy } => Some(default_policy),
65            _ => None,
66        }
67    }
68    /// Gateway configuration, absent on older deployments.
69    pub fn gateway(&self) -> Option<&SandboxEgressGateway> {
70        match self {
71            Self::Gateway(value) => Some(value),
72            Self::Policy(_) | Self::Defaults { .. } => None,
73        }
74    }
75}
76
77impl<'de> Deserialize<'de> for SandboxEgressBinding {
78    fn deserialize<D: serde::Deserializer<'de>>(
79        deserializer: D,
80    ) -> std::result::Result<Self, D::Error> {
81        #[derive(Deserialize)]
82        #[serde(untagged)]
83        enum Input {
84            Gateway(SandboxEgressGateway),
85            Policy(SandboxEgress),
86            Defaults {
87                #[serde(rename = "defaultPolicy")]
88                default_policy: EgressPolicy,
89            },
90        }
91        Ok(match Input::deserialize(deserializer)? {
92            Input::Gateway(value) => Self::Gateway(value),
93            Input::Policy(value) => Self::Policy(value),
94            Input::Defaults { default_policy } => Self::Defaults { default_policy },
95        })
96    }
97}
98impl From<&crate::Sandbox> for SandboxEgressBinding {
99    fn from(value: &crate::Sandbox) -> Self {
100        match &value.default_policy {
101            Some(default_policy) => Self::Defaults {
102                default_policy: default_policy.clone(),
103            },
104            None => Self::Policy(value.egress.clone()),
105        }
106    }
107}
108
109impl From<SandboxEgress> for SandboxEgressBinding {
110    fn from(value: SandboxEgress) -> Self {
111        Self::Policy(value)
112    }
113}
114
115/// Public binding metadata. Private key material never belongs in a binding.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase", deny_unknown_fields)]
118pub struct SandboxEgressGateway {
119    /// Linked gateway Container binding; its internal URL is resolved at runtime.
120    pub container: String,
121    /// Deployment prefix and resource id.
122    pub audience: String,
123    /// Vault locator for the deployment's signing key.
124    pub signing_key: SandboxEgressSigningKey,
125    /// Key id published in the gateway's rotation set.
126    pub kid: String,
127    /// Trust root for an admin listener using a deployment-issued TLS certificate.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub admin_ca_pem: Option<String>,
130    /// Replicas that must each acknowledge a policy write. Absent when the gateway
131    /// replicates writes itself behind one admin address.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub replicas: Option<SandboxEgressReplicas>,
134    /// Bindings of the services this sandbox resource links, by resource id. Each carries the
135    /// service's internal URLs only, which the gateway reaches inside the deployment. Every
136    /// command a sandbox runs receives them as `ALIEN_<ID>_BINDING`. Omitted without links.
137    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
138    pub links: std::collections::BTreeMap<String, super::ContainerBinding>,
139}
140
141/// Ready gateway replicas a policy write must reach.
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
143#[serde(rename_all = "camelCase", deny_unknown_fields)]
144pub struct SandboxEgressReplicas {
145    /// Name that resolves, through the workload's DNS search path, to every ready replica.
146    /// Ignored when `addresses` is set.
147    #[serde(default)]
148    pub dns: String,
149    /// Fixed replica IPs (static NICs, as on Azure's setup-created gateway VMs). When set,
150    /// no DNS lookup happens and every listed address must acknowledge a write.
151    #[serde(default, skip_serializing_if = "Vec::is_empty")]
152    pub addresses: Vec<String>,
153    /// Admin port on each replica.
154    pub port: u16,
155    /// Replicas the gateway runs. A write refuses when fewer are resolvable.
156    pub count: u32,
157    /// Lowest gateway admin protocol this binding can serve (`GET /v1/protocol`). 0 skips the
158    /// check, for gateways that replicate behind one address and are updated with the binding.
159    /// Azure's setup-created VMs are updated only by re-running setup, so they set it.
160    #[serde(default, skip_serializing_if = "is_zero")]
161    pub min_protocol: u32,
162    /// The port sandboxes dial on each address when it is not the gateway's own proxy port: GCP
163    /// sandboxes reach the gateway VMs on one port that crosses from Google's sandbox tenant into
164    /// the VPC, and the VM redirects it to the proxy. 0 means the gateway's own proxy port, as
165    /// every other backend uses. Setup records it once.
166    #[serde(default, skip_serializing_if = "is_zero_port")]
167    pub proxy_port: u16,
168}
169
170/// The gateway admin protocol this release speaks and serves at `GET /v1/protocol`. Bump only
171/// for an incompatible change: a newer gateway must keep serving older bindings.
172pub const EGRESS_GATEWAY_ADMIN_PROTOCOL: u32 = 1;
173
174fn is_zero(value: &u32) -> bool {
175    *value == 0
176}
177
178fn is_zero_port(value: &u16) -> bool {
179    *value == 0
180}
181
182/// Management-only vault reference for an Ed25519 PKCS#8 key.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(rename_all = "camelCase", deny_unknown_fields)]
185pub struct SandboxEgressSigningKey {
186    /// Name of the vault binding, normally `secrets`.
187    pub vault: String,
188    /// Secret name, normally `sandbox-egress-signing-key`.
189    pub key: String,
190}
191
192/// AWS sandbox binding configuration.
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(rename_all = "camelCase")]
195pub struct AwsSandboxBinding {
196    /// Default runtime policy when create omits one.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub default_policy: Option<EgressPolicy>,
199    /// Declared internet access. Absent only in bindings created by older releases.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub egress: Option<SandboxEgressBinding>,
202    /// MicroVM image ARN that scopes the sandboxes this binding creates
203    pub image_arn: BindingValue<String>,
204    /// Image version that `RunMicrovm` launches.
205    pub image_version: BindingValue<String>,
206    /// Region the MicroVMs run in
207    pub region: BindingValue<String>,
208    /// Execution role attached to each MicroVM, distinct from the workload's own role
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub execution_role_arn: Option<BindingValue<String>>,
211    /// Egress connectors every sandbox is started with.
212    ///
213    /// Carried rather than implied: a MicroVM started with no connector reaches the public
214    /// internet, so an empty list here is `allow`, not `deny`. The declared mode is realised by
215    /// which connector setup built, and the sandbox has to be started with it.
216    #[serde(default, skip_serializing_if = "Vec::is_empty")]
217    pub egress_connector_arns: Vec<BindingValue<String>>,
218    /// Ports a preview capability may be minted for.
219    ///
220    /// Carried because the token is what grants ingress: `CreateMicrovmAuthToken` mints access to
221    /// whatever port it is asked for, so "a port not listed here can never be exposed" is only
222    /// true if the declared list reaches the code that mints.
223    #[serde(default, skip_serializing_if = "Vec::is_empty")]
224    pub preview_ports: Vec<u16>,
225    /// Idle seconds after which a sandbox pauses, if the declaration asked for one.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub idle_pause_seconds: Option<u32>,
228    /// Wall-clock ceiling on a sandbox, if the declaration asked for one.
229    ///
230    /// Enforced by Lambda rather than by us: `RunMicrovm` takes it as
231    /// `maximumDurationInSeconds` and terminates the MicroVM when it elapses.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub max_lifetime_seconds: Option<u32>,
234    /// Whether the declaration asked for open egress.
235    ///
236    /// Carried because an empty connector list cannot otherwise be read: a MicroVM started with
237    /// no connector reaches the internet, so a `deny` binding stripped of its connectors would be
238    /// indistinguishable from `allow`. Absent means `deny`, which is the answer that fails closed.
239    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
240    pub allow_egress: bool,
241}
242
243/// Azure sandbox binding configuration.
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(rename_all = "camelCase")]
246pub struct AzureSandboxBinding {
247    /// New packages serve commands and files through a bounded root agent. Absent in released
248    /// native images, which retain their original transport until explicitly rebuilt.
249    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
250    pub agent: bool,
251    /// Default runtime policy when create omits one.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub default_policy: Option<EgressPolicy>,
254    /// Sandbox group that scopes every sandbox, image, snapshot and secret
255    pub sandbox_group: BindingValue<String>,
256    /// ADC data-plane endpoint, which is separate from the ARM control plane
257    pub data_plane_endpoint: BindingValue<String>,
258    /// Region the sandbox group lives in; selects the per-region ADC endpoint
259    pub region: BindingValue<String>,
260    /// Resource group the sandbox group sits in. The data-plane path is scoped by it, and the
261    /// Azure client config does not carry one.
262    pub resource_group: BindingValue<String>,
263    /// Outbound policy every sandbox is created with, as declared.
264    ///
265    /// Carried whole rather than as a flag: the data plane's default action is `Allow`, so a
266    /// sandbox created without a policy is an open one, and a hostname list has no boolean to
267    /// travel in.
268    pub egress: SandboxEgressBinding,
269    /// Idle seconds after which a sandbox pauses, if the declaration asked for one.
270    ///
271    /// Carried because the data plane takes it at create and nowhere else: a policy that does not
272    /// travel with the create body is a declaration the sandbox never hears about.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub idle_pause_seconds: Option<u32>,
275    /// Ports a preview capability may be granted for. The in-sandbox agent only forwards to ports
276    /// it is told about, so the same list reaches it as `ALIEN_SANDBOX_PREVIEW_PORTS` at create.
277    #[serde(default, skip_serializing_if = "Vec::is_empty")]
278    pub preview_ports: Vec<u16>,
279    /// Wall-clock ceiling on a sandbox, if the declaration asked for one. Azure has no ceiling of
280    /// its own, so it travels to the binding that stamps it on each sandbox for the reaper.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub max_lifetime_seconds: Option<u32>,
283    /// Catalog name or registry image every sandbox is created from, as `code` declares it. A
284    /// registry image is resolved by label to the disk image the controller built, so the value
285    /// stays one a setup package can render.
286    pub disk_image: BindingValue<String>,
287    /// Sandbox ceilings in the data plane's own units, from the declaration. Optional because a
288    /// binding from an earlier release carries none — a required field would fail to deserialize
289    /// on an already-running deployment. Absent takes the data plane's own default.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub cpu: Option<BindingValue<String>>,
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub memory: Option<BindingValue<String>>,
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub disk: Option<BindingValue<String>>,
296}
297
298/// GCP Agent Platform sandbox binding configuration.
299///
300/// Sandboxes have a durable parent to address: an Agent Engine provisioned at deploy and reached
301/// through a regional endpoint.
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
303#[serde(rename_all = "camelCase")]
304pub struct GcpAgentPlatformSandboxBinding {
305    /// Default runtime policy when create omits one.
306    #[serde(default, skip_serializing_if = "Option::is_none")]
307    pub default_policy: Option<EgressPolicy>,
308    /// Declared internet access. Absent only in bindings created by older releases.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub egress: Option<SandboxEgressBinding>,
311    /// Agent Engine that parents every sandbox. Sandboxes are created and enumerated under it,
312    /// so a binding without it can neither reach nor reap them.
313    pub engine: BindingValue<String>,
314    /// Template every sandbox is created from. It carries the image digest, the ceilings and the
315    /// egress rules, so a sandbox created without it runs an unpinned image with none applied.
316    pub template: BindingValue<String>,
317    /// Region selecting the regional aiplatform endpoint. The engine is regional with no global
318    /// alias, so the endpoint cannot be derived without it.
319    pub region: BindingValue<String>,
320    /// Seconds a sandbox may live, from the declaration. Carried only when one was declared; an
321    /// absent value takes the service default, which is why it is not defaulted here.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub max_lifetime_seconds: Option<u32>,
324    /// Whether the declaration asked for open egress. The template enforces the policy; this lets a
325    /// reader that never sees the template tell `allow` from `deny`. Absent means `deny`.
326    #[serde(default)]
327    pub allow_egress: bool,
328    /// Service account that signs the edge credential for preview requests. Preview is available
329    /// only when it is present: the edge host comes from each sandbox's own connection info.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub preview_service_account: Option<BindingValue<String>>,
332    /// Ports the declaration names for preview. The template declares the same ports; carried so
333    /// a preview for any other port is refused before a call is spent, and so the agent learns
334    /// which ports the sandbox declared (its template cannot carry an environment).
335    #[serde(default, skip_serializing_if = "Vec::is_empty")]
336    pub preview_ports: Vec<u16>,
337    /// `address:port` of the deployment's Private Service Connect endpoint. A template with a
338    /// network attachment has private ingress, so its sandboxes answer only through this endpoint
339    /// (with the edge credential `previewServiceAccount` signs); absent for every other template.
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub private_endpoint: Option<String>,
342}
343
344/// Kubernetes sandbox binding configuration.
345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
346#[serde(rename_all = "camelCase")]
347pub struct KubernetesSandboxBinding {
348    /// Default runtime policy when create omits one.
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub default_policy: Option<EgressPolicy>,
351    /// Declared internet access. Absent only in bindings created by older releases.
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub egress: Option<SandboxEgressBinding>,
354    /// Namespace sandbox pods are created in
355    pub namespace: BindingValue<String>,
356    /// Runtime class every sandbox pod must carry, such as `gvisor` or `kata`
357    pub runtime_class: BindingValue<String>,
358    /// Label selector identifying this sandbox's pods, used for enumeration and reaping
359    pub selector: BindingValue<String>,
360    /// Sandbox broker served by the operator. Claiming a pod is a `PATCH` on pods, which must
361    /// not reach the application.
362    pub broker_url: BindingValue<String>,
363    /// Secret holding the capability signing key, by name. The binding names it; only the
364    /// broker can read it.
365    pub key_name: BindingValue<String>,
366    /// Where Kubernetes mounted the pod's own ServiceAccount token. A path, not a secret: the
367    /// platform put the file there and the broker verifies it with a `TokenReview`.
368    pub token_path: BindingValue<String>,
369}
370
371/// Local sandbox binding configuration.
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373#[serde(rename_all = "camelCase")]
374pub struct LocalSandboxBinding {
375    /// Default runtime policy when create omits one.
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub default_policy: Option<EgressPolicy>,
378    /// Declared internet access. Absent only in bindings created by older releases.
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub egress: Option<SandboxEgressBinding>,
381    /// Loopback endpoint of the local sandbox manager
382    pub manager_url: BindingValue<String>,
383    /// Key scoping this binding's sandboxes within the manager
384    pub sandbox_key: BindingValue<String>,
385    /// File holding the route's bearer token. A locator, not the token: a binding is
386    /// serialized into the workload's environment, and a secret there is a secret in state.
387    pub token_path: BindingValue<String>,
388    /// Bindings of the services this sandbox links, by resource id, with their internal URLs,
389    /// which the sandbox's egress gateway reaches on `deployment-network`. Every command a
390    /// sandbox runs receives them as `ALIEN_<ID>_BINDING`. Omitted without links.
391    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
392    pub links: std::collections::BTreeMap<String, super::ContainerBinding>,
393}
394
395impl SandboxBinding {
396    /// Egress handoff, including declarations stored by earlier releases.
397    pub fn egress(&self) -> Option<&SandboxEgressBinding> {
398        match self {
399            Self::Aws(value) => value.egress.as_ref(),
400            Self::Azure(value) => Some(&value.egress),
401            Self::GcpAgentPlatform(value) => value.egress.as_ref(),
402            Self::Kubernetes(value) => value.egress.as_ref(),
403            Self::Local(value) => value.egress.as_ref(),
404        }
405    }
406    /// Default runtime policy, including the released allowDomains alias.
407    pub fn default_policy(&self) -> Option<&EgressPolicy> {
408        let explicit = match self {
409            Self::Aws(value) => value.default_policy.as_ref(),
410            Self::Azure(value) => value.default_policy.as_ref(),
411            Self::GcpAgentPlatform(value) => value.default_policy.as_ref(),
412            Self::Kubernetes(value) => value.default_policy.as_ref(),
413            Self::Local(value) => value.default_policy.as_ref(),
414        };
415        explicit.or_else(|| self.egress().and_then(SandboxEgressBinding::default_policy))
416    }
417
418    /// Creates an AWS sandbox binding.
419    pub fn aws(
420        image_arn: impl Into<BindingValue<String>>,
421        image_version: impl Into<BindingValue<String>>,
422        region: impl Into<BindingValue<String>>,
423    ) -> Self {
424        Self::Aws(AwsSandboxBinding {
425            default_policy: None,
426            egress: None,
427            image_arn: image_arn.into(),
428            image_version: image_version.into(),
429            region: region.into(),
430            execution_role_arn: None,
431            egress_connector_arns: Vec::new(),
432            preview_ports: Vec::new(),
433            idle_pause_seconds: None,
434            max_lifetime_seconds: None,
435            allow_egress: false,
436        })
437    }
438
439    /// Creates an Azure sandbox binding.
440    pub fn azure(
441        sandbox_group: impl Into<BindingValue<String>>,
442        data_plane_endpoint: impl Into<BindingValue<String>>,
443        region: impl Into<BindingValue<String>>,
444        resource_group: impl Into<BindingValue<String>>,
445        disk_image: impl Into<BindingValue<String>>,
446        egress: SandboxEgress,
447        idle_pause_seconds: Option<u32>,
448    ) -> Self {
449        Self::Azure(AzureSandboxBinding {
450            agent: false,
451            default_policy: None,
452            sandbox_group: sandbox_group.into(),
453            data_plane_endpoint: data_plane_endpoint.into(),
454            region: region.into(),
455            resource_group: resource_group.into(),
456            egress: egress.into(),
457            idle_pause_seconds,
458            preview_ports: Vec::new(),
459            max_lifetime_seconds: None,
460            disk_image: disk_image.into(),
461            // Ceilings are set on the struct where a caller has them; a positional argument each
462            // would make this constructor ten wide for the case that rarely carries them.
463            cpu: None,
464            memory: None,
465            disk: None,
466        })
467    }
468
469    /// Creates a GCP Agent Platform binding from the legacy template switch.
470    /// Gateway-backed declarations must supply their explicit egress configuration.
471    pub fn gcp_agent_platform(
472        engine: impl Into<BindingValue<String>>,
473        template: impl Into<BindingValue<String>>,
474        region: impl Into<BindingValue<String>>,
475        max_lifetime_seconds: Option<u32>,
476        allow_egress: bool,
477    ) -> Self {
478        Self::GcpAgentPlatform(GcpAgentPlatformSandboxBinding {
479            default_policy: None,
480            egress: Some(
481                (if allow_egress {
482                    SandboxEgress::Allow
483                } else {
484                    SandboxEgress::None
485                })
486                .into(),
487            ),
488            engine: engine.into(),
489            template: template.into(),
490            region: region.into(),
491            max_lifetime_seconds,
492            allow_egress,
493            preview_service_account: None,
494            preview_ports: Vec::new(),
495            private_endpoint: None,
496        })
497    }
498
499    /// Creates a Kubernetes sandbox binding.
500    pub fn kubernetes(
501        namespace: impl Into<BindingValue<String>>,
502        runtime_class: impl Into<BindingValue<String>>,
503        selector: impl Into<BindingValue<String>>,
504        broker_url: impl Into<BindingValue<String>>,
505        key_name: impl Into<BindingValue<String>>,
506        token_path: impl Into<BindingValue<String>>,
507        egress: Option<SandboxEgress>,
508    ) -> Self {
509        Self::Kubernetes(KubernetesSandboxBinding {
510            default_policy: None,
511            egress: egress.map(Into::into),
512            namespace: namespace.into(),
513            runtime_class: runtime_class.into(),
514            selector: selector.into(),
515            broker_url: broker_url.into(),
516            key_name: key_name.into(),
517            token_path: token_path.into(),
518        })
519    }
520
521    /// Creates a local sandbox binding.
522    pub fn local(
523        manager_url: impl Into<BindingValue<String>>,
524        sandbox_key: impl Into<BindingValue<String>>,
525        token_path: impl Into<BindingValue<String>>,
526        egress: Option<SandboxEgress>,
527    ) -> Self {
528        Self::Local(LocalSandboxBinding {
529            default_policy: None,
530            egress: egress.map(Into::into),
531            manager_url: manager_url.into(),
532            sandbox_key: sandbox_key.into(),
533            token_path: token_path.into(),
534            links: Default::default(),
535        })
536    }
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542    use crate::bindings::{ContainerBinding, KvBinding};
543
544    #[test]
545    fn every_variant_roundtrips() {
546        let bindings = vec![
547            SandboxBinding::aws(
548                "arn:aws:lambda:us-east-2:1:microvm-image:sbx",
549                "3",
550                "us-east-2",
551            ),
552            SandboxBinding::azure(
553                "sbg1",
554                "https://management.swedencentral.azuredevcompute.io",
555                "swedencentral",
556                "rg",
557                "ubuntu",
558                SandboxEgress::None,
559                None,
560            ),
561            SandboxBinding::gcp_agent_platform(
562                "projects/p/locations/us-central1/reasoningEngines/1",
563                "projects/p/locations/us-central1/sandboxTemplates/agent",
564                "us-central1",
565                Some(3600),
566                true,
567            ),
568            SandboxBinding::kubernetes(
569                "alien-sandboxes",
570                "gvisor",
571                "alien.dev/sandbox=agent",
572                "http://alien-operator.alien.svc:8080",
573                "alien-sandbox-agent-capability",
574                "/var/run/secrets/kubernetes.io/serviceaccount/token",
575                None,
576            ),
577            SandboxBinding::local(
578                "http://127.0.0.1:8931",
579                "agent",
580                "/state/sandbox-manager.token",
581                None,
582            ),
583        ];
584
585        for binding in bindings {
586            let json = serde_json::to_string(&binding).expect("serializes");
587            let restored: SandboxBinding = serde_json::from_str(&json).expect("deserializes");
588            assert_eq!(binding, restored, "roundtrip changed the binding: {json}");
589        }
590    }
591
592    /// The Agent Platform binding carries an egress-bearing template, so there is no safe default
593    /// for a missing required field: a binding stripped of one must fail to load rather than
594    /// deserialize into a sandbox with no image, no limits and open egress. `maxLifetimeSeconds` is
595    /// the one field that may be absent, and its absence must still parse.
596    #[test]
597    fn agent_platform_required_fields_have_no_default() {
598        let binding = SandboxBinding::gcp_agent_platform(
599            "projects/p/locations/us-central1/reasoningEngines/1",
600            "projects/p/locations/us-central1/sandboxTemplates/agent",
601            "us-central1",
602            Some(3600),
603            true,
604        );
605        let full = serde_json::to_value(&binding).expect("serializes");
606
607        for required in ["engine", "template", "region"] {
608            let mut stripped = full.clone();
609            stripped
610                .as_object_mut()
611                .expect("binding serializes as an object")
612                .remove(required)
613                .expect("the field is present before it is stripped");
614            serde_json::from_value::<SandboxBinding>(stripped)
615                .expect_err(&format!("a binding missing '{required}' must not load"));
616        }
617
618        let mut without_ttl = full;
619        without_ttl
620            .as_object_mut()
621            .expect("binding serializes as an object")
622            .remove("maxLifetimeSeconds")
623            .expect("the fixture set a ttl");
624        without_ttl
625            .as_object_mut()
626            .expect("binding serializes as an object")
627            .remove("allowEgress")
628            .expect("the fixture allowed egress");
629        without_ttl.as_object_mut().unwrap().remove("egress");
630        let restored: SandboxBinding = serde_json::from_value(without_ttl)
631            .expect("legacy binding without optional fields loads");
632        let SandboxBinding::GcpAgentPlatform(restored) = restored else {
633            panic!("the service tag must select Agent Platform");
634        };
635        assert_eq!(restored.max_lifetime_seconds, None);
636        assert!(!restored.allow_egress, "legacy bindings default to deny");
637        assert_eq!(
638            restored.egress, None,
639            "legacy bindings carry no explicit declaration"
640        );
641    }
642
643    #[test]
644    fn service_tags_are_prefixed_and_distinct() {
645        let tags: Vec<String> = vec![
646            SandboxBinding::aws("a", "1", "r"),
647            SandboxBinding::azure("g", "e", "r", "rg", "ubuntu", SandboxEgress::None, None),
648            SandboxBinding::gcp_agent_platform("e", "t", "us-central1", None, false),
649            SandboxBinding::kubernetes("n", "gvisor", "s", "http://op:8080", "k", "/t", None),
650            SandboxBinding::local("u", "k", "t", None),
651        ]
652        .iter()
653        .map(|binding| {
654            serde_json::to_value(binding).expect("serializes")["service"]
655                .as_str()
656                .expect("has a service tag")
657                .to_string()
658        })
659        .collect();
660
661        for tag in &tags {
662            assert!(tag.starts_with("sandbox-"), "tag '{tag}' is not namespaced");
663        }
664
665        let mut unique = tags.clone();
666        unique.sort();
667        unique.dedup();
668        assert_eq!(unique.len(), tags.len(), "duplicate service tags: {tags:?}");
669    }
670
671    /// The failure the bindings AGENTS.md warns about: with `tag = "service"`, serde picks the
672    /// variant on that field alone, so a shared tag lets one resource's binding deserialize as
673    /// another's by dropping the fields that differ.
674    #[test]
675    fn a_sandbox_binding_cannot_deserialize_as_another_resource() {
676        let json = serde_json::to_string(&SandboxBinding::local(
677            "http://127.0.0.1:8931",
678            "agent",
679            "/state/sandbox-manager.token",
680            None,
681        ))
682        .expect("serializes");
683
684        serde_json::from_str::<KvBinding>(&json)
685            .expect_err("a sandbox binding must not parse as a KV binding");
686        serde_json::from_str::<ContainerBinding>(&json)
687            .expect_err("a sandbox binding must not parse as a container binding");
688    }
689
690    #[test]
691    fn another_resource_binding_cannot_deserialize_as_a_sandbox() {
692        let json = serde_json::to_string(&ContainerBinding::local("api", "http://api.svc:8080"))
693            .expect("serializes");
694
695        serde_json::from_str::<SandboxBinding>(&json)
696            .expect_err("a container binding must not parse as a sandbox binding");
697    }
698
699    /// Every binding that exists today names no proxy port, and must serialize exactly as it did
700    /// before the field: older readers refuse unknown fields.
701    #[test]
702    fn replicas_without_a_proxy_port_serialize_as_before_for_every_backend() {
703        // DNS-resolved replicas (Kubernetes and AWS services), static addresses (Azure's VMs).
704        let dns = SandboxEgressReplicas {
705            dns: "gateway.default.svc".into(),
706            addresses: Vec::new(),
707            port: 3129,
708            count: 2,
709            min_protocol: 0,
710            proxy_port: 0,
711        };
712        let fixed = SandboxEgressReplicas {
713            dns: String::new(),
714            addresses: vec!["10.0.6.4".into(), "10.0.6.5".into()],
715            port: 3129,
716            count: 2,
717            min_protocol: EGRESS_GATEWAY_ADMIN_PROTOCOL,
718            proxy_port: 0,
719        };
720        assert_eq!(
721            serde_json::to_string(&dns).unwrap(),
722            r#"{"dns":"gateway.default.svc","port":3129,"count":2}"#
723        );
724        assert_eq!(
725            serde_json::to_string(&fixed).unwrap(),
726            r#"{"dns":"","addresses":["10.0.6.4","10.0.6.5"],"port":3129,"count":2,"minProtocol":1}"#
727        );
728        // An old binding parses with no proxy port, and a GCP one carries it.
729        let parsed: SandboxEgressReplicas =
730            serde_json::from_str(&serde_json::to_string(&fixed).unwrap()).unwrap();
731        assert_eq!(parsed.proxy_port, 0);
732        let gcp = SandboxEgressReplicas {
733            proxy_port: 22,
734            ..fixed
735        };
736        assert!(serde_json::to_string(&gcp)
737            .unwrap()
738            .ends_with(r#""minProtocol":1,"proxyPort":22}"#));
739    }
740}