1use crate::error::{ErrorData, Result};
15use crate::resource::ResourceRef;
16use crate::Platform;
17use alien_error::AlienError;
18use serde::{Deserialize, Serialize};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
23#[serde(rename_all = "camelCase")]
24pub enum SandboxImageMountType {
25 Nfs,
27 Tmpfs,
29 Bind,
32}
33
34impl SandboxImageMountType {
35 pub fn as_str(self) -> &'static str {
37 match self {
38 Self::Nfs => "nfs",
39 Self::Tmpfs => "tmpfs",
40 Self::Bind => "bind",
41 }
42 }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
48#[serde(rename_all = "camelCase", deny_unknown_fields)]
49pub struct SandboxImageMount {
50 #[serde(rename = "type")]
52 pub mount_type: SandboxImageMountType,
53 pub path: String,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub size: Option<String>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub from: Option<String>,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
71#[serde(rename_all = "camelCase", deny_unknown_fields)]
72pub struct SandboxImageConnection {
73 pub to: ResourceRef,
76 pub port: u16,
78}
79
80#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
86#[serde(rename_all = "camelCase", deny_unknown_fields)]
87pub struct SandboxImagePermissions {
88 #[serde(default, skip_serializing_if = "Vec::is_empty")]
90 pub mounts: Vec<SandboxImageMount>,
91 #[serde(default, skip_serializing_if = "Vec::is_empty")]
93 pub connections: Vec<SandboxImageConnection>,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
100#[serde(rename_all = "camelCase")]
101pub enum PrivateEndpointPlacement {
102 StackNetwork,
104}
105
106pub trait PrivateNetworkEndpoints {
111 fn private_endpoint_placement(&self) -> PrivateEndpointPlacement;
113}
114
115const PROTECTED_PATHS: &[&str] = &[
118 "/opt/alien",
119 "/proc",
120 "/sys",
121 "/dev",
122 "/run",
123 "/etc",
124 "/usr",
125 "/bin",
126 "/sbin",
127 "/boot",
128];
129
130const MAX_TMPFS_BYTES: u64 = 1 << 40;
133
134impl SandboxImagePermissions {
135 pub fn validate(&self, resource_id: &str) -> Result<()> {
139 let invalid = |field: &str, value: &str, reason: &str| {
140 AlienError::new(ErrorData::SandboxLimitInvalid {
141 resource_id: resource_id.to_string(),
142 field: field.to_string(),
143 value: value.to_string(),
144 reason: reason.to_string(),
145 })
146 };
147 if self.mounts.is_empty() && self.connections.is_empty() {
148 return Err(invalid(
149 "imagePermissions",
150 "{}",
151 "declare at least one mount or connection, or leave imagePermissions out",
152 ));
153 }
154 let mut paths = std::collections::BTreeSet::new();
155 for mount in &self.mounts {
156 if let Err(reason) = check_mount_path(&mount.path) {
157 return Err(invalid(
158 "imagePermissions.mounts.path",
159 &mount.path,
160 &reason,
161 ));
162 }
163 if !paths.insert(mount.path.as_str()) {
164 return Err(invalid(
165 "imagePermissions.mounts.path",
166 &mount.path,
167 "declared more than once",
168 ));
169 }
170 let refuse = |field: &str, value: &str, reason: &str| {
171 Err(invalid(
172 &format!("imagePermissions.mounts.{field}"),
173 value,
174 reason,
175 ))
176 };
177 match (mount.mount_type, &mount.size, &mount.from) {
178 (SandboxImageMountType::Tmpfs, None, _) => {
179 return refuse(
180 "size",
181 &mount.path,
182 "a tmpfs mount needs a size, such as \"8Gi\"",
183 )
184 }
185 (SandboxImageMountType::Tmpfs, Some(size), None) => {
186 tmpfs_size_bytes(size)
187 .map_err(|reason| invalid("imagePermissions.mounts.size", size, &reason))?;
188 }
189 (SandboxImageMountType::Nfs | SandboxImageMountType::Bind, Some(size), _) => {
190 return refuse("size", size, "only a tmpfs mount takes a size")
191 }
192 (SandboxImageMountType::Bind, None, None) => {
193 return refuse(
194 "from",
195 &mount.path,
196 "a bind mount needs `from`, the declared mount it places again",
197 )
198 }
199 (SandboxImageMountType::Bind, None, Some(from)) => {
200 if let Err(reason) = check_mount_path(from) {
201 return refuse("from", from, &reason);
202 }
203 let source = self.mounts.iter().find(|source| {
208 source.mount_type == SandboxImageMountType::Tmpfs && from == &source.path
209 });
210 if source.is_none() {
211 return refuse("from", from, "must be the path of a declared tmpfs mount");
212 }
213 let target = self.mounts.iter().any(|target| {
216 target.mount_type == SandboxImageMountType::Nfs
217 && is_under(&mount.path, &target.path)
218 });
219 if !target {
220 return refuse(
221 "path",
222 &mount.path,
223 "a bind must be placed inside a declared nfs mount",
224 );
225 }
226 if is_same_or_under(&mount.path, from) {
227 return refuse(
228 "from",
229 from,
230 "a bind cannot be placed inside its own source",
231 );
232 }
233 }
234 (SandboxImageMountType::Nfs | SandboxImageMountType::Tmpfs, _, Some(from)) => {
235 return refuse("from", from, "only a bind mount takes `from`")
236 }
237 (SandboxImageMountType::Nfs, None, None) => {}
238 }
239 }
240 let mut connections = std::collections::HashSet::new();
241 for connection in &self.connections {
242 let value = format!("{}:{}", connection.to.id, connection.port);
243 if connection.port == 0 {
244 return Err(invalid(
245 "imagePermissions.connections.port",
246 &value,
247 "port 0 names no service",
248 ));
249 }
250 if connection.port == 53 {
251 return Err(invalid(
252 "imagePermissions.connections.port",
253 &value,
254 "DNS always goes through the agent's resolver; port 53 cannot be a direct connection",
255 ));
256 }
257 if !connections.insert((&connection.to, connection.port)) {
258 return Err(invalid(
259 "imagePermissions.connections",
260 &value,
261 "declared more than once",
262 ));
263 }
264 }
265 Ok(())
266 }
267}
268
269fn check_mount_path(path: &str) -> std::result::Result<(), String> {
271 if !path.starts_with('/') {
272 return Err("must be an absolute path".into());
273 }
274 if path == "/" {
275 return Err("cannot mount over the root file system".into());
276 }
277 if path.len() > 1024 {
278 return Err("longer than 1024 bytes".into());
279 }
280 if !path
281 .bytes()
282 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'-' | b'_' | b'.'))
283 {
284 return Err("may contain only letters, digits, '/', '-', '_' and '.'".into());
285 }
286 let segments: Vec<&str> = path[1..].split('/').collect();
287 if segments
288 .iter()
289 .any(|segment| segment.is_empty() || *segment == "." || *segment == "..")
290 {
291 return Err(
292 "must be normalized: no trailing '/', no '//', and no '.' or '..' segments".into(),
293 );
294 }
295 if segments[0].starts_with("lib") {
296 return Err(format!("overlaps the system path /{}", segments[0]));
297 }
298 for protected in PROTECTED_PATHS {
299 if is_same_or_under(path, protected) || is_same_or_under(protected, path) {
300 return Err(format!("overlaps the system path {protected}"));
301 }
302 }
303 Ok(())
304}
305
306fn is_same_or_under(path: &str, ancestor: &str) -> bool {
308 path == ancestor
309 || path
310 .strip_prefix(ancestor)
311 .is_some_and(|rest| rest.starts_with('/'))
312}
313
314fn is_under(path: &str, ancestor: &str) -> bool {
316 path != ancestor && is_same_or_under(path, ancestor)
317}
318
319pub fn tmpfs_size_bytes(size: &str) -> std::result::Result<u64, String> {
321 let digits_end = size
322 .find(|c: char| !c.is_ascii_digit())
323 .unwrap_or(size.len());
324 let (number, suffix) = size.split_at(digits_end);
325 let unit: u64 = match suffix {
326 "" => 1,
327 "k" => 1_000,
328 "M" => 1_000_000,
329 "G" => 1_000_000_000,
330 "T" => 1_000_000_000_000,
331 "Ki" => 1 << 10,
332 "Mi" => 1 << 20,
333 "Gi" => 1 << 30,
334 "Ti" => 1 << 40,
335 _ => {
336 return Err(
337 "must be a whole number with an optional unit (k, M, G, T, Ki, Mi, Gi, Ti)".into(),
338 )
339 }
340 };
341 let number: u64 = number
342 .parse()
343 .map_err(|_| "must start with a whole number, such as \"8Gi\"".to_string())?;
344 let bytes = number
345 .checked_mul(unit)
346 .filter(|bytes| *bytes <= MAX_TMPFS_BYTES)
347 .ok_or_else(|| "must be at most 1Ti".to_string())?;
348 if bytes < 1 << 20 {
349 return Err("must be at least 1Mi".into());
350 }
351 Ok(bytes)
352}
353
354pub(crate) fn validate_lifecycle_argv(
359 resource_id: &str,
360 field: &str,
361 argv: &[String],
362 mounts: &[SandboxImageMount],
363) -> Result<()> {
364 let invalid = |value: &str, reason: &str| {
365 AlienError::new(ErrorData::SandboxLimitInvalid {
366 resource_id: resource_id.to_string(),
367 field: field.to_string(),
368 value: value.to_string(),
369 reason: reason.to_string(),
370 })
371 };
372 let Some(program) = argv.first() else {
373 return Err(invalid("[]", "needs a program to run"));
374 };
375 if !program.starts_with('/') {
376 return Err(invalid(
377 program,
378 "the program must be an absolute path inside the image; there is no PATH lookup",
379 ));
380 }
381 if program[1..]
382 .split('/')
383 .any(|segment| segment.is_empty() || segment == "." || segment == "..")
384 {
385 return Err(invalid(
386 program,
387 "the program path must be normalized: no trailing '/', no '//', and no '.' or '..' \
388 segments",
389 ));
390 }
391 if let Some(mount) = mounts
392 .iter()
393 .find(|mount| is_same_or_under(program, &mount.path))
394 {
395 return Err(invalid(
396 program,
397 &format!(
398 "the program is on the declared mount {}; a lifecycle step must run from the \
399 image's own files",
400 mount.path
401 ),
402 ));
403 }
404 if argv
405 .iter()
406 .any(|argument| argument.contains('\0') || argument.len() > 4096)
407 {
408 return Err(invalid(
409 program,
410 "arguments may not contain NUL or exceed 4096 bytes",
411 ));
412 }
413 if argv.len() > 64 {
414 return Err(invalid(program, "at most 64 arguments"));
415 }
416 Ok(())
417}
418
419pub(crate) fn require_image_permissions_platform(
421 capability: &str,
422 platform: Platform,
423) -> Result<()> {
424 if platform == Platform::Aws {
425 return Ok(());
426 }
427 Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
428 capability: format!("{capability} (available on AWS Lambda MicroVM sandboxes only)"),
429 platform: platform.to_string(),
430 }))
431}
432
433#[cfg(test)]
434mod tests {
435 use super::*;
436 use crate::ResourceType;
437
438 fn mount(
439 mount_type: SandboxImageMountType,
440 path: &str,
441 size: Option<&str>,
442 ) -> SandboxImageMount {
443 SandboxImageMount {
444 mount_type,
445 path: path.into(),
446 size: size.map(Into::into),
447 from: None,
448 }
449 }
450
451 fn connection(id: &str, port: u16) -> SandboxImageConnection {
452 SandboxImageConnection {
453 to: ResourceRef::new(ResourceType::from("acme-files"), id),
454 port,
455 }
456 }
457
458 fn permissions(
459 mounts: Vec<SandboxImageMount>,
460 connections: Vec<SandboxImageConnection>,
461 ) -> SandboxImagePermissions {
462 SandboxImagePermissions {
463 mounts,
464 connections,
465 }
466 }
467
468 #[test]
469 fn the_designed_declaration_is_accepted() {
470 permissions(
471 vec![
472 mount(SandboxImageMountType::Nfs, "/workspace", None),
473 mount(SandboxImageMountType::Tmpfs, "/workspace/tmp", Some("8Gi")),
474 ],
475 vec![connection("workspace-files", 2049)],
476 )
477 .validate("sandboxes")
478 .unwrap();
479 }
480
481 #[test]
482 fn system_and_unnormalized_paths_are_refused() {
483 for path in [
484 "/",
485 "workspace",
486 "/workspace/",
487 "/workspace//tmp",
488 "/workspace/./tmp",
489 "/workspace/../etc",
490 "/opt/alien",
491 "/opt/alien/bin",
492 "/opt",
493 "/proc",
494 "/proc/sys",
495 "/sys",
496 "/dev/shm",
497 "/run",
498 "/run/alien",
499 "/etc",
500 "/usr/local",
501 "/bin",
502 "/sbin",
503 "/lib",
504 "/lib64",
505 "/libx32/foo",
506 "/boot",
507 "/boot/efi",
508 "/work space",
509 "/work,space",
510 ] {
511 let error = permissions(vec![mount(SandboxImageMountType::Nfs, path, None)], vec![])
512 .validate("sandboxes")
513 .expect_err(path);
514 assert!(error.to_string().contains("mounts.path"), "{path}: {error}");
515 }
516 for path in [
518 "/procedures",
519 "/opt/alienware",
520 "/devices",
521 "/running",
522 "/opt/data",
523 ] {
524 permissions(vec![mount(SandboxImageMountType::Nfs, path, None)], vec![])
525 .validate("sandboxes")
526 .unwrap_or_else(|error| panic!("{path}: {error}"));
527 }
528 }
529
530 #[test]
531 fn tmpfs_needs_a_size_and_nfs_takes_none() {
532 assert!(permissions(
533 vec![mount(SandboxImageMountType::Tmpfs, "/scratch", None)],
534 vec![]
535 )
536 .validate("s")
537 .is_err());
538 assert!(permissions(
539 vec![mount(SandboxImageMountType::Nfs, "/scratch", Some("1Gi"))],
540 vec![]
541 )
542 .validate("s")
543 .is_err());
544 for size in ["8", "1.5Gi", "8gb", "2Ti", "", "Gi", "512Ki"] {
545 assert!(
546 permissions(
547 vec![mount(SandboxImageMountType::Tmpfs, "/scratch", Some(size))],
548 vec![]
549 )
550 .validate("s")
551 .is_err(),
552 "{size}"
553 );
554 }
555 assert_eq!(tmpfs_size_bytes("8Gi").unwrap(), 8_589_934_592);
556 assert_eq!(tmpfs_size_bytes("512Mi").unwrap(), 536_870_912);
557 assert_eq!(tmpfs_size_bytes("2G").unwrap(), 2_000_000_000);
558 }
559
560 fn bind(from: &str, path: &str) -> SandboxImageMount {
561 SandboxImageMount {
562 mount_type: SandboxImageMountType::Bind,
563 path: path.into(),
564 size: None,
565 from: Some(from.into()),
566 }
567 }
568
569 #[test]
571 fn a_bind_places_a_declared_mount_again_and_nothing_else() {
572 let tmpfs = || {
573 mount(
574 SandboxImageMountType::Tmpfs,
575 "/var/lib/app/scratch",
576 Some("8Gi"),
577 )
578 };
579 let nfs = || mount(SandboxImageMountType::Nfs, "/workspace", None);
580 permissions(
581 vec![
582 nfs(),
583 tmpfs(),
584 bind("/var/lib/app/scratch", "/workspace/tmp"),
585 ],
586 vec![],
587 )
588 .validate("s")
589 .unwrap();
590
591 for (mounts, why) in [
592 (
593 vec![
594 nfs(),
595 tmpfs(),
596 bind("/var/lib/app/scratch/a", "/workspace/a"),
597 ],
598 "source inside a tmpfs rather than the tmpfs itself (the agent takes only a \
599 declared mount path)",
600 ),
601 (
602 vec![nfs(), bind("/var/lib/app/scratch", "/workspace/tmp")],
603 "undeclared source",
604 ),
605 (vec![nfs(), bind("/etc", "/workspace/etc")], "system source"),
606 (
607 vec![tmpfs(), bind("/var/lib/app/scratch", "/data")],
608 "target outside any nfs mount",
609 ),
610 (
611 vec![nfs(), tmpfs(), bind("/var/lib/app/scratch", "/workspace")],
612 "target is the nfs mount itself",
613 ),
614 (
615 vec![
616 nfs(),
617 mount(SandboxImageMountType::Nfs, "/shared", None),
618 bind("/shared", "/workspace/shared"),
619 ],
620 "nfs source",
621 ),
622 (
623 vec![tmpfs(), bind("/var/lib/app", "/data")],
624 "parent of a mount",
625 ),
626 (
627 vec![
628 tmpfs(),
629 bind("/var/lib/app/scratch", "/var/lib/app/scratch/x"),
630 ],
631 "inside itself",
632 ),
633 (
634 vec![
635 nfs(),
636 tmpfs(),
637 bind("/var/lib/app/scratch", "/workspace/a"),
638 bind("/workspace/a", "/workspace/b"),
639 ],
640 "from a bind",
641 ),
642 (
643 vec![SandboxImageMount {
644 mount_type: SandboxImageMountType::Bind,
645 path: "/x".into(),
646 size: None,
647 from: None,
648 }],
649 "no from",
650 ),
651 (
652 vec![SandboxImageMount {
653 from: Some("/workspace".into()),
654 ..nfs()
655 }],
656 "from on nfs",
657 ),
658 ] {
659 assert!(permissions(mounts, vec![]).validate("s").is_err(), "{why}");
660 }
661 }
662
663 #[test]
664 fn port_53_zero_and_duplicates_are_refused() {
665 for connections in [
666 vec![connection("files", 53)],
667 vec![connection("files", 0)],
668 vec![connection("files", 2049), connection("files", 2049)],
669 ] {
670 assert!(permissions(vec![], connections).validate("s").is_err());
671 }
672 assert!(permissions(
673 vec![
674 mount(SandboxImageMountType::Nfs, "/a", None),
675 mount(SandboxImageMountType::Nfs, "/a", None)
676 ],
677 vec![]
678 )
679 .validate("s")
680 .is_err());
681 assert!(permissions(vec![], vec![]).validate("s").is_err());
682 }
683
684 #[test]
685 fn unknown_fields_are_refused_so_an_older_reader_cannot_drop_them() {
686 for json in [
687 r#"{"mounts":[{"type":"nfs","path":"/w","readOnly":true}]}"#,
688 r#"{"mounts":[],"capabilities":["SYS_ADMIN"]}"#,
689 r#"{"connections":[{"to":{"type":"x","id":"y"},"port":2049,"cidr":"0.0.0.0/0"}]}"#,
690 r#"{"mounts":[{"type":"overlay","path":"/w"}]}"#,
691 ] {
692 serde_json::from_str::<SandboxImagePermissions>(json).expect_err(json);
693 }
694 }
695
696 #[test]
697 fn lifecycle_argv_must_name_an_absolute_program() {
698 validate_lifecycle_argv(
699 "s",
700 "onPause",
701 &["/usr/bin/app".into(), "pause".into()],
702 &[],
703 )
704 .unwrap();
705 assert!(validate_lifecycle_argv("s", "onPause", &[], &[]).is_err());
706 assert!(validate_lifecycle_argv("s", "onPause", &["app".into()], &[]).is_err());
707 assert!(
708 validate_lifecycle_argv("s", "onPause", &["/a".into(), "b\0".into()], &[]).is_err()
709 );
710 }
711
712 fn declared_sandbox() -> crate::Sandbox {
713 let mut sandbox = crate::Sandbox::new("sandboxes".to_string())
714 .code(crate::SandboxCode::Image {
715 image: "s3://bundles/sandboxes.zip".to_string(),
716 bundled_from: None,
717 })
718 .egress(crate::SandboxEgress::Internet)
719 .lifecycle(crate::SandboxLifecyclePolicy::default())
720 .build();
721 sandbox.image_permissions = Some(permissions(
722 vec![mount(SandboxImageMountType::Nfs, "/workspace", None)],
723 vec![connection("workspace-files", 2049)],
724 ));
725 sandbox
726 }
727
728 #[test]
729 fn only_aws_accepts_image_permissions_and_the_refusal_names_the_platform() {
730 declared_sandbox()
731 .validate_for_platform(Platform::Aws)
732 .unwrap();
733 for platform in [
734 Platform::Gcp,
735 Platform::Azure,
736 Platform::Kubernetes,
737 Platform::Local,
738 ] {
739 let error = declared_sandbox()
740 .validate_for_platform(platform)
741 .expect_err("refused off AWS");
742 assert!(error.to_string().contains("imagePermissions"), "{error}");
743 assert!(error.to_string().contains(&platform.to_string()), "{error}");
744 }
745 let mut steps_only = declared_sandbox();
746 steps_only.image_permissions = None;
747 steps_only.lifecycle.on_resume = Some(vec!["/bin/true".into()]);
748 steps_only.validate_for_platform(Platform::Aws).unwrap();
749 let error = steps_only.validate_for_platform(Platform::Gcp).unwrap_err();
750 assert!(error.to_string().contains("onResume"), "{error}");
751
752 let mut pause_only = declared_sandbox();
753 pause_only.image_permissions = None;
754 pause_only.lifecycle.on_pause = Some(vec!["/bin/sync".into()]);
755 pause_only.validate_for_platform(Platform::Aws).unwrap();
756 for platform in [Platform::Azure, Platform::Kubernetes, Platform::Local] {
757 let error = pause_only
758 .validate_for_platform(platform)
759 .expect_err("onPause refused off AWS");
760 assert!(error.to_string().contains("onPause"), "{error}");
761 assert!(error.to_string().contains(&platform.to_string()), "{error}");
762 }
763 }
764
765 #[test]
770 fn lifecycle_programs_under_a_declared_mount_are_refused() {
771 let with_mounts = || {
772 let mut sandbox = declared_sandbox();
773 sandbox.image_permissions = Some(permissions(
774 vec![
775 mount(SandboxImageMountType::Nfs, "/workspace", None),
776 mount(SandboxImageMountType::Tmpfs, "/scratch", Some("64Mi")),
777 SandboxImageMount {
778 mount_type: SandboxImageMountType::Bind,
779 path: "/workspace/cache".into(),
780 size: None,
781 from: Some("/scratch".into()),
782 },
783 ],
784 vec![connection("workspace-files", 2049)],
785 ));
786 sandbox
787 };
788 for field in ["onPause", "onResume"] {
789 let set = |sandbox: &mut crate::Sandbox, program: &str| {
790 let argv = Some(vec![program.to_string(), "pause".to_string()]);
791 if field == "onPause" {
792 sandbox.lifecycle.on_pause = argv;
793 } else {
794 sandbox.lifecycle.on_resume = argv;
795 }
796 };
797 for program in ["/usr/local/bin/app", "/workspaces/app", "/scratchpad"] {
798 let mut sandbox = with_mounts();
799 set(&mut sandbox, program);
800 sandbox
801 .validate_for_platform(Platform::Aws)
802 .unwrap_or_else(|error| panic!("{field} {program}: {error}"));
803 }
804 for program in [
805 "/workspace",
806 "/workspace/bin/pause",
807 "/scratch/pause",
808 "/workspace/cache/pause",
809 "//workspace/bin/pause",
810 "/usr/../workspace/pause",
811 "/./scratch/pause",
812 "/usr/bin/",
813 ] {
814 let mut sandbox = with_mounts();
815 set(&mut sandbox, program);
816 let error = sandbox
817 .validate_for_platform(Platform::Aws)
818 .expect_err(program);
819 assert!(error.to_string().contains(field), "{program}: {error}");
820 }
821 }
822 }
823
824 #[test]
828 fn image_permissions_need_guest_network_egress_and_a_root_image() {
829 let steps_only = || {
830 let mut sandbox = declared_sandbox();
831 sandbox.image_permissions = None;
832 sandbox.lifecycle.on_pause = Some(vec!["/bin/sync".into()]);
833 sandbox
834 };
835 for declared in [declared_sandbox, steps_only] {
836 for egress in [crate::SandboxEgress::Internet, crate::SandboxEgress::None] {
837 let mut sandbox = declared();
838 sandbox.egress = egress;
839 sandbox.validate_for_platform(Platform::Aws).unwrap();
840 sandbox.image_user = Some(0);
841 sandbox.validate_for_platform(Platform::Aws).unwrap();
842 }
843 for egress in [
844 crate::SandboxEgress::Allow,
845 crate::SandboxEgress::AllowDomains {
846 domains: vec!["example.com".into()],
847 },
848 ] {
849 let mut sandbox = declared();
850 sandbox.egress = egress;
851 let error = sandbox
852 .validate_for_platform(Platform::Aws)
853 .expect_err("egress without the guest network");
854 assert!(error.to_string().contains("egress"), "{error}");
855 }
856 let mut sandbox = declared();
857 sandbox.image_user = Some(1000);
858 let error = sandbox
859 .validate_for_platform(Platform::Aws)
860 .expect_err("a non-root image");
861 assert!(error.to_string().contains("root"), "{error}");
862 }
863 }
864
865 #[test]
866 fn a_sandbox_without_image_permissions_serializes_as_before() {
867 let mut sandbox = declared_sandbox();
868 sandbox.image_permissions = None;
869 let json = serde_json::to_value(&sandbox).unwrap();
870 assert!(json.get("imagePermissions").is_none());
871 assert_eq!(json["lifecycle"], serde_json::json!({}));
872
873 let declared = serde_json::to_value(declared_sandbox()).unwrap();
874 assert_eq!(
875 declared["imagePermissions"],
876 serde_json::json!({
877 "mounts": [{"type": "nfs", "path": "/workspace"}],
878 "connections": [{"to": {"type": "acme-files", "id": "workspace-files"}, "port": 2049}]
879 })
880 );
881 let read: crate::Sandbox = serde_json::from_value(declared).unwrap();
882 assert_eq!(read, declared_sandbox());
883 }
884}