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 #[serde(default)]
143 pub dns: String,
144 #[serde(default, skip_serializing_if = "Vec::is_empty")]
147 pub addresses: Vec<String>,
148 pub port: u16,
150 pub count: u32,
152 #[serde(default, skip_serializing_if = "is_zero")]
156 pub min_protocol: u32,
157}
158
159pub const EGRESS_GATEWAY_ADMIN_PROTOCOL: u32 = 1;
162
163fn is_zero(value: &u32) -> bool {
164 *value == 0
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase", deny_unknown_fields)]
170pub struct SandboxEgressSigningKey {
171 pub vault: String,
173 pub key: String,
175}
176
177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "camelCase")]
180pub struct AwsSandboxBinding {
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub default_policy: Option<EgressPolicy>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub egress: Option<SandboxEgressBinding>,
187 pub image_arn: BindingValue<String>,
189 pub image_version: BindingValue<String>,
191 pub region: BindingValue<String>,
193 #[serde(skip_serializing_if = "Option::is_none")]
195 pub execution_role_arn: Option<BindingValue<String>>,
196 #[serde(default, skip_serializing_if = "Vec::is_empty")]
202 pub egress_connector_arns: Vec<BindingValue<String>>,
203 #[serde(default, skip_serializing_if = "Vec::is_empty")]
209 pub preview_ports: Vec<u16>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub idle_pause_seconds: Option<u32>,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub max_lifetime_seconds: Option<u32>,
219 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
225 pub allow_egress: bool,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "camelCase")]
231pub struct AzureSandboxBinding {
232 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
235 pub agent: bool,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub default_policy: Option<EgressPolicy>,
239 pub sandbox_group: BindingValue<String>,
241 pub data_plane_endpoint: BindingValue<String>,
243 pub region: BindingValue<String>,
245 pub resource_group: BindingValue<String>,
248 pub egress: SandboxEgressBinding,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub idle_pause_seconds: Option<u32>,
260 #[serde(default, skip_serializing_if = "Vec::is_empty")]
263 pub preview_ports: Vec<u16>,
264 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub max_lifetime_seconds: Option<u32>,
268 pub disk_image: BindingValue<String>,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub cpu: Option<BindingValue<String>>,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub memory: Option<BindingValue<String>>,
279 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub disk: Option<BindingValue<String>>,
281}
282
283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase")]
289pub struct GcpAgentPlatformSandboxBinding {
290 #[serde(default, skip_serializing_if = "Option::is_none")]
292 pub default_policy: Option<EgressPolicy>,
293 #[serde(default, skip_serializing_if = "Option::is_none")]
295 pub egress: Option<SandboxEgressBinding>,
296 pub engine: BindingValue<String>,
299 pub template: BindingValue<String>,
302 pub region: BindingValue<String>,
305 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub max_lifetime_seconds: Option<u32>,
309 #[serde(default)]
312 pub allow_egress: bool,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub preview_service_account: Option<BindingValue<String>>,
317 #[serde(default, skip_serializing_if = "Vec::is_empty")]
321 pub preview_ports: Vec<u16>,
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
326#[serde(rename_all = "camelCase")]
327pub struct KubernetesSandboxBinding {
328 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub default_policy: Option<EgressPolicy>,
331 #[serde(default, skip_serializing_if = "Option::is_none")]
333 pub egress: Option<SandboxEgressBinding>,
334 pub namespace: BindingValue<String>,
336 pub runtime_class: BindingValue<String>,
338 pub selector: BindingValue<String>,
340 pub broker_url: BindingValue<String>,
343 pub key_name: BindingValue<String>,
346 pub token_path: BindingValue<String>,
349}
350
351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(rename_all = "camelCase")]
354pub struct LocalSandboxBinding {
355 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub default_policy: Option<EgressPolicy>,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
360 pub egress: Option<SandboxEgressBinding>,
361 pub manager_url: BindingValue<String>,
363 pub sandbox_key: BindingValue<String>,
365 pub token_path: BindingValue<String>,
368}
369
370impl SandboxBinding {
371 pub fn egress(&self) -> Option<&SandboxEgressBinding> {
373 match self {
374 Self::Aws(value) => value.egress.as_ref(),
375 Self::Azure(value) => Some(&value.egress),
376 Self::GcpAgentPlatform(value) => value.egress.as_ref(),
377 Self::Kubernetes(value) => value.egress.as_ref(),
378 Self::Local(value) => value.egress.as_ref(),
379 }
380 }
381 pub fn default_policy(&self) -> Option<&EgressPolicy> {
383 let explicit = match self {
384 Self::Aws(value) => value.default_policy.as_ref(),
385 Self::Azure(value) => value.default_policy.as_ref(),
386 Self::GcpAgentPlatform(value) => value.default_policy.as_ref(),
387 Self::Kubernetes(value) => value.default_policy.as_ref(),
388 Self::Local(value) => value.default_policy.as_ref(),
389 };
390 explicit.or_else(|| self.egress().and_then(SandboxEgressBinding::default_policy))
391 }
392
393 pub fn aws(
395 image_arn: impl Into<BindingValue<String>>,
396 image_version: impl Into<BindingValue<String>>,
397 region: impl Into<BindingValue<String>>,
398 ) -> Self {
399 Self::Aws(AwsSandboxBinding {
400 default_policy: None,
401 egress: None,
402 image_arn: image_arn.into(),
403 image_version: image_version.into(),
404 region: region.into(),
405 execution_role_arn: None,
406 egress_connector_arns: Vec::new(),
407 preview_ports: Vec::new(),
408 idle_pause_seconds: None,
409 max_lifetime_seconds: None,
410 allow_egress: false,
411 })
412 }
413
414 pub fn azure(
416 sandbox_group: impl Into<BindingValue<String>>,
417 data_plane_endpoint: impl Into<BindingValue<String>>,
418 region: impl Into<BindingValue<String>>,
419 resource_group: impl Into<BindingValue<String>>,
420 disk_image: impl Into<BindingValue<String>>,
421 egress: SandboxEgress,
422 idle_pause_seconds: Option<u32>,
423 ) -> Self {
424 Self::Azure(AzureSandboxBinding {
425 agent: false,
426 default_policy: None,
427 sandbox_group: sandbox_group.into(),
428 data_plane_endpoint: data_plane_endpoint.into(),
429 region: region.into(),
430 resource_group: resource_group.into(),
431 egress: egress.into(),
432 idle_pause_seconds,
433 preview_ports: Vec::new(),
434 max_lifetime_seconds: None,
435 disk_image: disk_image.into(),
436 cpu: None,
439 memory: None,
440 disk: None,
441 })
442 }
443
444 pub fn gcp_agent_platform(
447 engine: impl Into<BindingValue<String>>,
448 template: impl Into<BindingValue<String>>,
449 region: impl Into<BindingValue<String>>,
450 max_lifetime_seconds: Option<u32>,
451 allow_egress: bool,
452 ) -> Self {
453 Self::GcpAgentPlatform(GcpAgentPlatformSandboxBinding {
454 default_policy: None,
455 egress: Some(
456 (if allow_egress {
457 SandboxEgress::Allow
458 } else {
459 SandboxEgress::None
460 })
461 .into(),
462 ),
463 engine: engine.into(),
464 template: template.into(),
465 region: region.into(),
466 max_lifetime_seconds,
467 allow_egress,
468 preview_service_account: None,
469 preview_ports: Vec::new(),
470 })
471 }
472
473 pub fn kubernetes(
475 namespace: impl Into<BindingValue<String>>,
476 runtime_class: impl Into<BindingValue<String>>,
477 selector: impl Into<BindingValue<String>>,
478 broker_url: impl Into<BindingValue<String>>,
479 key_name: impl Into<BindingValue<String>>,
480 token_path: impl Into<BindingValue<String>>,
481 egress: Option<SandboxEgress>,
482 ) -> Self {
483 Self::Kubernetes(KubernetesSandboxBinding {
484 default_policy: None,
485 egress: egress.map(Into::into),
486 namespace: namespace.into(),
487 runtime_class: runtime_class.into(),
488 selector: selector.into(),
489 broker_url: broker_url.into(),
490 key_name: key_name.into(),
491 token_path: token_path.into(),
492 })
493 }
494
495 pub fn local(
497 manager_url: impl Into<BindingValue<String>>,
498 sandbox_key: impl Into<BindingValue<String>>,
499 token_path: impl Into<BindingValue<String>>,
500 egress: Option<SandboxEgress>,
501 ) -> Self {
502 Self::Local(LocalSandboxBinding {
503 default_policy: None,
504 egress: egress.map(Into::into),
505 manager_url: manager_url.into(),
506 sandbox_key: sandbox_key.into(),
507 token_path: token_path.into(),
508 })
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515 use crate::bindings::{ContainerBinding, KvBinding};
516
517 #[test]
518 fn every_variant_roundtrips() {
519 let bindings = vec![
520 SandboxBinding::aws(
521 "arn:aws:lambda:us-east-2:1:microvm-image:sbx",
522 "3",
523 "us-east-2",
524 ),
525 SandboxBinding::azure(
526 "sbg1",
527 "https://management.swedencentral.azuredevcompute.io",
528 "swedencentral",
529 "rg",
530 "ubuntu",
531 SandboxEgress::None,
532 None,
533 ),
534 SandboxBinding::gcp_agent_platform(
535 "projects/p/locations/us-central1/reasoningEngines/1",
536 "projects/p/locations/us-central1/sandboxTemplates/agent",
537 "us-central1",
538 Some(3600),
539 true,
540 ),
541 SandboxBinding::kubernetes(
542 "alien-sandboxes",
543 "gvisor",
544 "alien.dev/sandbox=agent",
545 "http://alien-operator.alien.svc:8080",
546 "alien-sandbox-agent-capability",
547 "/var/run/secrets/kubernetes.io/serviceaccount/token",
548 None,
549 ),
550 SandboxBinding::local(
551 "http://127.0.0.1:8931",
552 "agent",
553 "/state/sandbox-manager.token",
554 None,
555 ),
556 ];
557
558 for binding in bindings {
559 let json = serde_json::to_string(&binding).expect("serializes");
560 let restored: SandboxBinding = serde_json::from_str(&json).expect("deserializes");
561 assert_eq!(binding, restored, "roundtrip changed the binding: {json}");
562 }
563 }
564
565 #[test]
570 fn agent_platform_required_fields_have_no_default() {
571 let binding = SandboxBinding::gcp_agent_platform(
572 "projects/p/locations/us-central1/reasoningEngines/1",
573 "projects/p/locations/us-central1/sandboxTemplates/agent",
574 "us-central1",
575 Some(3600),
576 true,
577 );
578 let full = serde_json::to_value(&binding).expect("serializes");
579
580 for required in ["engine", "template", "region"] {
581 let mut stripped = full.clone();
582 stripped
583 .as_object_mut()
584 .expect("binding serializes as an object")
585 .remove(required)
586 .expect("the field is present before it is stripped");
587 serde_json::from_value::<SandboxBinding>(stripped)
588 .expect_err(&format!("a binding missing '{required}' must not load"));
589 }
590
591 let mut without_ttl = full;
592 without_ttl
593 .as_object_mut()
594 .expect("binding serializes as an object")
595 .remove("maxLifetimeSeconds")
596 .expect("the fixture set a ttl");
597 without_ttl
598 .as_object_mut()
599 .expect("binding serializes as an object")
600 .remove("allowEgress")
601 .expect("the fixture allowed egress");
602 without_ttl.as_object_mut().unwrap().remove("egress");
603 let restored: SandboxBinding = serde_json::from_value(without_ttl)
604 .expect("legacy binding without optional fields loads");
605 let SandboxBinding::GcpAgentPlatform(restored) = restored else {
606 panic!("the service tag must select Agent Platform");
607 };
608 assert_eq!(restored.max_lifetime_seconds, None);
609 assert!(!restored.allow_egress, "legacy bindings default to deny");
610 assert_eq!(
611 restored.egress, None,
612 "legacy bindings carry no explicit declaration"
613 );
614 }
615
616 #[test]
617 fn service_tags_are_prefixed_and_distinct() {
618 let tags: Vec<String> = vec![
619 SandboxBinding::aws("a", "1", "r"),
620 SandboxBinding::azure("g", "e", "r", "rg", "ubuntu", SandboxEgress::None, None),
621 SandboxBinding::gcp_agent_platform("e", "t", "us-central1", None, false),
622 SandboxBinding::kubernetes("n", "gvisor", "s", "http://op:8080", "k", "/t", None),
623 SandboxBinding::local("u", "k", "t", None),
624 ]
625 .iter()
626 .map(|binding| {
627 serde_json::to_value(binding).expect("serializes")["service"]
628 .as_str()
629 .expect("has a service tag")
630 .to_string()
631 })
632 .collect();
633
634 for tag in &tags {
635 assert!(tag.starts_with("sandbox-"), "tag '{tag}' is not namespaced");
636 }
637
638 let mut unique = tags.clone();
639 unique.sort();
640 unique.dedup();
641 assert_eq!(unique.len(), tags.len(), "duplicate service tags: {tags:?}");
642 }
643
644 #[test]
648 fn a_sandbox_binding_cannot_deserialize_as_another_resource() {
649 let json = serde_json::to_string(&SandboxBinding::local(
650 "http://127.0.0.1:8931",
651 "agent",
652 "/state/sandbox-manager.token",
653 None,
654 ))
655 .expect("serializes");
656
657 serde_json::from_str::<KvBinding>(&json)
658 .expect_err("a sandbox binding must not parse as a KV binding");
659 serde_json::from_str::<ContainerBinding>(&json)
660 .expect_err("a sandbox binding must not parse as a container binding");
661 }
662
663 #[test]
664 fn another_resource_binding_cannot_deserialize_as_a_sandbox() {
665 let json = serde_json::to_string(&ContainerBinding::local("api", "http://api.svc:8080"))
666 .expect("serializes");
667
668 serde_json::from_str::<SandboxBinding>(&json)
669 .expect_err("a container binding must not parse as a sandbox binding");
670 }
671}