1pub const AGENT_PATH: &str = "/usr/local/bin/alien-sandbox-agent";
19
20pub const AGENT_PORT: u16 = 8971;
26
27pub const PREVIEW_CAPABILITY_HEADER: &str = "x-alien-preview-capability";
30
31pub const PREVIEW_PORT_HEADER: &str = "x-alien-preview-port";
33
34pub const CALLER_AUTHORIZATION_HEADER: &str = "x-alien-caller-authorization";
38
39pub const ENV_CALLER_AUTHORIZATION_HEADER: &str = "ALIEN_SANDBOX_CALLER_AUTHORIZATION_HEADER";
42
43pub const PREVIEW_CAPABILITY_MAX_SECONDS: i64 = 15 * 60;
45
46pub const ENV_PROTECTED_MOUNTS: &str = "ALIEN_SANDBOX_PROTECTED_MOUNTS";
51
52pub const ENV_MUST_DROP_KUBE_API: &str = "ALIEN_SANDBOX_MUST_DROP_KUBE_API";
57pub const ENV_MUST_DROP_PUBLIC: &str = "ALIEN_SANDBOX_MUST_DROP_PUBLIC";
62pub const MUST_DROP_PUBLIC_PROBE: &str = "1.1.1.1:443";
64pub const STAGE_PROTECTED_FILES_ARGUMENT: &str = "--stage-protected-files";
66pub const STAGED_AGENT_NAME: &str = "agent";
68pub const STAGED_METADATA_NAME: &str = "opt";
69
70pub const AGENT_MODE: u32 = 0o755;
72
73pub const EXEC_USER: &str = "sandbox";
75
76pub const SESSION_ROOT_MODE: u32 = 0o700;
78
79pub const GCP_AGENT_LOG_FILTER: &str = "info";
81
82pub const IMAGE_ROOT_CAPABILITY_SET: &[(&str, u8)] = &[
89 ("CHOWN", 0),
90 ("DAC_OVERRIDE", 1),
91 ("FOWNER", 3),
92 ("FSETID", 4),
93 ("KILL", 5),
94 ("SETGID", 6),
95 ("SETUID", 7),
96 ("SETPCAP", 8),
97 ("NET_BIND_SERVICE", 10),
98 ("SYS_CHROOT", 18),
99 ("MKNOD", 27),
100 ("AUDIT_WRITE", 29),
101 ("SETFCAP", 31),
102];
103
104pub const IMAGE_ROOT_CAPABILITY_MASK: u32 = {
106 let mut mask = 0u32;
107 let mut index = 0;
108 while index < IMAGE_ROOT_CAPABILITY_SET.len() {
109 mask |= 1 << IMAGE_ROOT_CAPABILITY_SET[index].1;
110 index += 1;
111 }
112 mask
113};
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Isolation {
122 UidSplit,
125 Platform,
128}
129
130impl Isolation {
131 pub fn env_value(self) -> &'static str {
133 match self {
134 Self::UidSplit => "uid-split",
135 Self::Platform => "platform",
136 }
137 }
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum Authorization {
143 Transport,
146 Capability,
148 NativeFile,
150}
151
152impl Authorization {
153 pub fn env_value(self) -> &'static str {
155 match self {
156 Self::Transport => "transport",
157 Self::Capability => "capability",
158 Self::NativeFile => "native-file",
159 }
160 }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub struct SandboxImage {
166 pub exec_uid: u32,
168 pub exec_gid: u32,
170 pub session_root: &'static str,
172 pub port: u16,
174 pub authorization: Authorization,
175 pub isolation: Isolation,
176}
177
178impl SandboxImage {
179 pub fn exec_gid(&self) -> u32 {
181 self.exec_gid
182 }
183
184 pub fn contract_env_vars(&self) -> [(&'static str, String); 6] {
187 [
188 ("ALIEN_SANDBOX_ROOT", self.session_root.to_string()),
189 ("ALIEN_SANDBOX_PORT", self.port.to_string()),
190 (
191 "ALIEN_SANDBOX_AUTHORIZATION",
192 self.authorization.env_value().to_string(),
193 ),
194 ("ALIEN_SANDBOX_EXEC_UID", self.exec_uid.to_string()),
195 ("ALIEN_SANDBOX_EXEC_GID", self.exec_gid().to_string()),
196 (
197 "ALIEN_SANDBOX_ISOLATION",
198 self.isolation.env_value().to_string(),
199 ),
200 ]
201 }
202
203 pub fn user(&self) -> Option<String> {
206 match self.isolation {
207 Isolation::UidSplit => None,
208 Isolation::Platform => Some(format!("{}:{}", self.exec_uid, self.exec_gid())),
209 }
210 }
211
212 pub fn exposed_port(&self) -> String {
214 format!("{}/tcp", self.port)
215 }
216
217 pub fn passwd_entry(&self) -> String {
219 format!(
220 "{EXEC_USER}:x:{uid}:{gid}::{root}:/sbin/nologin",
221 uid = self.exec_uid,
222 gid = self.exec_gid(),
223 root = self.session_root,
224 )
225 }
226
227 pub fn group_entry(&self) -> String {
229 format!("{EXEC_USER}:x:{gid}:", gid = self.exec_gid())
230 }
231}
232
233pub const AWS_MICROVM: SandboxImage = SandboxImage {
239 exec_uid: 60000,
240 exec_gid: 60000,
241 session_root: "/sandbox",
242 port: AGENT_PORT,
243 authorization: Authorization::Transport,
244 isolation: Isolation::UidSplit,
245};
246
247pub const GCP_AGENT_PLATFORM: SandboxImage = SandboxImage {
254 exec_uid: 1000,
255 exec_gid: 1000,
256 session_root: "/sandbox",
257 port: AGENT_PORT,
258 authorization: Authorization::Transport,
259 isolation: Isolation::UidSplit,
260};
261
262pub fn gcp_agent_platform_env() -> Vec<(&'static str, String)> {
264 let mut env = GCP_AGENT_PLATFORM.contract_env_vars().to_vec();
265 env.push(("RUST_LOG", GCP_AGENT_LOG_FILTER.to_string()));
266 env.push(("ALIEN_SANDBOX_IMAGE_COMMAND", "true".into()));
267 env
268}
269
270pub const AZURE_SANDBOX: SandboxImage = SandboxImage {
273 exec_uid: 1000,
274 exec_gid: 1000,
275 session_root: "/sandbox",
276 port: AGENT_PORT,
277 authorization: Authorization::NativeFile,
278 isolation: Isolation::UidSplit,
279};
280
281pub const KUBERNETES_SANDBOX: SandboxImage = SandboxImage {
286 exec_uid: 1000,
287 exec_gid: 1000,
288 session_root: "/sandbox",
289 port: AGENT_PORT,
290 authorization: Authorization::Capability,
291 isolation: Isolation::Platform,
292};
293
294pub const DEFAULT_SANDBOX_BASE_IMAGE: &str = "public.ecr.aws/docker/library/buildpack-deps:26.04@sha256:159ea382e6fb39e62480ee932113f885f7bd787cd4895fc4dc71aebb175077fd";
299
300pub const DEFAULT_SANDBOX_UV_IMAGE: &str = "ghcr.io/astral-sh/uv:0.12.21@sha256:a7aed3216253ee804de3e2d8afa5073baa1a177335345d43845cd4165e43b711";
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub struct SandboxTool {
306 pub package: Option<&'static str>,
309 pub version_command: &'static str,
311}
312
313pub const DEFAULT_SANDBOX_TOOLS: &[SandboxTool] = &[
318 SandboxTool {
319 package: Some("nftables"),
320 version_command: "/usr/sbin/nft --version",
321 },
322 SandboxTool {
323 package: Some("iptables"),
324 version_command: "iptables-nft --version",
325 },
326 SandboxTool {
327 package: Some("nodejs"),
328 version_command: "node --version",
329 },
330 SandboxTool {
331 package: Some("npm"),
332 version_command: "npm --version",
333 },
334 SandboxTool {
335 package: Some("ripgrep"),
336 version_command: "rg --version",
337 },
338 SandboxTool {
339 package: Some("jq"),
340 version_command: "jq --version",
341 },
342 SandboxTool {
343 package: Some("zip"),
344 version_command: "zip -v",
345 },
346 SandboxTool {
347 package: Some("less"),
348 version_command: "less --version",
349 },
350 SandboxTool {
351 package: Some("nano"),
352 version_command: "nano --version",
353 },
354 SandboxTool {
355 package: Some("vim-tiny"),
356 version_command: "vim.tiny --version",
357 },
358 SandboxTool {
359 package: Some("htop"),
360 version_command: "htop --version",
361 },
362 SandboxTool {
363 package: None,
364 version_command: "uv --version",
365 },
366 SandboxTool {
367 package: None,
368 version_command: "uvx --version",
369 },
370];
371
372pub fn identity_setup(image: &SandboxImage) -> String {
374 format!(
375 r#"RUN test ! -L /etc/passwd && test ! -L /etc/group && test ! -L {root} \
376 && touch /etc/passwd /etc/group \
377 && chown 0:0 /etc/passwd /etc/group && chmod 0644 /etc/passwd /etc/group \
378 && (awk -F: '$3 == {uid} {{ found=1 }} END {{ exit !found }}' /etc/passwd || printf '{passwd}\n' >> /etc/passwd) \
379 && (awk -F: '$3 == {gid} {{ found=1 }} END {{ exit !found }}' /etc/group || printf '{group}\n' >> /etc/group) \
380 && mkdir -p {root} \
381 && chown {uid}:{gid} {root} \
382 && chmod {SESSION_ROOT_MODE:04o} {root}"#,
383 passwd = image.passwd_entry(),
384 group = image.group_entry(),
385 root = image.session_root,
386 uid = image.exec_uid,
387 gid = image.exec_gid(),
388 )
389}
390
391pub fn contract_env(image: &SandboxImage) -> String {
393 let vars: Vec<String> = image
394 .contract_env_vars()
395 .iter()
396 .map(|(name, value)| format!("{name}={value}"))
397 .collect();
398 format!("ENV {}", vars.join(" \\\n "))
399}
400
401pub fn entrypoint(image: &SandboxImage) -> String {
403 let ending = match image.user() {
404 None => String::new(),
405 Some(user) => format!(
406 "# Explicit gid so a runtime that does not read /etc/passwd cannot start the agent in \
407 group 0, which\n# makes the exec drop a privilege crossing whose setgroups needs a \
408 CAP_SETGID this image lacks, so\n# every exec fails.\nUSER {user}\n"
409 ),
410 };
411 format!(
412 "EXPOSE {port}\n{ending}ENTRYPOINT [\"{AGENT_PATH}\"]",
413 port = image.exposed_port()
414 )
415}
416
417#[cfg(test)]
419const GCP_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-agent";
420
421#[cfg(test)]
423const GCP_DEFAULT_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-gcp";
424
425#[cfg(test)]
427const DEFAULT_SANDBOX_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-default";
428
429#[cfg(test)]
431const DEFAULT_SANDBOX_TOOLS_FILE: &str = "docker/sandbox-default-tools.txt";
432
433#[cfg(test)]
436const SANDBOX_FILES_UPDATE: &str = "UPDATE_SANDBOX_AGENT_DOCKERFILE";
437
438#[cfg(test)]
440fn default_sandbox_dockerfile() -> String {
441 let packages: Vec<&str> = DEFAULT_SANDBOX_TOOLS
442 .iter()
443 .filter_map(|tool| tool.package)
444 .collect();
445 format!(
446 r#"# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
447# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
448#
449# Multi-arch tools-only base for the default sandbox images, with no agent. An image that runs the
450# agent adds it and its own ending on top, and a runtime with no in-guest agent runs this as is,
451# so it declares no USER, ENTRYPOINT or ENV.
452
453FROM {DEFAULT_SANDBOX_BASE_IMAGE}
454
455# No version pins: the -updates and -security pockets supersede a pinned version and the arm64
456# ports lag behind, so a pin breaks the build. The published digest is what fixes the versions.
457# ca-certificates is already in the base; naming it upgrades the trust store to the archive's
458# current one instead of the one frozen in the base digest.
459RUN apt-get update \
460 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
461 ca-certificates {packages} \
462 && rm -rf /var/lib/apt/lists/*
463
464COPY --from={DEFAULT_SANDBOX_UV_IMAGE} /uv /uvx /usr/local/bin/
465"#,
466 packages = packages.join(" "),
467 )
468}
469
470#[cfg(test)]
472fn default_sandbox_tools_list() -> String {
473 let mut list = format!(
474 "# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
475# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
476#
477# One command per tool the default sandbox base ships; each prints a version and exits zero.
478"
479 );
480 for tool in DEFAULT_SANDBOX_TOOLS {
481 list.push_str(tool.version_command);
482 list.push('\n');
483 }
484 list
485}
486
487#[cfg(test)]
489enum GcpBase {
490 Image(&'static str),
491 BuildArg(&'static str),
493}
494
495#[cfg(test)]
497fn gcp_agent_platform_dockerfile() -> String {
498 gcp_dockerfile(
499 "Multi-arch build for the alien-sandbox-agent Docker image",
500 GcpBase::Image("docker.io/chainguard/wolfi-base:latest"),
501 "# git is for the sandboxed command, not the agent, and pulls 24 transitive packages. That cost
502# lands here because this image is the sandbox, with no customer base image underneath to carry it.
503RUN apk add --no-cache git",
504 )
505}
506
507#[cfg(test)]
510fn gcp_default_sandbox_dockerfile() -> String {
511 assert_eq!(
512 GCP_AGENT_PLATFORM.exec_uid, 1000,
513 "the userdel below exists only because Ubuntu's own user holds the exec uid"
514 );
515 gcp_dockerfile(
516 "Multi-arch build for the default GCP sandbox image: the default sandbox base plus the agent",
517 GcpBase::BuildArg("SANDBOX_DEFAULT_BASE"),
518 "# Ubuntu ships `ubuntu` at uid 1000. Appending a second entry for that uid leaves `id` and every
519# tool resolving it to `ubuntu`, so the exec user would not be `sandbox`.
520RUN userdel --remove ubuntu",
521 )
522}
523
524#[cfg(test)]
531fn gcp_dockerfile(title: &str, base: GcpBase, base_setup: &str) -> String {
532 let image = &GCP_AGENT_PLATFORM;
533 let (directive, base_arg, base) = match base {
536 GcpBase::Image(reference) => (String::new(), String::new(), reference.to_string()),
537 GcpBase::BuildArg(name) => (
538 "# check=skip=InvalidDefaultArgInFrom\n".to_string(),
539 format!(
540 "# No default: the base's digest exists only once it is built, so whoever builds \
541 this image\n# passes it. The check directive on line 1 is for this.\nARG {name}\n\n"
542 ),
543 format!("${{{name}}}"),
544 ),
545 };
546 format!(
547 r#"{directive}# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
548# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
549#
550# {title}
551# Run directly as the GCP Agent Platform sandbox; nothing layers on top of it
552
553{base_arg}FROM docker.io/chainguard/wolfi-base:latest AS binary-selector
554
555COPY target/aarch64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-aarch64
556COPY target/x86_64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-x86_64
557
558ARG TARGETARCH
559RUN case "$TARGETARCH" in \
560 amd64) cp /tmp/alien-sandbox-agent-x86_64 /tmp/alien-sandbox-agent ;; \
561 arm64) cp /tmp/alien-sandbox-agent-aarch64 /tmp/alien-sandbox-agent ;; \
562 *) echo "unsupported TARGETARCH '$TARGETARCH'" >&2; exit 1 ;; \
563 esac
564
565FROM {base}
566
567{base_setup}
568
569# Root-owned and unwritable by uid {exec_uid}: the supervised command runs under that uid and must not
570# be able to rewrite its own supervisor.
571COPY --from=binary-selector --chown=0:0 --chmod={AGENT_MODE:04o} \
572 /tmp/alien-sandbox-agent {AGENT_PATH}
573
574# Numeric ids and a plain append rather than adduser, which differs across base distributions.
575# Linux runs a process under a uid with no passwd entry, but tooling inside the sandbox reads one.
576{identity}
577
578# The template carries no env, so the contract lives here, and none of it is optional. transport
579# serves an uncapabilitied request only from a socket `peer::transport_may_serve` cannot trace
580# back to the exec uid, and the agent refuses the mode where /proc/net/tcp is unreadable.
581{env}
582
583# The release build resolves tracing-subscriber once across every package it names, and five of
584# them ask for env-filter, so the agent's fmt::init() has an EnvFilter under it. Unset, that
585# filter discards the startup warning saying this image serves requests without a capability.
586ENV RUST_LOG={GCP_AGENT_LOG_FILTER} \
587 ALIEN_SANDBOX_IMAGE_COMMAND=true
588
589# These published agent images have no application startup command. Declare that explicitly so
590# inherited base CMD values cannot become agent arguments or a second shell process.
591RUN mkdir -p /opt/alien \
592 && printf '%s\n' '{empty_image_command}' > {IMAGE_COMMAND_PATH} \
593 && chmod 0444 {IMAGE_COMMAND_PATH}
594
595{entrypoint}
596CMD []
597"#,
598 empty_image_command = serde_json::to_string(&SandboxImageCommand {
599 user: Some(String::new()),
600 working_directory: "/".into(),
601 ..Default::default()
602 })
603 .expect("static default image command must serialize"),
604 exec_uid = image.exec_uid,
605 identity = identity_setup(image),
606 env = contract_env(image),
607 entrypoint = entrypoint(image),
608 )
609}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614
615 #[test]
617 fn the_gcp_agent_leaves_port_8080_to_the_workload() {
618 assert_ne!(GCP_AGENT_PLATFORM.port, 8080);
619 assert_eq!(GCP_AGENT_PLATFORM.port, AGENT_PORT);
620 }
621
622 #[test]
625 fn root_capability_set_is_dockers_default_without_net_raw() {
626 assert_eq!(IMAGE_ROOT_CAPABILITY_MASK, 0xa80405fb);
627 for forbidden in ["NET_ADMIN", "SYS_ADMIN", "NET_RAW"] {
628 assert!(IMAGE_ROOT_CAPABILITY_SET
629 .iter()
630 .all(|(name, _)| *name != forbidden));
631 }
632 }
633
634 fn committed_path(relative: &str) -> std::path::PathBuf {
635 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
636 .join("../..")
637 .join(relative)
638 }
639
640 fn first_difference(committed: &str, rendered: &str) -> String {
643 for (index, (left, right)) in committed.lines().zip(rendered.lines()).enumerate() {
644 if left != right {
645 let line = index + 1;
646 return format!("line {line}: committed {left:?}, contract renders {right:?}");
647 }
648 }
649 format!(
650 "committed has {} lines, the contract renders {}",
651 committed.lines().count(),
652 rendered.lines().count()
653 )
654 }
655
656 #[test]
659 fn the_committed_gcp_dockerfiles_are_what_the_contract_renders() {
660 for (file, rendered) in [
661 (GCP_DOCKERFILE, gcp_agent_platform_dockerfile()),
662 (GCP_DEFAULT_DOCKERFILE, gcp_default_sandbox_dockerfile()),
663 (DEFAULT_SANDBOX_DOCKERFILE, default_sandbox_dockerfile()),
664 (DEFAULT_SANDBOX_TOOLS_FILE, default_sandbox_tools_list()),
665 ] {
666 let path = committed_path(file);
667
668 if std::env::var_os(SANDBOX_FILES_UPDATE).is_some() {
669 std::fs::write(&path, &rendered)
670 .unwrap_or_else(|error| panic!("{} must be writable: {error}", path.display()));
671 continue;
672 }
673
674 let committed = std::fs::read_to_string(&path)
675 .unwrap_or_else(|error| panic!("{} must be readable: {error}", path.display()));
676 assert!(
677 committed == rendered,
678 "{file} has drifted from the contract it is rendered from.\n\
679 {}\n\
680 Regenerate it: {SANDBOX_FILES_UPDATE}=1 cargo test -p alien-core --lib sandbox_image",
681 first_difference(&committed, &rendered)
682 );
683 }
684 }
685
686 #[test]
689 fn the_gcp_env_accessor_is_every_env_the_committed_dockerfile_sets() {
690 let committed = std::fs::read_to_string(committed_path(GCP_DEFAULT_DOCKERFILE)).unwrap();
691 let mut set = Vec::new();
692 let mut in_env = false;
693 for line in committed.lines() {
694 let line = line.trim();
695 let rest = match line.strip_prefix("ENV ") {
696 Some(rest) => rest,
697 None if in_env => line,
698 None => continue,
699 };
700 in_env = rest.ends_with('\\');
701 for pair in rest.trim_end_matches('\\').split_whitespace() {
702 let (name, value) = pair.split_once('=').expect("ENV name=value");
703 set.push((name.to_string(), value.to_string()));
704 }
705 }
706 let accessor: Vec<(String, String)> = gcp_agent_platform_env()
707 .into_iter()
708 .map(|(name, value)| (name.to_string(), value))
709 .collect();
710 assert_eq!(accessor, set);
711 }
712
713 #[test]
717 fn the_two_images_carry_the_identities_their_stacks_were_built_against() {
718 assert_eq!(AWS_MICROVM.port, 8971);
719 assert_eq!(AWS_MICROVM.exec_uid, 60000);
720 assert_eq!(AWS_MICROVM.session_root, "/sandbox");
721 assert_eq!(GCP_AGENT_PLATFORM.port, 8971);
722 assert_eq!(GCP_AGENT_PLATFORM.exec_uid, 1000);
723 assert_eq!(GCP_AGENT_PLATFORM.session_root, "/sandbox");
724 for image in [&AWS_MICROVM, &GCP_AGENT_PLATFORM] {
725 assert_ne!(image.exec_uid, 0, "the exec uid must never be root");
726 }
727 }
728
729 #[test]
733 fn the_ending_an_image_declares_follows_its_isolation() {
734 assert!(!entrypoint(&AWS_MICROVM).contains("USER "));
735 assert!(contract_env(&AWS_MICROVM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
736 assert_eq!(GCP_AGENT_PLATFORM.isolation, Isolation::UidSplit);
737 assert!(contract_env(&GCP_AGENT_PLATFORM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
738 }
739}
740
741#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
743#[serde(rename_all = "camelCase", deny_unknown_fields)]
744pub struct SandboxImageCommand {
745 #[serde(default, skip_serializing_if = "Option::is_none")]
748 pub user: Option<String>,
749 pub command: Vec<String>,
751 pub env: std::collections::BTreeMap<String, String>,
753 pub working_directory: String,
755}
756
757pub const IMAGE_COMMAND_PATH: &str = "/opt/alien/image-command.json";
759
760pub const NATIVE_TOKEN_PATH: &str = "/opt/alien/native-token";