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}
295
296/// Kubernetes sandbox binding configuration.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct KubernetesSandboxBinding {
300    /// Default runtime policy when create omits one.
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub default_policy: Option<EgressPolicy>,
303    /// Declared internet access. Absent only in bindings created by older releases.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub egress: Option<SandboxEgressBinding>,
306    /// Namespace sandbox pods are created in
307    pub namespace: BindingValue<String>,
308    /// Runtime class every sandbox pod must carry, such as `gvisor` or `kata`
309    pub runtime_class: BindingValue<String>,
310    /// Label selector identifying this sandbox's pods, used for enumeration and reaping
311    pub selector: BindingValue<String>,
312    /// Sandbox broker served by the operator. Claiming a pod is a `PATCH` on pods, which must
313    /// not reach the application.
314    pub broker_url: BindingValue<String>,
315    /// Secret holding the capability signing key, by name. The binding names it; only the
316    /// broker can read it.
317    pub key_name: BindingValue<String>,
318    /// Where Kubernetes mounted the pod's own ServiceAccount token. A path, not a secret: the
319    /// platform put the file there and the broker verifies it with a `TokenReview`.
320    pub token_path: BindingValue<String>,
321}
322
323/// Local sandbox binding configuration.
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "camelCase")]
326pub struct LocalSandboxBinding {
327    /// Default runtime policy when create omits one.
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub default_policy: Option<EgressPolicy>,
330    /// Declared internet access. Absent only in bindings created by older releases.
331    #[serde(default, skip_serializing_if = "Option::is_none")]
332    pub egress: Option<SandboxEgressBinding>,
333    /// Loopback endpoint of the local sandbox manager
334    pub manager_url: BindingValue<String>,
335    /// Key scoping this binding's sandboxes within the manager
336    pub sandbox_key: BindingValue<String>,
337    /// File holding the route's bearer token. A locator, not the token: a binding is
338    /// serialized into the workload's environment, and a secret there is a secret in state.
339    pub token_path: BindingValue<String>,
340}
341
342impl SandboxBinding {
343    /// Egress handoff, including declarations stored by earlier releases.
344    pub fn egress(&self) -> Option<&SandboxEgressBinding> {
345        match self {
346            Self::Aws(value) => value.egress.as_ref(),
347            Self::Azure(value) => Some(&value.egress),
348            Self::GcpAgentPlatform(value) => value.egress.as_ref(),
349            Self::Kubernetes(value) => value.egress.as_ref(),
350            Self::Local(value) => value.egress.as_ref(),
351        }
352    }
353    /// Default runtime policy, including the released allowDomains alias.
354    pub fn default_policy(&self) -> Option<&EgressPolicy> {
355        let explicit = match self {
356            Self::Aws(value) => value.default_policy.as_ref(),
357            Self::Azure(value) => value.default_policy.as_ref(),
358            Self::GcpAgentPlatform(value) => value.default_policy.as_ref(),
359            Self::Kubernetes(value) => value.default_policy.as_ref(),
360            Self::Local(value) => value.default_policy.as_ref(),
361        };
362        explicit.or_else(|| self.egress().and_then(SandboxEgressBinding::default_policy))
363    }
364
365    /// Creates an AWS sandbox binding.
366    pub fn aws(
367        image_arn: impl Into<BindingValue<String>>,
368        image_version: impl Into<BindingValue<String>>,
369        region: impl Into<BindingValue<String>>,
370    ) -> Self {
371        Self::Aws(AwsSandboxBinding {
372            default_policy: None,
373            egress: None,
374            image_arn: image_arn.into(),
375            image_version: image_version.into(),
376            region: region.into(),
377            execution_role_arn: None,
378            egress_connector_arns: Vec::new(),
379            preview_ports: Vec::new(),
380            idle_pause_seconds: None,
381            max_lifetime_seconds: None,
382            allow_egress: false,
383        })
384    }
385
386    /// Creates an Azure sandbox binding.
387    pub fn azure(
388        sandbox_group: impl Into<BindingValue<String>>,
389        data_plane_endpoint: impl Into<BindingValue<String>>,
390        region: impl Into<BindingValue<String>>,
391        resource_group: impl Into<BindingValue<String>>,
392        disk_image: impl Into<BindingValue<String>>,
393        egress: SandboxEgress,
394        idle_pause_seconds: Option<u32>,
395    ) -> Self {
396        Self::Azure(AzureSandboxBinding {
397            agent: false,
398            default_policy: None,
399            sandbox_group: sandbox_group.into(),
400            data_plane_endpoint: data_plane_endpoint.into(),
401            region: region.into(),
402            resource_group: resource_group.into(),
403            egress: egress.into(),
404            idle_pause_seconds,
405            preview_ports: Vec::new(),
406            max_lifetime_seconds: None,
407            disk_image: disk_image.into(),
408            // Ceilings are set on the struct where a caller has them; a positional argument each
409            // would make this constructor ten wide for the case that rarely carries them.
410            cpu: None,
411            memory: None,
412            disk: None,
413        })
414    }
415
416    /// Creates a GCP Agent Platform binding from the legacy template switch.
417    /// Gateway-backed declarations must supply their explicit egress configuration.
418    pub fn gcp_agent_platform(
419        engine: impl Into<BindingValue<String>>,
420        template: impl Into<BindingValue<String>>,
421        region: impl Into<BindingValue<String>>,
422        max_lifetime_seconds: Option<u32>,
423        allow_egress: bool,
424    ) -> Self {
425        Self::GcpAgentPlatform(GcpAgentPlatformSandboxBinding {
426            default_policy: None,
427            egress: Some(
428                (if allow_egress {
429                    SandboxEgress::Allow
430                } else {
431                    SandboxEgress::None
432                })
433                .into(),
434            ),
435            engine: engine.into(),
436            template: template.into(),
437            region: region.into(),
438            max_lifetime_seconds,
439            allow_egress,
440        })
441    }
442
443    /// Creates a Kubernetes sandbox binding.
444    pub fn kubernetes(
445        namespace: impl Into<BindingValue<String>>,
446        runtime_class: impl Into<BindingValue<String>>,
447        selector: impl Into<BindingValue<String>>,
448        broker_url: impl Into<BindingValue<String>>,
449        key_name: impl Into<BindingValue<String>>,
450        token_path: impl Into<BindingValue<String>>,
451        egress: Option<SandboxEgress>,
452    ) -> Self {
453        Self::Kubernetes(KubernetesSandboxBinding {
454            default_policy: None,
455            egress: egress.map(Into::into),
456            namespace: namespace.into(),
457            runtime_class: runtime_class.into(),
458            selector: selector.into(),
459            broker_url: broker_url.into(),
460            key_name: key_name.into(),
461            token_path: token_path.into(),
462        })
463    }
464
465    /// Creates a local sandbox binding.
466    pub fn local(
467        manager_url: impl Into<BindingValue<String>>,
468        sandbox_key: impl Into<BindingValue<String>>,
469        token_path: impl Into<BindingValue<String>>,
470        egress: Option<SandboxEgress>,
471    ) -> Self {
472        Self::Local(LocalSandboxBinding {
473            default_policy: None,
474            egress: egress.map(Into::into),
475            manager_url: manager_url.into(),
476            sandbox_key: sandbox_key.into(),
477            token_path: token_path.into(),
478        })
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485    use crate::bindings::{ContainerBinding, KvBinding};
486
487    #[test]
488    fn every_variant_roundtrips() {
489        let bindings = vec![
490            SandboxBinding::aws(
491                "arn:aws:lambda:us-east-2:1:microvm-image:sbx",
492                "3",
493                "us-east-2",
494            ),
495            SandboxBinding::azure(
496                "sbg1",
497                "https://management.swedencentral.azuredevcompute.io",
498                "swedencentral",
499                "rg",
500                "ubuntu",
501                SandboxEgress::None,
502                None,
503            ),
504            SandboxBinding::gcp_agent_platform(
505                "projects/p/locations/us-central1/reasoningEngines/1",
506                "projects/p/locations/us-central1/sandboxTemplates/agent",
507                "us-central1",
508                Some(3600),
509                true,
510            ),
511            SandboxBinding::kubernetes(
512                "alien-sandboxes",
513                "gvisor",
514                "alien.dev/sandbox=agent",
515                "http://alien-operator.alien.svc:8080",
516                "alien-sandbox-agent-capability",
517                "/var/run/secrets/kubernetes.io/serviceaccount/token",
518                None,
519            ),
520            SandboxBinding::local(
521                "http://127.0.0.1:8931",
522                "agent",
523                "/state/sandbox-manager.token",
524                None,
525            ),
526        ];
527
528        for binding in bindings {
529            let json = serde_json::to_string(&binding).expect("serializes");
530            let restored: SandboxBinding = serde_json::from_str(&json).expect("deserializes");
531            assert_eq!(binding, restored, "roundtrip changed the binding: {json}");
532        }
533    }
534
535    /// The Agent Platform binding carries an egress-bearing template, so there is no safe default
536    /// for a missing required field: a binding stripped of one must fail to load rather than
537    /// deserialize into a sandbox with no image, no limits and open egress. `maxLifetimeSeconds` is
538    /// the one field that may be absent, and its absence must still parse.
539    #[test]
540    fn agent_platform_required_fields_have_no_default() {
541        let binding = SandboxBinding::gcp_agent_platform(
542            "projects/p/locations/us-central1/reasoningEngines/1",
543            "projects/p/locations/us-central1/sandboxTemplates/agent",
544            "us-central1",
545            Some(3600),
546            true,
547        );
548        let full = serde_json::to_value(&binding).expect("serializes");
549
550        for required in ["engine", "template", "region"] {
551            let mut stripped = full.clone();
552            stripped
553                .as_object_mut()
554                .expect("binding serializes as an object")
555                .remove(required)
556                .expect("the field is present before it is stripped");
557            serde_json::from_value::<SandboxBinding>(stripped)
558                .expect_err(&format!("a binding missing '{required}' must not load"));
559        }
560
561        let mut without_ttl = full;
562        without_ttl
563            .as_object_mut()
564            .expect("binding serializes as an object")
565            .remove("maxLifetimeSeconds")
566            .expect("the fixture set a ttl");
567        without_ttl
568            .as_object_mut()
569            .expect("binding serializes as an object")
570            .remove("allowEgress")
571            .expect("the fixture allowed egress");
572        without_ttl.as_object_mut().unwrap().remove("egress");
573        let restored: SandboxBinding = serde_json::from_value(without_ttl)
574            .expect("legacy binding without optional fields loads");
575        let SandboxBinding::GcpAgentPlatform(restored) = restored else {
576            panic!("the service tag must select Agent Platform");
577        };
578        assert_eq!(restored.max_lifetime_seconds, None);
579        assert!(!restored.allow_egress, "legacy bindings default to deny");
580        assert_eq!(
581            restored.egress, None,
582            "legacy bindings carry no explicit declaration"
583        );
584    }
585
586    #[test]
587    fn service_tags_are_prefixed_and_distinct() {
588        let tags: Vec<String> = vec![
589            SandboxBinding::aws("a", "1", "r"),
590            SandboxBinding::azure("g", "e", "r", "rg", "ubuntu", SandboxEgress::None, None),
591            SandboxBinding::gcp_agent_platform("e", "t", "us-central1", None, false),
592            SandboxBinding::kubernetes("n", "gvisor", "s", "http://op:8080", "k", "/t", None),
593            SandboxBinding::local("u", "k", "t", None),
594        ]
595        .iter()
596        .map(|binding| {
597            serde_json::to_value(binding).expect("serializes")["service"]
598                .as_str()
599                .expect("has a service tag")
600                .to_string()
601        })
602        .collect();
603
604        for tag in &tags {
605            assert!(tag.starts_with("sandbox-"), "tag '{tag}' is not namespaced");
606        }
607
608        let mut unique = tags.clone();
609        unique.sort();
610        unique.dedup();
611        assert_eq!(unique.len(), tags.len(), "duplicate service tags: {tags:?}");
612    }
613
614    /// The failure the bindings AGENTS.md warns about: with `tag = "service"`, serde picks the
615    /// variant on that field alone, so a shared tag lets one resource's binding deserialize as
616    /// another's by dropping the fields that differ.
617    #[test]
618    fn a_sandbox_binding_cannot_deserialize_as_another_resource() {
619        let json = serde_json::to_string(&SandboxBinding::local(
620            "http://127.0.0.1:8931",
621            "agent",
622            "/state/sandbox-manager.token",
623            None,
624        ))
625        .expect("serializes");
626
627        serde_json::from_str::<KvBinding>(&json)
628            .expect_err("a sandbox binding must not parse as a KV binding");
629        serde_json::from_str::<ContainerBinding>(&json)
630            .expect_err("a sandbox binding must not parse as a container binding");
631    }
632
633    #[test]
634    fn another_resource_binding_cannot_deserialize_as_a_sandbox() {
635        let json = serde_json::to_string(&ContainerBinding::local("api", "http://api.svc:8080"))
636            .expect("serializes");
637
638        serde_json::from_str::<SandboxBinding>(&json)
639            .expect_err("a container binding must not parse as a sandbox binding");
640    }
641}