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