1pub const AGENT_PATH: &str = "/usr/local/bin/alien-sandbox-agent";
19
20pub const AGENT_PORT: u16 = 8971;
26
27pub const AGENT_MODE: u32 = 0o755;
29
30pub const EXEC_USER: &str = "sandbox";
32
33pub const SESSION_ROOT_MODE: u32 = 0o700;
35
36pub const GCP_AGENT_LOG_FILTER: &str = "info";
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Isolation {
46 UidSplit,
49 Platform,
52}
53
54impl Isolation {
55 pub fn env_value(self) -> &'static str {
57 match self {
58 Self::UidSplit => "uid-split",
59 Self::Platform => "platform",
60 }
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Authorization {
67 Transport,
70 Capability,
72 NativeFile,
74}
75
76impl Authorization {
77 pub fn env_value(self) -> &'static str {
79 match self {
80 Self::Transport => "transport",
81 Self::Capability => "capability",
82 Self::NativeFile => "native-file",
83 }
84 }
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct SandboxImage {
90 pub exec_uid: u32,
92 pub exec_gid: u32,
94 pub session_root: &'static str,
96 pub port: u16,
98 pub authorization: Authorization,
99 pub isolation: Isolation,
100}
101
102impl SandboxImage {
103 pub fn exec_gid(&self) -> u32 {
105 self.exec_gid
106 }
107
108 pub fn contract_env_vars(&self) -> [(&'static str, String); 6] {
111 [
112 ("ALIEN_SANDBOX_ROOT", self.session_root.to_string()),
113 ("ALIEN_SANDBOX_PORT", self.port.to_string()),
114 (
115 "ALIEN_SANDBOX_AUTHORIZATION",
116 self.authorization.env_value().to_string(),
117 ),
118 ("ALIEN_SANDBOX_EXEC_UID", self.exec_uid.to_string()),
119 ("ALIEN_SANDBOX_EXEC_GID", self.exec_gid().to_string()),
120 (
121 "ALIEN_SANDBOX_ISOLATION",
122 self.isolation.env_value().to_string(),
123 ),
124 ]
125 }
126
127 pub fn user(&self) -> Option<String> {
130 match self.isolation {
131 Isolation::UidSplit => None,
132 Isolation::Platform => Some(format!("{}:{}", self.exec_uid, self.exec_gid())),
133 }
134 }
135
136 pub fn exposed_port(&self) -> String {
138 format!("{}/tcp", self.port)
139 }
140
141 pub fn passwd_entry(&self) -> String {
143 format!(
144 "{EXEC_USER}:x:{uid}:{gid}::{root}:/sbin/nologin",
145 uid = self.exec_uid,
146 gid = self.exec_gid(),
147 root = self.session_root,
148 )
149 }
150
151 pub fn group_entry(&self) -> String {
153 format!("{EXEC_USER}:x:{gid}:", gid = self.exec_gid())
154 }
155}
156
157pub const AWS_MICROVM: SandboxImage = SandboxImage {
163 exec_uid: 60000,
164 exec_gid: 60000,
165 session_root: "/sandbox",
166 port: AGENT_PORT,
167 authorization: Authorization::Transport,
168 isolation: Isolation::UidSplit,
169};
170
171pub const GCP_AGENT_PLATFORM: SandboxImage = SandboxImage {
176 exec_uid: 1000,
177 exec_gid: 1000,
178 session_root: "/sandbox",
179 port: 8080,
180 authorization: Authorization::Transport,
181 isolation: Isolation::UidSplit,
182};
183
184pub fn gcp_agent_platform_env() -> Vec<(&'static str, String)> {
186 let mut env = GCP_AGENT_PLATFORM.contract_env_vars().to_vec();
187 env.push(("RUST_LOG", GCP_AGENT_LOG_FILTER.to_string()));
188 env.push(("ALIEN_SANDBOX_IMAGE_COMMAND", "true".into()));
189 env
190}
191
192pub const AZURE_SANDBOX: SandboxImage = SandboxImage {
195 exec_uid: 1000,
196 exec_gid: 1000,
197 session_root: "/sandbox",
198 port: AGENT_PORT,
199 authorization: Authorization::NativeFile,
200 isolation: Isolation::UidSplit,
201};
202
203pub const KUBERNETES_SANDBOX: SandboxImage = SandboxImage {
208 exec_uid: 1000,
209 exec_gid: 1000,
210 session_root: "/sandbox",
211 port: AGENT_PORT,
212 authorization: Authorization::Capability,
213 isolation: Isolation::Platform,
214};
215
216pub const DEFAULT_SANDBOX_BASE_IMAGE: &str = "public.ecr.aws/docker/library/buildpack-deps:26.04@sha256:159ea382e6fb39e62480ee932113f885f7bd787cd4895fc4dc71aebb175077fd";
221
222pub const DEFAULT_SANDBOX_UV_IMAGE: &str = "ghcr.io/astral-sh/uv:0.12.21@sha256:a7aed3216253ee804de3e2d8afa5073baa1a177335345d43845cd4165e43b711";
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct SandboxTool {
228 pub package: Option<&'static str>,
231 pub version_command: &'static str,
233}
234
235pub const DEFAULT_SANDBOX_TOOLS: &[SandboxTool] = &[
240 SandboxTool {
241 package: Some("nftables"),
242 version_command: "/usr/sbin/nft --version",
243 },
244 SandboxTool {
245 package: Some("iptables"),
246 version_command: "iptables-nft --version",
247 },
248 SandboxTool {
249 package: Some("nodejs"),
250 version_command: "node --version",
251 },
252 SandboxTool {
253 package: Some("npm"),
254 version_command: "npm --version",
255 },
256 SandboxTool {
257 package: Some("ripgrep"),
258 version_command: "rg --version",
259 },
260 SandboxTool {
261 package: Some("jq"),
262 version_command: "jq --version",
263 },
264 SandboxTool {
265 package: Some("zip"),
266 version_command: "zip -v",
267 },
268 SandboxTool {
269 package: Some("less"),
270 version_command: "less --version",
271 },
272 SandboxTool {
273 package: Some("nano"),
274 version_command: "nano --version",
275 },
276 SandboxTool {
277 package: Some("vim-tiny"),
278 version_command: "vim.tiny --version",
279 },
280 SandboxTool {
281 package: Some("htop"),
282 version_command: "htop --version",
283 },
284 SandboxTool {
285 package: None,
286 version_command: "uv --version",
287 },
288 SandboxTool {
289 package: None,
290 version_command: "uvx --version",
291 },
292];
293
294pub fn identity_setup(image: &SandboxImage) -> String {
296 format!(
297 r#"RUN test ! -L /etc/passwd && test ! -L /etc/group && test ! -L {root} \
298 && touch /etc/passwd /etc/group \
299 && chown 0:0 /etc/passwd /etc/group && chmod 0644 /etc/passwd /etc/group \
300 && (awk -F: '$3 == {uid} {{ found=1 }} END {{ exit !found }}' /etc/passwd || printf '{passwd}\n' >> /etc/passwd) \
301 && (awk -F: '$3 == {gid} {{ found=1 }} END {{ exit !found }}' /etc/group || printf '{group}\n' >> /etc/group) \
302 && mkdir -p {root} \
303 && chown {uid}:{gid} {root} \
304 && chmod {SESSION_ROOT_MODE:04o} {root}"#,
305 passwd = image.passwd_entry(),
306 group = image.group_entry(),
307 root = image.session_root,
308 uid = image.exec_uid,
309 gid = image.exec_gid(),
310 )
311}
312
313pub fn contract_env(image: &SandboxImage) -> String {
315 let vars: Vec<String> = image
316 .contract_env_vars()
317 .iter()
318 .map(|(name, value)| format!("{name}={value}"))
319 .collect();
320 format!("ENV {}", vars.join(" \\\n "))
321}
322
323pub fn entrypoint(image: &SandboxImage) -> String {
325 let ending = match image.user() {
326 None => String::new(),
327 Some(user) => format!(
328 "# Explicit gid so a runtime that does not read /etc/passwd cannot start the agent in \
329 group 0, which\n# makes the exec drop a privilege crossing whose setgroups needs a \
330 CAP_SETGID this image lacks, so\n# every exec fails.\nUSER {user}\n"
331 ),
332 };
333 format!(
334 "EXPOSE {port}\n{ending}ENTRYPOINT [\"{AGENT_PATH}\"]",
335 port = image.exposed_port()
336 )
337}
338
339#[cfg(test)]
341const GCP_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-agent";
342
343#[cfg(test)]
345const GCP_DEFAULT_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-gcp";
346
347#[cfg(test)]
349const DEFAULT_SANDBOX_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-default";
350
351#[cfg(test)]
353const DEFAULT_SANDBOX_TOOLS_FILE: &str = "docker/sandbox-default-tools.txt";
354
355#[cfg(test)]
358const SANDBOX_FILES_UPDATE: &str = "UPDATE_SANDBOX_AGENT_DOCKERFILE";
359
360#[cfg(test)]
362fn default_sandbox_dockerfile() -> String {
363 let packages: Vec<&str> = DEFAULT_SANDBOX_TOOLS
364 .iter()
365 .filter_map(|tool| tool.package)
366 .collect();
367 format!(
368 r#"# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
369# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
370#
371# Multi-arch tools-only base for the default sandbox images, with no agent. An image that runs the
372# agent adds it and its own ending on top, and a runtime with no in-guest agent runs this as is,
373# so it declares no USER, ENTRYPOINT or ENV.
374
375FROM {DEFAULT_SANDBOX_BASE_IMAGE}
376
377# No version pins: the -updates and -security pockets supersede a pinned version and the arm64
378# ports lag behind, so a pin breaks the build. The published digest is what fixes the versions.
379# ca-certificates is already in the base; naming it upgrades the trust store to the archive's
380# current one instead of the one frozen in the base digest.
381RUN apt-get update \
382 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
383 ca-certificates {packages} \
384 && rm -rf /var/lib/apt/lists/*
385
386COPY --from={DEFAULT_SANDBOX_UV_IMAGE} /uv /uvx /usr/local/bin/
387"#,
388 packages = packages.join(" "),
389 )
390}
391
392#[cfg(test)]
394fn default_sandbox_tools_list() -> String {
395 let mut list = format!(
396 "# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
397# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
398#
399# One command per tool the default sandbox base ships; each prints a version and exits zero.
400"
401 );
402 for tool in DEFAULT_SANDBOX_TOOLS {
403 list.push_str(tool.version_command);
404 list.push('\n');
405 }
406 list
407}
408
409#[cfg(test)]
411enum GcpBase {
412 Image(&'static str),
413 BuildArg(&'static str),
415}
416
417#[cfg(test)]
419fn gcp_agent_platform_dockerfile() -> String {
420 gcp_dockerfile(
421 "Multi-arch build for the alien-sandbox-agent Docker image",
422 GcpBase::Image("docker.io/chainguard/wolfi-base:latest"),
423 "# git is for the sandboxed command, not the agent, and pulls 24 transitive packages. That cost
424# lands here because this image is the sandbox, with no customer base image underneath to carry it.
425RUN apk add --no-cache git",
426 )
427}
428
429#[cfg(test)]
432fn gcp_default_sandbox_dockerfile() -> String {
433 assert_eq!(
434 GCP_AGENT_PLATFORM.exec_uid, 1000,
435 "the userdel below exists only because Ubuntu's own user holds the exec uid"
436 );
437 gcp_dockerfile(
438 "Multi-arch build for the default GCP sandbox image: the default sandbox base plus the agent",
439 GcpBase::BuildArg("SANDBOX_DEFAULT_BASE"),
440 "# Ubuntu ships `ubuntu` at uid 1000. Appending a second entry for that uid leaves `id` and every
441# tool resolving it to `ubuntu`, so the exec user would not be `sandbox`.
442RUN userdel --remove ubuntu",
443 )
444}
445
446#[cfg(test)]
453fn gcp_dockerfile(title: &str, base: GcpBase, base_setup: &str) -> String {
454 let image = &GCP_AGENT_PLATFORM;
455 let (directive, base_arg, base) = match base {
458 GcpBase::Image(reference) => (String::new(), String::new(), reference.to_string()),
459 GcpBase::BuildArg(name) => (
460 "# check=skip=InvalidDefaultArgInFrom\n".to_string(),
461 format!(
462 "# No default: the base's digest exists only once it is built, so whoever builds \
463 this image\n# passes it. The check directive on line 1 is for this.\nARG {name}\n\n"
464 ),
465 format!("${{{name}}}"),
466 ),
467 };
468 format!(
469 r#"{directive}# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
470# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
471#
472# {title}
473# Run directly as the GCP Agent Platform sandbox; nothing layers on top of it
474
475{base_arg}FROM docker.io/chainguard/wolfi-base:latest AS binary-selector
476
477COPY target/aarch64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-aarch64
478COPY target/x86_64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-x86_64
479
480ARG TARGETARCH
481RUN case "$TARGETARCH" in \
482 amd64) cp /tmp/alien-sandbox-agent-x86_64 /tmp/alien-sandbox-agent ;; \
483 arm64) cp /tmp/alien-sandbox-agent-aarch64 /tmp/alien-sandbox-agent ;; \
484 *) echo "unsupported TARGETARCH '$TARGETARCH'" >&2; exit 1 ;; \
485 esac
486
487FROM {base}
488
489{base_setup}
490
491# Root-owned and unwritable by uid {exec_uid}: the supervised command runs under that uid and must not
492# be able to rewrite its own supervisor.
493COPY --from=binary-selector --chown=0:0 --chmod={AGENT_MODE:04o} \
494 /tmp/alien-sandbox-agent {AGENT_PATH}
495
496# Numeric ids and a plain append rather than adduser, which differs across base distributions.
497# Linux runs a process under a uid with no passwd entry, but tooling inside the sandbox reads one.
498{identity}
499
500# The template carries no env, so the contract lives here, and none of it is optional. transport
501# serves an uncapabilitied request only from a socket `peer::transport_may_serve` cannot trace
502# back to the exec uid, and the agent refuses the mode where /proc/net/tcp is unreadable.
503{env}
504
505# The release build resolves tracing-subscriber once across every package it names, and five of
506# them ask for env-filter, so the agent's fmt::init() has an EnvFilter under it. Unset, that
507# filter discards the startup warning saying this image serves requests without a capability.
508ENV RUST_LOG={GCP_AGENT_LOG_FILTER} \
509 ALIEN_SANDBOX_IMAGE_COMMAND=true
510
511# These published agent images have no application startup command. Declare that explicitly so
512# inherited base CMD values cannot become agent arguments or a second shell process.
513RUN mkdir -p /opt/alien \
514 && printf '%s\n' '{empty_image_command}' > {IMAGE_COMMAND_PATH} \
515 && chmod 0600 {IMAGE_COMMAND_PATH}
516
517{entrypoint}
518CMD []
519"#,
520 empty_image_command = serde_json::to_string(&SandboxImageCommand {
521 user: Some(String::new()),
522 working_directory: "/".into(),
523 ..Default::default()
524 })
525 .expect("static default image command must serialize"),
526 exec_uid = image.exec_uid,
527 identity = identity_setup(image),
528 env = contract_env(image),
529 entrypoint = entrypoint(image),
530 )
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536
537 fn committed_path(relative: &str) -> std::path::PathBuf {
538 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
539 .join("../..")
540 .join(relative)
541 }
542
543 fn first_difference(committed: &str, rendered: &str) -> String {
546 for (index, (left, right)) in committed.lines().zip(rendered.lines()).enumerate() {
547 if left != right {
548 let line = index + 1;
549 return format!("line {line}: committed {left:?}, contract renders {right:?}");
550 }
551 }
552 format!(
553 "committed has {} lines, the contract renders {}",
554 committed.lines().count(),
555 rendered.lines().count()
556 )
557 }
558
559 #[test]
562 fn the_committed_gcp_dockerfiles_are_what_the_contract_renders() {
563 for (file, rendered) in [
564 (GCP_DOCKERFILE, gcp_agent_platform_dockerfile()),
565 (GCP_DEFAULT_DOCKERFILE, gcp_default_sandbox_dockerfile()),
566 (DEFAULT_SANDBOX_DOCKERFILE, default_sandbox_dockerfile()),
567 (DEFAULT_SANDBOX_TOOLS_FILE, default_sandbox_tools_list()),
568 ] {
569 let path = committed_path(file);
570
571 if std::env::var_os(SANDBOX_FILES_UPDATE).is_some() {
572 std::fs::write(&path, &rendered)
573 .unwrap_or_else(|error| panic!("{} must be writable: {error}", path.display()));
574 continue;
575 }
576
577 let committed = std::fs::read_to_string(&path)
578 .unwrap_or_else(|error| panic!("{} must be readable: {error}", path.display()));
579 assert!(
580 committed == rendered,
581 "{file} has drifted from the contract it is rendered from.\n\
582 {}\n\
583 Regenerate it: {SANDBOX_FILES_UPDATE}=1 cargo test -p alien-core --lib sandbox_image",
584 first_difference(&committed, &rendered)
585 );
586 }
587 }
588
589 #[test]
592 fn the_gcp_env_accessor_is_every_env_the_committed_dockerfile_sets() {
593 let committed = std::fs::read_to_string(committed_path(GCP_DEFAULT_DOCKERFILE)).unwrap();
594 let mut set = Vec::new();
595 let mut in_env = false;
596 for line in committed.lines() {
597 let line = line.trim();
598 let rest = match line.strip_prefix("ENV ") {
599 Some(rest) => rest,
600 None if in_env => line,
601 None => continue,
602 };
603 in_env = rest.ends_with('\\');
604 for pair in rest.trim_end_matches('\\').split_whitespace() {
605 let (name, value) = pair.split_once('=').expect("ENV name=value");
606 set.push((name.to_string(), value.to_string()));
607 }
608 }
609 let accessor: Vec<(String, String)> = gcp_agent_platform_env()
610 .into_iter()
611 .map(|(name, value)| (name.to_string(), value))
612 .collect();
613 assert_eq!(accessor, set);
614 }
615
616 #[test]
620 fn the_two_images_carry_the_identities_their_stacks_were_built_against() {
621 assert_eq!(AWS_MICROVM.port, 8971);
622 assert_eq!(AWS_MICROVM.exec_uid, 60000);
623 assert_eq!(AWS_MICROVM.session_root, "/sandbox");
624 assert_eq!(GCP_AGENT_PLATFORM.port, 8080);
625 assert_eq!(GCP_AGENT_PLATFORM.exec_uid, 1000);
626 assert_eq!(GCP_AGENT_PLATFORM.session_root, "/sandbox");
627 for image in [&AWS_MICROVM, &GCP_AGENT_PLATFORM] {
628 assert_ne!(image.exec_uid, 0, "the exec uid must never be root");
629 }
630 }
631
632 #[test]
636 fn the_ending_an_image_declares_follows_its_isolation() {
637 assert!(!entrypoint(&AWS_MICROVM).contains("USER "));
638 assert!(contract_env(&AWS_MICROVM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
639 assert_eq!(GCP_AGENT_PLATFORM.isolation, Isolation::UidSplit);
640 assert!(contract_env(&GCP_AGENT_PLATFORM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
641 }
642}
643
644#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
646#[serde(rename_all = "camelCase", deny_unknown_fields)]
647pub struct SandboxImageCommand {
648 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub user: Option<String>,
652 pub command: Vec<String>,
654 pub env: std::collections::BTreeMap<String, String>,
656 pub working_directory: String,
658}
659
660pub const IMAGE_COMMAND_PATH: &str = "/opt/alien/image-command.json";
662
663pub const NATIVE_TOKEN_PATH: &str = "/opt/alien/native-token";