1use super::BindingValue;
8use crate::{EgressPolicy, SandboxEgress};
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(tag = "service")]
18pub enum SandboxBinding {
19 #[serde(rename = "sandbox-aws")]
21 Aws(AwsSandboxBinding),
22 #[serde(rename = "sandbox-azure")]
24 Azure(AzureSandboxBinding),
25 #[serde(rename = "sandbox-gcp-agent-platform")]
27 GcpAgentPlatform(GcpAgentPlatformSandboxBinding),
28 #[serde(rename = "sandbox-kubernetes")]
30 Kubernetes(KubernetesSandboxBinding),
31 #[serde(rename = "sandbox-local")]
33 Local(LocalSandboxBinding),
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
39#[serde(untagged)]
40pub enum SandboxEgressBinding {
41 Gateway(SandboxEgressGateway),
43 Policy(SandboxEgress),
45 Defaults {
47 #[serde(rename = "defaultPolicy")]
48 default_policy: EgressPolicy,
49 },
50}
51
52impl SandboxEgressBinding {
53 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 pub fn default_policy(&self) -> Option<&EgressPolicy> {
63 match self {
64 Self::Defaults { default_policy } => Some(default_policy),
65 _ => None,
66 }
67 }
68 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase", deny_unknown_fields)]
118pub struct SandboxEgressGateway {
119 pub container: String,
121 pub audience: String,
123 pub signing_key: SandboxEgressSigningKey,
125 pub kid: String,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub admin_ca_pem: Option<String>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub replicas: Option<SandboxEgressReplicas>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase", deny_unknown_fields)]
139pub struct SandboxEgressReplicas {
140 pub dns: String,
142 pub port: u16,
144 pub count: u32,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "camelCase", deny_unknown_fields)]
151pub struct SandboxEgressSigningKey {
152 pub vault: String,
154 pub key: String,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(rename_all = "camelCase")]
161pub struct AwsSandboxBinding {
162 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub default_policy: Option<EgressPolicy>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub egress: Option<SandboxEgressBinding>,
168 pub image_arn: BindingValue<String>,
170 pub image_version: BindingValue<String>,
172 pub region: BindingValue<String>,
174 #[serde(skip_serializing_if = "Option::is_none")]
176 pub execution_role_arn: Option<BindingValue<String>>,
177 #[serde(default, skip_serializing_if = "Vec::is_empty")]
183 pub egress_connector_arns: Vec<BindingValue<String>>,
184 #[serde(default, skip_serializing_if = "Vec::is_empty")]
190 pub preview_ports: Vec<u16>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub idle_pause_seconds: Option<u32>,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub max_lifetime_seconds: Option<u32>,
200 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
206 pub allow_egress: bool,
207}
208
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(rename_all = "camelCase")]
212pub struct AzureSandboxBinding {
213 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
216 pub agent: bool,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub default_policy: Option<EgressPolicy>,
220 pub sandbox_group: BindingValue<String>,
222 pub data_plane_endpoint: BindingValue<String>,
224 pub region: BindingValue<String>,
226 pub resource_group: BindingValue<String>,
229 pub egress: SandboxEgressBinding,
235 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub idle_pause_seconds: Option<u32>,
241 #[serde(default, skip_serializing_if = "Vec::is_empty")]
244 pub preview_ports: Vec<u16>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub max_lifetime_seconds: Option<u32>,
249 pub disk_image: BindingValue<String>,
253 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "camelCase")]
270pub struct GcpAgentPlatformSandboxBinding {
271 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub default_policy: Option<EgressPolicy>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub egress: Option<SandboxEgressBinding>,
277 pub engine: BindingValue<String>,
280 pub template: BindingValue<String>,
283 pub region: BindingValue<String>,
286 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub max_lifetime_seconds: Option<u32>,
290 #[serde(default)]
293 pub allow_egress: bool,
294}
295
296#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct KubernetesSandboxBinding {
300 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub default_policy: Option<EgressPolicy>,
303 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub egress: Option<SandboxEgressBinding>,
306 pub namespace: BindingValue<String>,
308 pub runtime_class: BindingValue<String>,
310 pub selector: BindingValue<String>,
312 pub broker_url: BindingValue<String>,
315 pub key_name: BindingValue<String>,
318 pub token_path: BindingValue<String>,
321}
322
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "camelCase")]
326pub struct LocalSandboxBinding {
327 #[serde(default, skip_serializing_if = "Option::is_none")]
329 pub default_policy: Option<EgressPolicy>,
330 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub egress: Option<SandboxEgressBinding>,
333 pub manager_url: BindingValue<String>,
335 pub sandbox_key: BindingValue<String>,
337 pub token_path: BindingValue<String>,
340}
341
342impl SandboxBinding {
343 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 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 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 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 cpu: None,
411 memory: None,
412 disk: None,
413 })
414 }
415
416 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 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 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 #[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 #[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}