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 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub preview_service_account: Option<BindingValue<String>>,
298 #[serde(default, skip_serializing_if = "Vec::is_empty")]
302 pub preview_ports: Vec<u16>,
303}
304
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(rename_all = "camelCase")]
308pub struct KubernetesSandboxBinding {
309 #[serde(default, skip_serializing_if = "Option::is_none")]
311 pub default_policy: Option<EgressPolicy>,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub egress: Option<SandboxEgressBinding>,
315 pub namespace: BindingValue<String>,
317 pub runtime_class: BindingValue<String>,
319 pub selector: BindingValue<String>,
321 pub broker_url: BindingValue<String>,
324 pub key_name: BindingValue<String>,
327 pub token_path: BindingValue<String>,
330}
331
332#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
334#[serde(rename_all = "camelCase")]
335pub struct LocalSandboxBinding {
336 #[serde(default, skip_serializing_if = "Option::is_none")]
338 pub default_policy: Option<EgressPolicy>,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub egress: Option<SandboxEgressBinding>,
342 pub manager_url: BindingValue<String>,
344 pub sandbox_key: BindingValue<String>,
346 pub token_path: BindingValue<String>,
349}
350
351impl SandboxBinding {
352 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 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 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 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 cpu: None,
420 memory: None,
421 disk: None,
422 })
423 }
424
425 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 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 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 #[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 #[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}