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}
135
136/// Ready gateway replicas a policy write must reach.
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase", deny_unknown_fields)]
139pub struct SandboxEgressReplicas {
140    /// Name that resolves, through the workload's DNS search path, to every ready replica.
141    /// Ignored when `addresses` is set.
142    #[serde(default)]
143    pub dns: String,
144    /// Fixed replica IPs (static NICs, as on Azure's setup-created gateway VMs). When set,
145    /// no DNS lookup happens and every listed address must acknowledge a write.
146    #[serde(default, skip_serializing_if = "Vec::is_empty")]
147    pub addresses: Vec<String>,
148    /// Admin port on each replica.
149    pub port: u16,
150    /// Replicas the gateway runs. A write refuses when fewer are resolvable.
151    pub count: u32,
152    /// Lowest gateway admin protocol this binding can serve (`GET /v1/protocol`). 0 skips the
153    /// check, for gateways that replicate behind one address and are updated with the binding.
154    /// Azure's setup-created VMs are updated only by re-running setup, so they set it.
155    #[serde(default, skip_serializing_if = "is_zero")]
156    pub min_protocol: u32,
157}
158
159/// The gateway admin protocol this release speaks and serves at `GET /v1/protocol`. Bump only
160/// for an incompatible change: a newer gateway must keep serving older bindings.
161pub const EGRESS_GATEWAY_ADMIN_PROTOCOL: u32 = 1;
162
163fn is_zero(value: &u32) -> bool {
164    *value == 0
165}
166
167/// Management-only vault reference for an Ed25519 PKCS#8 key.
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase", deny_unknown_fields)]
170pub struct SandboxEgressSigningKey {
171    /// Name of the vault binding, normally `secrets`.
172    pub vault: String,
173    /// Secret name, normally `sandbox-egress-signing-key`.
174    pub key: String,
175}
176
177/// AWS sandbox binding configuration.
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "camelCase")]
180pub struct AwsSandboxBinding {
181    /// Default runtime policy when create omits one.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub default_policy: Option<EgressPolicy>,
184    /// Declared internet access. Absent only in bindings created by older releases.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub egress: Option<SandboxEgressBinding>,
187    /// MicroVM image ARN that scopes the sandboxes this binding creates
188    pub image_arn: BindingValue<String>,
189    /// Image version that `RunMicrovm` launches.
190    pub image_version: BindingValue<String>,
191    /// Region the MicroVMs run in
192    pub region: BindingValue<String>,
193    /// Execution role attached to each MicroVM, distinct from the workload's own role
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub execution_role_arn: Option<BindingValue<String>>,
196    /// Egress connectors every sandbox is started with.
197    ///
198    /// Carried rather than implied: a MicroVM started with no connector reaches the public
199    /// internet, so an empty list here is `allow`, not `deny`. The declared mode is realised by
200    /// which connector setup built, and the sandbox has to be started with it.
201    #[serde(default, skip_serializing_if = "Vec::is_empty")]
202    pub egress_connector_arns: Vec<BindingValue<String>>,
203    /// Ports a preview capability may be minted for.
204    ///
205    /// Carried because the token is what grants ingress: `CreateMicrovmAuthToken` mints access to
206    /// whatever port it is asked for, so "a port not listed here can never be exposed" is only
207    /// true if the declared list reaches the code that mints.
208    #[serde(default, skip_serializing_if = "Vec::is_empty")]
209    pub preview_ports: Vec<u16>,
210    /// Idle seconds after which a sandbox pauses, if the declaration asked for one.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub idle_pause_seconds: Option<u32>,
213    /// Wall-clock ceiling on a sandbox, if the declaration asked for one.
214    ///
215    /// Enforced by Lambda rather than by us: `RunMicrovm` takes it as
216    /// `maximumDurationInSeconds` and terminates the MicroVM when it elapses.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub max_lifetime_seconds: Option<u32>,
219    /// Whether the declaration asked for open egress.
220    ///
221    /// Carried because an empty connector list cannot otherwise be read: a MicroVM started with
222    /// no connector reaches the internet, so a `deny` binding stripped of its connectors would be
223    /// indistinguishable from `allow`. Absent means `deny`, which is the answer that fails closed.
224    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
225    pub allow_egress: bool,
226}
227
228/// Azure sandbox binding configuration.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "camelCase")]
231pub struct AzureSandboxBinding {
232    /// New packages serve commands and files through a bounded root agent. Absent in released
233    /// native images, which retain their original transport until explicitly rebuilt.
234    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
235    pub agent: bool,
236    /// Default runtime policy when create omits one.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub default_policy: Option<EgressPolicy>,
239    /// Sandbox group that scopes every sandbox, image, snapshot and secret
240    pub sandbox_group: BindingValue<String>,
241    /// ADC data-plane endpoint, which is separate from the ARM control plane
242    pub data_plane_endpoint: BindingValue<String>,
243    /// Region the sandbox group lives in; selects the per-region ADC endpoint
244    pub region: BindingValue<String>,
245    /// Resource group the sandbox group sits in. The data-plane path is scoped by it, and the
246    /// Azure client config does not carry one.
247    pub resource_group: BindingValue<String>,
248    /// Outbound policy every sandbox is created with, as declared.
249    ///
250    /// Carried whole rather than as a flag: the data plane's default action is `Allow`, so a
251    /// sandbox created without a policy is an open one, and a hostname list has no boolean to
252    /// travel in.
253    pub egress: SandboxEgressBinding,
254    /// Idle seconds after which a sandbox pauses, if the declaration asked for one.
255    ///
256    /// Carried because the data plane takes it at create and nowhere else: a policy that does not
257    /// travel with the create body is a declaration the sandbox never hears about.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub idle_pause_seconds: Option<u32>,
260    /// Ports a preview capability may be granted for. The in-sandbox agent only forwards to ports
261    /// it is told about, so the same list reaches it as `ALIEN_SANDBOX_PREVIEW_PORTS` at create.
262    #[serde(default, skip_serializing_if = "Vec::is_empty")]
263    pub preview_ports: Vec<u16>,
264    /// Wall-clock ceiling on a sandbox, if the declaration asked for one. Azure has no ceiling of
265    /// its own, so it travels to the binding that stamps it on each sandbox for the reaper.
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub max_lifetime_seconds: Option<u32>,
268    /// Catalog name or registry image every sandbox is created from, as `code` declares it. A
269    /// registry image is resolved by label to the disk image the controller built, so the value
270    /// stays one a setup package can render.
271    pub disk_image: BindingValue<String>,
272    /// Sandbox ceilings in the data plane's own units, from the declaration. Optional because a
273    /// binding from an earlier release carries none — a required field would fail to deserialize
274    /// on an already-running deployment. Absent takes the data plane's own default.
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub cpu: Option<BindingValue<String>>,
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub memory: Option<BindingValue<String>>,
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub disk: Option<BindingValue<String>>,
281}
282
283/// GCP Agent Platform sandbox binding configuration.
284///
285/// Sandboxes have a durable parent to address: an Agent Engine provisioned at deploy and reached
286/// through a regional endpoint.
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase")]
289pub struct GcpAgentPlatformSandboxBinding {
290    /// Default runtime policy when create omits one.
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub default_policy: Option<EgressPolicy>,
293    /// Declared internet access. Absent only in bindings created by older releases.
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub egress: Option<SandboxEgressBinding>,
296    /// Agent Engine that parents every sandbox. Sandboxes are created and enumerated under it,
297    /// so a binding without it can neither reach nor reap them.
298    pub engine: BindingValue<String>,
299    /// Template every sandbox is created from. It carries the image digest, the ceilings and the
300    /// egress rules, so a sandbox created without it runs an unpinned image with none applied.
301    pub template: BindingValue<String>,
302    /// Region selecting the regional aiplatform endpoint. The engine is regional with no global
303    /// alias, so the endpoint cannot be derived without it.
304    pub region: BindingValue<String>,
305    /// Seconds a sandbox may live, from the declaration. Carried only when one was declared; an
306    /// absent value takes the service default, which is why it is not defaulted here.
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub max_lifetime_seconds: Option<u32>,
309    /// Whether the declaration asked for open egress. The template enforces the policy; this lets a
310    /// reader that never sees the template tell `allow` from `deny`. Absent means `deny`.
311    #[serde(default)]
312    pub allow_egress: bool,
313    /// Service account that signs the edge credential for preview requests. Preview is available
314    /// only when it is present: the edge host comes from each sandbox's own connection info.
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub preview_service_account: Option<BindingValue<String>>,
317    /// Ports the declaration names for preview. The template declares the same ports; carried so
318    /// a preview for any other port is refused before a call is spent, and so the agent learns
319    /// which ports the sandbox declared (its template cannot carry an environment).
320    #[serde(default, skip_serializing_if = "Vec::is_empty")]
321    pub preview_ports: Vec<u16>,
322}
323
324/// Kubernetes sandbox binding configuration.
325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
326#[serde(rename_all = "camelCase")]
327pub struct KubernetesSandboxBinding {
328    /// Default runtime policy when create omits one.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub default_policy: Option<EgressPolicy>,
331    /// Declared internet access. Absent only in bindings created by older releases.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub egress: Option<SandboxEgressBinding>,
334    /// Namespace sandbox pods are created in
335    pub namespace: BindingValue<String>,
336    /// Runtime class every sandbox pod must carry, such as `gvisor` or `kata`
337    pub runtime_class: BindingValue<String>,
338    /// Label selector identifying this sandbox's pods, used for enumeration and reaping
339    pub selector: BindingValue<String>,
340    /// Sandbox broker served by the operator. Claiming a pod is a `PATCH` on pods, which must
341    /// not reach the application.
342    pub broker_url: BindingValue<String>,
343    /// Secret holding the capability signing key, by name. The binding names it; only the
344    /// broker can read it.
345    pub key_name: BindingValue<String>,
346    /// Where Kubernetes mounted the pod's own ServiceAccount token. A path, not a secret: the
347    /// platform put the file there and the broker verifies it with a `TokenReview`.
348    pub token_path: BindingValue<String>,
349}
350
351/// Local sandbox binding configuration.
352#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(rename_all = "camelCase")]
354pub struct LocalSandboxBinding {
355    /// Default runtime policy when create omits one.
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub default_policy: Option<EgressPolicy>,
358    /// Declared internet access. Absent only in bindings created by older releases.
359    #[serde(default, skip_serializing_if = "Option::is_none")]
360    pub egress: Option<SandboxEgressBinding>,
361    /// Loopback endpoint of the local sandbox manager
362    pub manager_url: BindingValue<String>,
363    /// Key scoping this binding's sandboxes within the manager
364    pub sandbox_key: BindingValue<String>,
365    /// File holding the route's bearer token. A locator, not the token: a binding is
366    /// serialized into the workload's environment, and a secret there is a secret in state.
367    pub token_path: BindingValue<String>,
368}
369
370impl SandboxBinding {
371    /// Egress handoff, including declarations stored by earlier releases.
372    pub fn egress(&self) -> Option<&SandboxEgressBinding> {
373        match self {
374            Self::Aws(value) => value.egress.as_ref(),
375            Self::Azure(value) => Some(&value.egress),
376            Self::GcpAgentPlatform(value) => value.egress.as_ref(),
377            Self::Kubernetes(value) => value.egress.as_ref(),
378            Self::Local(value) => value.egress.as_ref(),
379        }
380    }
381    /// Default runtime policy, including the released allowDomains alias.
382    pub fn default_policy(&self) -> Option<&EgressPolicy> {
383        let explicit = match self {
384            Self::Aws(value) => value.default_policy.as_ref(),
385            Self::Azure(value) => value.default_policy.as_ref(),
386            Self::GcpAgentPlatform(value) => value.default_policy.as_ref(),
387            Self::Kubernetes(value) => value.default_policy.as_ref(),
388            Self::Local(value) => value.default_policy.as_ref(),
389        };
390        explicit.or_else(|| self.egress().and_then(SandboxEgressBinding::default_policy))
391    }
392
393    /// Creates an AWS sandbox binding.
394    pub fn aws(
395        image_arn: impl Into<BindingValue<String>>,
396        image_version: impl Into<BindingValue<String>>,
397        region: impl Into<BindingValue<String>>,
398    ) -> Self {
399        Self::Aws(AwsSandboxBinding {
400            default_policy: None,
401            egress: None,
402            image_arn: image_arn.into(),
403            image_version: image_version.into(),
404            region: region.into(),
405            execution_role_arn: None,
406            egress_connector_arns: Vec::new(),
407            preview_ports: Vec::new(),
408            idle_pause_seconds: None,
409            max_lifetime_seconds: None,
410            allow_egress: false,
411        })
412    }
413
414    /// Creates an Azure sandbox binding.
415    pub fn azure(
416        sandbox_group: impl Into<BindingValue<String>>,
417        data_plane_endpoint: impl Into<BindingValue<String>>,
418        region: impl Into<BindingValue<String>>,
419        resource_group: impl Into<BindingValue<String>>,
420        disk_image: impl Into<BindingValue<String>>,
421        egress: SandboxEgress,
422        idle_pause_seconds: Option<u32>,
423    ) -> Self {
424        Self::Azure(AzureSandboxBinding {
425            agent: false,
426            default_policy: None,
427            sandbox_group: sandbox_group.into(),
428            data_plane_endpoint: data_plane_endpoint.into(),
429            region: region.into(),
430            resource_group: resource_group.into(),
431            egress: egress.into(),
432            idle_pause_seconds,
433            preview_ports: Vec::new(),
434            max_lifetime_seconds: None,
435            disk_image: disk_image.into(),
436            // Ceilings are set on the struct where a caller has them; a positional argument each
437            // would make this constructor ten wide for the case that rarely carries them.
438            cpu: None,
439            memory: None,
440            disk: None,
441        })
442    }
443
444    /// Creates a GCP Agent Platform binding from the legacy template switch.
445    /// Gateway-backed declarations must supply their explicit egress configuration.
446    pub fn gcp_agent_platform(
447        engine: impl Into<BindingValue<String>>,
448        template: impl Into<BindingValue<String>>,
449        region: impl Into<BindingValue<String>>,
450        max_lifetime_seconds: Option<u32>,
451        allow_egress: bool,
452    ) -> Self {
453        Self::GcpAgentPlatform(GcpAgentPlatformSandboxBinding {
454            default_policy: None,
455            egress: Some(
456                (if allow_egress {
457                    SandboxEgress::Allow
458                } else {
459                    SandboxEgress::None
460                })
461                .into(),
462            ),
463            engine: engine.into(),
464            template: template.into(),
465            region: region.into(),
466            max_lifetime_seconds,
467            allow_egress,
468            preview_service_account: None,
469            preview_ports: Vec::new(),
470        })
471    }
472
473    /// Creates a Kubernetes sandbox binding.
474    pub fn kubernetes(
475        namespace: impl Into<BindingValue<String>>,
476        runtime_class: impl Into<BindingValue<String>>,
477        selector: impl Into<BindingValue<String>>,
478        broker_url: impl Into<BindingValue<String>>,
479        key_name: impl Into<BindingValue<String>>,
480        token_path: impl Into<BindingValue<String>>,
481        egress: Option<SandboxEgress>,
482    ) -> Self {
483        Self::Kubernetes(KubernetesSandboxBinding {
484            default_policy: None,
485            egress: egress.map(Into::into),
486            namespace: namespace.into(),
487            runtime_class: runtime_class.into(),
488            selector: selector.into(),
489            broker_url: broker_url.into(),
490            key_name: key_name.into(),
491            token_path: token_path.into(),
492        })
493    }
494
495    /// Creates a local sandbox binding.
496    pub fn local(
497        manager_url: impl Into<BindingValue<String>>,
498        sandbox_key: impl Into<BindingValue<String>>,
499        token_path: impl Into<BindingValue<String>>,
500        egress: Option<SandboxEgress>,
501    ) -> Self {
502        Self::Local(LocalSandboxBinding {
503            default_policy: None,
504            egress: egress.map(Into::into),
505            manager_url: manager_url.into(),
506            sandbox_key: sandbox_key.into(),
507            token_path: token_path.into(),
508        })
509    }
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515    use crate::bindings::{ContainerBinding, KvBinding};
516
517    #[test]
518    fn every_variant_roundtrips() {
519        let bindings = vec![
520            SandboxBinding::aws(
521                "arn:aws:lambda:us-east-2:1:microvm-image:sbx",
522                "3",
523                "us-east-2",
524            ),
525            SandboxBinding::azure(
526                "sbg1",
527                "https://management.swedencentral.azuredevcompute.io",
528                "swedencentral",
529                "rg",
530                "ubuntu",
531                SandboxEgress::None,
532                None,
533            ),
534            SandboxBinding::gcp_agent_platform(
535                "projects/p/locations/us-central1/reasoningEngines/1",
536                "projects/p/locations/us-central1/sandboxTemplates/agent",
537                "us-central1",
538                Some(3600),
539                true,
540            ),
541            SandboxBinding::kubernetes(
542                "alien-sandboxes",
543                "gvisor",
544                "alien.dev/sandbox=agent",
545                "http://alien-operator.alien.svc:8080",
546                "alien-sandbox-agent-capability",
547                "/var/run/secrets/kubernetes.io/serviceaccount/token",
548                None,
549            ),
550            SandboxBinding::local(
551                "http://127.0.0.1:8931",
552                "agent",
553                "/state/sandbox-manager.token",
554                None,
555            ),
556        ];
557
558        for binding in bindings {
559            let json = serde_json::to_string(&binding).expect("serializes");
560            let restored: SandboxBinding = serde_json::from_str(&json).expect("deserializes");
561            assert_eq!(binding, restored, "roundtrip changed the binding: {json}");
562        }
563    }
564
565    /// The Agent Platform binding carries an egress-bearing template, so there is no safe default
566    /// for a missing required field: a binding stripped of one must fail to load rather than
567    /// deserialize into a sandbox with no image, no limits and open egress. `maxLifetimeSeconds` is
568    /// the one field that may be absent, and its absence must still parse.
569    #[test]
570    fn agent_platform_required_fields_have_no_default() {
571        let binding = SandboxBinding::gcp_agent_platform(
572            "projects/p/locations/us-central1/reasoningEngines/1",
573            "projects/p/locations/us-central1/sandboxTemplates/agent",
574            "us-central1",
575            Some(3600),
576            true,
577        );
578        let full = serde_json::to_value(&binding).expect("serializes");
579
580        for required in ["engine", "template", "region"] {
581            let mut stripped = full.clone();
582            stripped
583                .as_object_mut()
584                .expect("binding serializes as an object")
585                .remove(required)
586                .expect("the field is present before it is stripped");
587            serde_json::from_value::<SandboxBinding>(stripped)
588                .expect_err(&format!("a binding missing '{required}' must not load"));
589        }
590
591        let mut without_ttl = full;
592        without_ttl
593            .as_object_mut()
594            .expect("binding serializes as an object")
595            .remove("maxLifetimeSeconds")
596            .expect("the fixture set a ttl");
597        without_ttl
598            .as_object_mut()
599            .expect("binding serializes as an object")
600            .remove("allowEgress")
601            .expect("the fixture allowed egress");
602        without_ttl.as_object_mut().unwrap().remove("egress");
603        let restored: SandboxBinding = serde_json::from_value(without_ttl)
604            .expect("legacy binding without optional fields loads");
605        let SandboxBinding::GcpAgentPlatform(restored) = restored else {
606            panic!("the service tag must select Agent Platform");
607        };
608        assert_eq!(restored.max_lifetime_seconds, None);
609        assert!(!restored.allow_egress, "legacy bindings default to deny");
610        assert_eq!(
611            restored.egress, None,
612            "legacy bindings carry no explicit declaration"
613        );
614    }
615
616    #[test]
617    fn service_tags_are_prefixed_and_distinct() {
618        let tags: Vec<String> = vec![
619            SandboxBinding::aws("a", "1", "r"),
620            SandboxBinding::azure("g", "e", "r", "rg", "ubuntu", SandboxEgress::None, None),
621            SandboxBinding::gcp_agent_platform("e", "t", "us-central1", None, false),
622            SandboxBinding::kubernetes("n", "gvisor", "s", "http://op:8080", "k", "/t", None),
623            SandboxBinding::local("u", "k", "t", None),
624        ]
625        .iter()
626        .map(|binding| {
627            serde_json::to_value(binding).expect("serializes")["service"]
628                .as_str()
629                .expect("has a service tag")
630                .to_string()
631        })
632        .collect();
633
634        for tag in &tags {
635            assert!(tag.starts_with("sandbox-"), "tag '{tag}' is not namespaced");
636        }
637
638        let mut unique = tags.clone();
639        unique.sort();
640        unique.dedup();
641        assert_eq!(unique.len(), tags.len(), "duplicate service tags: {tags:?}");
642    }
643
644    /// The failure the bindings AGENTS.md warns about: with `tag = "service"`, serde picks the
645    /// variant on that field alone, so a shared tag lets one resource's binding deserialize as
646    /// another's by dropping the fields that differ.
647    #[test]
648    fn a_sandbox_binding_cannot_deserialize_as_another_resource() {
649        let json = serde_json::to_string(&SandboxBinding::local(
650            "http://127.0.0.1:8931",
651            "agent",
652            "/state/sandbox-manager.token",
653            None,
654        ))
655        .expect("serializes");
656
657        serde_json::from_str::<KvBinding>(&json)
658            .expect_err("a sandbox binding must not parse as a KV binding");
659        serde_json::from_str::<ContainerBinding>(&json)
660            .expect_err("a sandbox binding must not parse as a container binding");
661    }
662
663    #[test]
664    fn another_resource_binding_cannot_deserialize_as_a_sandbox() {
665        let json = serde_json::to_string(&ContainerBinding::local("api", "http://api.svc:8080"))
666            .expect("serializes");
667
668        serde_json::from_str::<SandboxBinding>(&json)
669            .expect_err("a container binding must not parse as a sandbox binding");
670    }
671}