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 sessions inside it.
4//! Session identity is never in here — sessions are created at runtime and the provider is the
5//! record, so a binding describes the parent only.
6
7use super::BindingValue;
8use crate::SandboxEgress;
9use serde::{Deserialize, Serialize};
10
11/// Represents a sandbox binding for creating and reaching sandbox sessions.
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 as sessions 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/// AWS sandbox binding configuration.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39pub struct AwsSandboxBinding {
40    /// MicroVM image ARN that scopes this sandbox's sessions
41    pub image_arn: BindingValue<String>,
42    /// Image version. Sessions are enumerated by image and version together, so a rolled
43    /// version remains a cleanup scope until its own MicroVMs are gone.
44    pub image_version: BindingValue<String>,
45    /// Region the MicroVMs run in
46    pub region: BindingValue<String>,
47    /// Execution role attached to each MicroVM, distinct from the workload's own role
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub execution_role_arn: Option<BindingValue<String>>,
50    /// Egress connectors every session is started with.
51    ///
52    /// Carried rather than implied: a MicroVM started with no connector reaches the public
53    /// internet, so an empty list here is `allow`, not `deny`. The declared mode is realised by
54    /// which connector setup built, and the session has to be started with it.
55    #[serde(default, skip_serializing_if = "Vec::is_empty")]
56    pub egress_connector_arns: Vec<BindingValue<String>>,
57    /// Ports a preview capability may be minted for.
58    ///
59    /// Carried because the token is what grants ingress: `CreateMicrovmAuthToken` mints access to
60    /// whatever port it is asked for, so "a port not listed here can never be exposed" is only
61    /// true if the declared list reaches the code that mints.
62    #[serde(default, skip_serializing_if = "Vec::is_empty")]
63    pub preview_ports: Vec<u16>,
64    /// Idle seconds after which a session suspends, if the declaration asked for one.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub idle_suspend_seconds: Option<u32>,
67    /// Wall-clock ceiling on a session, if the declaration asked for one.
68    ///
69    /// Enforced by Lambda rather than by us: `RunMicrovm` takes it as
70    /// `maximumDurationInSeconds` and terminates the MicroVM when it elapses.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub max_lifetime_seconds: Option<u32>,
73    /// Whether the declaration asked for open egress.
74    ///
75    /// Carried because an empty connector list cannot otherwise be read: a MicroVM started with
76    /// no connector reaches the internet, so a `deny` binding stripped of its connectors would be
77    /// indistinguishable from `allow`. Absent means `deny`, which is the answer that fails closed.
78    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
79    pub allow_egress: bool,
80}
81
82/// Azure sandbox binding configuration.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(rename_all = "camelCase")]
85pub struct AzureSandboxBinding {
86    /// Sandbox group that scopes every sandbox, image, snapshot and secret
87    pub sandbox_group: BindingValue<String>,
88    /// ADC data-plane endpoint, which is separate from the ARM control plane
89    pub data_plane_endpoint: BindingValue<String>,
90    /// Region the sandbox group lives in; selects the per-region ADC endpoint
91    pub region: BindingValue<String>,
92    /// Resource group the sandbox group sits in. The data-plane path is scoped by it, and the
93    /// Azure client config does not carry one.
94    pub resource_group: BindingValue<String>,
95    /// Outbound policy every session is created with, as declared.
96    ///
97    /// Carried whole rather than as a flag: the data plane's default action is `Allow`, so a
98    /// session created without a policy is an open one, and a hostname list has no boolean to
99    /// travel in.
100    pub egress: SandboxEgress,
101    /// Idle seconds after which a session suspends, if the declaration asked for one.
102    ///
103    /// Carried because the data plane takes it at create and nowhere else: a policy that does not
104    /// travel with the create body is a declaration the sandbox never hears about.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub idle_suspend_seconds: Option<u32>,
107    /// Catalog disk image every session is created from, taken from the declaration's `code`.
108    ///
109    /// Carried rather than hardcoded in the provider because the declaration is the only place
110    /// that knows it, and a sandbox running an image its author did not choose is the one Azure
111    /// gap that fails without an error.
112    pub disk_image: BindingValue<String>,
113}
114
115/// GCP Agent Platform sandbox binding configuration.
116///
117/// Sessions have a durable parent to address: an Agent Engine provisioned at deploy and reached
118/// through a regional endpoint.
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "camelCase")]
121pub struct GcpAgentPlatformSandboxBinding {
122    /// Agent Engine that parents every session. Sessions are created and enumerated under it,
123    /// so a binding without it can neither reach nor reap them.
124    pub engine: BindingValue<String>,
125    /// Template every session is created from. It carries the image digest, the ceilings and the
126    /// egress rules, so a session created without it runs an unpinned image with none applied.
127    pub template: BindingValue<String>,
128    /// Region selecting the regional aiplatform endpoint. The engine is regional with no global
129    /// alias, so the endpoint cannot be derived without it.
130    pub region: BindingValue<String>,
131    /// Seconds a session may live, from the declaration. Carried only when one was declared; an
132    /// absent value takes the service default, which is why it is not defaulted here.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub session_ttl_seconds: Option<u32>,
135}
136
137/// Kubernetes sandbox binding configuration.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase")]
140pub struct KubernetesSandboxBinding {
141    /// Namespace sandbox pods are created in
142    pub namespace: BindingValue<String>,
143    /// Runtime class every sandbox pod must carry, such as `gvisor` or `kata`
144    pub runtime_class: BindingValue<String>,
145    /// Label selector identifying this sandbox's pods, used for enumeration and reaping
146    pub selector: BindingValue<String>,
147    /// Session broker served by the operator. Claiming a pod is a `PATCH` on pods, which must
148    /// not reach the application.
149    pub broker_url: BindingValue<String>,
150    /// Secret holding the capability signing key, by name. The binding names it; only the
151    /// broker can read it.
152    pub key_name: BindingValue<String>,
153    /// Where Kubernetes mounted the pod's own ServiceAccount token. A path, not a secret: the
154    /// platform put the file there and the broker verifies it with a `TokenReview`.
155    pub token_path: BindingValue<String>,
156}
157
158/// Local sandbox binding configuration.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(rename_all = "camelCase")]
161pub struct LocalSandboxBinding {
162    /// Loopback endpoint of the local sandbox manager
163    pub manager_url: BindingValue<String>,
164    /// Key scoping this sandbox's sessions within the manager
165    pub sandbox_key: BindingValue<String>,
166    /// File holding the route's bearer token. A locator, not the token: a binding is
167    /// serialized into the workload's environment, and a secret there is a secret in state.
168    pub token_path: BindingValue<String>,
169}
170
171impl SandboxBinding {
172    /// Creates an AWS sandbox binding.
173    pub fn aws(
174        image_arn: impl Into<BindingValue<String>>,
175        image_version: impl Into<BindingValue<String>>,
176        region: impl Into<BindingValue<String>>,
177    ) -> Self {
178        Self::Aws(AwsSandboxBinding {
179            image_arn: image_arn.into(),
180            image_version: image_version.into(),
181            region: region.into(),
182            execution_role_arn: None,
183            egress_connector_arns: Vec::new(),
184            preview_ports: Vec::new(),
185            idle_suspend_seconds: None,
186            max_lifetime_seconds: None,
187            allow_egress: false,
188        })
189    }
190
191    /// Creates an Azure sandbox binding.
192    pub fn azure(
193        sandbox_group: impl Into<BindingValue<String>>,
194        data_plane_endpoint: impl Into<BindingValue<String>>,
195        region: impl Into<BindingValue<String>>,
196        resource_group: impl Into<BindingValue<String>>,
197        disk_image: impl Into<BindingValue<String>>,
198        egress: SandboxEgress,
199        idle_suspend_seconds: Option<u32>,
200    ) -> Self {
201        Self::Azure(AzureSandboxBinding {
202            sandbox_group: sandbox_group.into(),
203            data_plane_endpoint: data_plane_endpoint.into(),
204            region: region.into(),
205            resource_group: resource_group.into(),
206            egress,
207            idle_suspend_seconds,
208            disk_image: disk_image.into(),
209        })
210    }
211
212    /// Creates a GCP Agent Platform sandbox binding.
213    pub fn gcp_agent_platform(
214        engine: impl Into<BindingValue<String>>,
215        template: impl Into<BindingValue<String>>,
216        region: impl Into<BindingValue<String>>,
217        session_ttl_seconds: Option<u32>,
218    ) -> Self {
219        Self::GcpAgentPlatform(GcpAgentPlatformSandboxBinding {
220            engine: engine.into(),
221            template: template.into(),
222            region: region.into(),
223            session_ttl_seconds,
224        })
225    }
226
227    /// Creates a Kubernetes sandbox binding.
228    pub fn kubernetes(
229        namespace: impl Into<BindingValue<String>>,
230        runtime_class: impl Into<BindingValue<String>>,
231        selector: impl Into<BindingValue<String>>,
232        broker_url: impl Into<BindingValue<String>>,
233        key_name: impl Into<BindingValue<String>>,
234        token_path: impl Into<BindingValue<String>>,
235    ) -> Self {
236        Self::Kubernetes(KubernetesSandboxBinding {
237            namespace: namespace.into(),
238            runtime_class: runtime_class.into(),
239            selector: selector.into(),
240            broker_url: broker_url.into(),
241            key_name: key_name.into(),
242            token_path: token_path.into(),
243        })
244    }
245
246    /// Creates a local sandbox binding.
247    pub fn local(
248        manager_url: impl Into<BindingValue<String>>,
249        sandbox_key: impl Into<BindingValue<String>>,
250        token_path: impl Into<BindingValue<String>>,
251    ) -> Self {
252        Self::Local(LocalSandboxBinding {
253            manager_url: manager_url.into(),
254            sandbox_key: sandbox_key.into(),
255            token_path: token_path.into(),
256        })
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::bindings::{ContainerBinding, KvBinding};
264
265    #[test]
266    fn every_variant_roundtrips() {
267        let bindings = vec![
268            SandboxBinding::aws(
269                "arn:aws:lambda:us-east-2:1:microvm-image:sbx",
270                "3",
271                "us-east-2",
272            ),
273            SandboxBinding::azure(
274                "sbg1",
275                "https://management.swedencentral.azuredevcompute.io",
276                "swedencentral",
277                "rg",
278                "ubuntu",
279                SandboxEgress::Deny,
280                None,
281            ),
282            SandboxBinding::gcp_agent_platform(
283                "projects/p/locations/us-central1/reasoningEngines/1",
284                "projects/p/locations/us-central1/sandboxTemplates/agent",
285                "us-central1",
286                Some(3600),
287            ),
288            SandboxBinding::kubernetes(
289                "alien-sandboxes",
290                "gvisor",
291                "alien.dev/sandbox=agent",
292                "http://alien-operator.alien.svc:8080",
293                "alien-sandbox-agent-capability",
294                "/var/run/secrets/kubernetes.io/serviceaccount/token",
295            ),
296            SandboxBinding::local(
297                "http://127.0.0.1:8931",
298                "agent",
299                "/state/sandbox-manager.token",
300            ),
301        ];
302
303        for binding in bindings {
304            let json = serde_json::to_string(&binding).expect("serializes");
305            let restored: SandboxBinding = serde_json::from_str(&json).expect("deserializes");
306            assert_eq!(binding, restored, "roundtrip changed the binding: {json}");
307        }
308    }
309
310    /// The Agent Platform binding carries an egress-bearing template, so there is no safe default
311    /// for a missing required field: a binding stripped of one must fail to load rather than
312    /// deserialize into a session with no image, no limits and open egress. `sessionTtlSeconds` is
313    /// the one field that may be absent, and its absence must still parse.
314    #[test]
315    fn agent_platform_required_fields_have_no_default() {
316        let binding = SandboxBinding::gcp_agent_platform(
317            "projects/p/locations/us-central1/reasoningEngines/1",
318            "projects/p/locations/us-central1/sandboxTemplates/agent",
319            "us-central1",
320            Some(3600),
321        );
322        let full = serde_json::to_value(&binding).expect("serializes");
323
324        for required in ["engine", "template", "region"] {
325            let mut stripped = full.clone();
326            stripped
327                .as_object_mut()
328                .expect("binding serializes as an object")
329                .remove(required)
330                .expect("the field is present before it is stripped");
331            serde_json::from_value::<SandboxBinding>(stripped)
332                .expect_err(&format!("a binding missing '{required}' must not load"));
333        }
334
335        let mut without_ttl = full;
336        without_ttl
337            .as_object_mut()
338            .expect("binding serializes as an object")
339            .remove("sessionTtlSeconds")
340            .expect("the fixture set a ttl");
341        let restored: SandboxBinding =
342            serde_json::from_value(without_ttl).expect("an absent ttl still loads");
343        assert_eq!(
344            restored,
345            SandboxBinding::gcp_agent_platform(
346                "projects/p/locations/us-central1/reasoningEngines/1",
347                "projects/p/locations/us-central1/sandboxTemplates/agent",
348                "us-central1",
349                None,
350            ),
351            "an absent ttl deserializes as None"
352        );
353    }
354
355    #[test]
356    fn service_tags_are_prefixed_and_distinct() {
357        let tags: Vec<String> = vec![
358            SandboxBinding::aws("a", "1", "r"),
359            SandboxBinding::azure("g", "e", "r", "rg", "ubuntu", SandboxEgress::Deny, None),
360            SandboxBinding::gcp_agent_platform("e", "t", "us-central1", None),
361            SandboxBinding::kubernetes("n", "gvisor", "s", "http://op:8080", "k", "/t"),
362            SandboxBinding::local("u", "k", "t"),
363        ]
364        .iter()
365        .map(|binding| {
366            serde_json::to_value(binding).expect("serializes")["service"]
367                .as_str()
368                .expect("has a service tag")
369                .to_string()
370        })
371        .collect();
372
373        for tag in &tags {
374            assert!(tag.starts_with("sandbox-"), "tag '{tag}' is not namespaced");
375        }
376
377        let mut unique = tags.clone();
378        unique.sort();
379        unique.dedup();
380        assert_eq!(unique.len(), tags.len(), "duplicate service tags: {tags:?}");
381    }
382
383    /// The failure the bindings AGENTS.md warns about: with `tag = "service"`, serde picks the
384    /// variant on that field alone, so a shared tag lets one resource's binding deserialize as
385    /// another's by dropping the fields that differ.
386    #[test]
387    fn a_sandbox_binding_cannot_deserialize_as_another_resource() {
388        let json = serde_json::to_string(&SandboxBinding::local(
389            "http://127.0.0.1:8931",
390            "agent",
391            "/state/sandbox-manager.token",
392        ))
393        .expect("serializes");
394
395        serde_json::from_str::<KvBinding>(&json)
396            .expect_err("a sandbox binding must not parse as a KV binding");
397        serde_json::from_str::<ContainerBinding>(&json)
398            .expect_err("a sandbox binding must not parse as a container binding");
399    }
400
401    #[test]
402    fn another_resource_binding_cannot_deserialize_as_a_sandbox() {
403        let json = serde_json::to_string(&ContainerBinding::local("api", "http://api.svc:8080"))
404            .expect("serializes");
405
406        serde_json::from_str::<SandboxBinding>(&json)
407            .expect_err("a container binding must not parse as a sandbox binding");
408    }
409}