Skip to main content

alien_core/
sandbox_image.rs

1//! What a sandbox image must carry for the agent to serve, and the Dockerfile text carrying it.
2//!
3//! Two kinds of image exist and neither is built the way the other is. AWS renders one per
4//! deployment onto a customer-supplied base image; GCP builds static images in CI. Nothing at build
5//! time reads the other side, and a value that disagrees is invisible until a session fails: an
6//! agent listening on a port no caller dials, or an exec into a uid the image never created.
7//!
8//! So the values live here once and both kinds render the block that carries them from this
9//! module. The same holds for the default sandbox base both kinds start from: its toolchain is
10//! listed here once, and a probe reads that list rather than restating it. The Dockerfiles and the
11//! tool list are committed as generated text because CI builds them with `docker build` and probes
12//! them from a shell, neither of which can call a Rust function.
13
14/// Path the agent binary is installed at inside every sandbox image.
15///
16/// An image that installs one path and entrypoints another exits before it serves, and the
17/// session times out on connect.
18pub const AGENT_PATH: &str = "/usr/local/bin/alien-sandbox-agent";
19
20/// Port the agent serves unless the platform pins another.
21///
22/// Defined once because two independent copies are a runtime-only failure: the image build places
23/// the agent on one port and the client dials the other, and nothing catches it until a sandbox
24/// hangs. AWS scopes its endpoint token to an explicit port set, so this cannot be discovered.
25pub const AGENT_PORT: u16 = 8971;
26
27/// Mode of the agent binary, owned by `0:0` so the exec uid cannot rewrite its supervisor.
28pub const AGENT_MODE: u32 = 0o755;
29
30/// Name of the exec identity's passwd and group entries.
31pub const EXEC_USER: &str = "sandbox";
32
33/// Mode of the session root, which the exec uid owns.
34pub const SESSION_ROOT_MODE: u32 = 0o700;
35
36/// `RUST_LOG` for a GCP image, which the agent needs set before it logs anything.
37pub const GCP_AGENT_LOG_FILTER: &str = "info";
38
39/// How an image ends, and the isolation that ending permits.
40///
41/// One value rather than two, because `ALIEN_SANDBOX_ISOLATION` and the trailing `USER` describe
42/// the same decision from opposite sides: an image that asks for `uid-split` under a non-root
43/// `USER` has no privilege left to drop with, and every exec in it fails.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Isolation {
46    /// The agent starts as root and drops to the exec uid before every spawn, so a command can
47    /// never rewrite its own supervisor. The image declares no `USER`.
48    UidSplit,
49    /// The agent starts as the exec uid and supervises commands under it, which is all a runtime
50    /// that refuses a root image can offer. The image ends `USER <uid>:<uid>`.
51    Platform,
52}
53
54impl Isolation {
55    /// The `ALIEN_SANDBOX_ISOLATION` value the agent parses.
56    pub fn env_value(self) -> &'static str {
57        match self {
58            Self::UidSplit => "uid-split",
59            Self::Platform => "platform",
60        }
61    }
62}
63
64/// How the agent decides a caller may be served.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Authorization {
67    /// The connection is the proof. The agent serves an uncapabilitied request only from a socket
68    /// peer it cannot trace back to the exec uid, which keeps the supervised command out.
69    Transport,
70    /// The caller presents a signed token, which is what a network anything can reach requires.
71    Capability,
72    /// A per-boot credential is read through the cloud's authenticated native file API.
73    NativeFile,
74}
75
76impl Authorization {
77    /// The `ALIEN_SANDBOX_AUTHORIZATION` value the agent parses.
78    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/// The values an image must carry for the agent to run in it.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct SandboxImage {
90    /// Uid the supervised command runs as, resolved from a non-root base USER or the default.
91    pub exec_uid: u32,
92    /// Primary gid from the base USER, which may differ from its uid.
93    pub exec_gid: u32,
94    /// Writable session directory. Image-owned directories may also be writable on VM backends.
95    pub session_root: &'static str,
96    /// Port the agent serves, both its own protocol and any lifecycle hooks.
97    pub port: u16,
98    pub authorization: Authorization,
99    pub isolation: Isolation,
100}
101
102impl SandboxImage {
103    /// Gid the supervised command runs as.
104    pub fn exec_gid(&self) -> u32 {
105        self.exec_gid
106    }
107
108    /// The agent's configuration contract as `(name, value)` pairs, in the order the `ENV` block
109    /// lists them.
110    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    /// The `uid:gid` the image runs as, or `None` when it declares no user and starts as root.
128    /// Why the gid is explicit is in the `USER` comment [`entrypoint`] renders.
129    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    /// The port the image exposes, as an OCI `ExposedPorts` key.
137    pub fn exposed_port(&self) -> String {
138        format!("{}/tcp", self.port)
139    }
140
141    /// The exec identity's `/etc/passwd` line, without a trailing newline.
142    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    /// The exec identity's `/etc/group` line, without a trailing newline.
152    pub fn group_entry(&self) -> String {
153        format!("{EXEC_USER}:x:{gid}:", gid = self.exec_gid())
154    }
155}
156
157/// The Lambda MicroVM image, rendered per deployment onto a customer base image.
158///
159/// The agent runs as root so it can drop to [`SandboxImage::exec_uid`] before every spawn; inside
160/// a MicroVM that is contained by hardware virtualisation, which is the tenant boundary. A
161/// shared-kernel backend must give the agent `CAP_SETUID` instead of root.
162pub 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
171/// GCP keeps a root supervisor separate from the non-root command identity.
172/// Live conformance must verify root execution and capability bounds because the
173/// provider's published custom-image requirements do not promise root support.
174/// Agent Platform serves the declared container port 8080.
175pub 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
184/// Every variable a GCP Agent Platform image sets: the contract, then `RUST_LOG`.
185pub 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
192/// Azure serves the agent through a published port and an authenticated native file read.
193/// Its native exec path is never used for packaged images because it grants excess capabilities.
194pub 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
203/// A Kubernetes sandbox pod. The cluster's sandboxed runtime is the tenant boundary and refuses to
204/// start a root container here (`runAsNonRoot`), so the agent starts as the exec uid and
205/// supervises under it. Anything on the cluster network can reach the pod, so a caller presents a
206/// signed capability. The exec uid is a default: a non-root base `USER` replaces it.
207pub 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
216/// The image every default sandbox builds on, by index digest so both architectures are pinned.
217///
218/// Bumped by hand, then regenerated: Renovate skips the generated Dockerfiles and does not read
219/// this file.
220pub const DEFAULT_SANDBOX_BASE_IMAGE: &str = "public.ecr.aws/docker/library/buildpack-deps:26.04@sha256:159ea382e6fb39e62480ee932113f885f7bd787cd4895fc4dc71aebb175077fd";
221
222/// The image uv and uvx are copied out of, by index digest.
223pub const DEFAULT_SANDBOX_UV_IMAGE: &str = "ghcr.io/astral-sh/uv:0.12.21@sha256:a7aed3216253ee804de3e2d8afa5073baa1a177335345d43845cd4165e43b711";
224
225/// A tool the default sandbox base ships, and the command that shows it runs.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct SandboxTool {
228    /// The Ubuntu archive package it comes from, or `None` for one copied out of
229    /// [`DEFAULT_SANDBOX_UV_IMAGE`].
230    pub package: Option<&'static str>,
231    /// Prints the tool's version and exits zero.
232    pub version_command: &'static str,
233}
234
235/// The toolchain of the default sandbox base, and the one list its probes read.
236///
237/// Every tool lands in `/usr/bin` or `/usr/local/bin`: a supervised command gets a fixed `PATH`
238/// and never the image's `ENV`, so a tool anywhere else is invisible to it.
239pub 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
294/// The `RUN` step creating the exec identity and the session root it owns.
295pub 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
313/// The `ENV` block carrying the agent's configuration contract.
314pub 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
323/// `EXPOSE`, the image's ending, and the `ENTRYPOINT`.
324pub 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/// Path of the committed minimal wolfi GCP Dockerfile, relative to the repository root.
340#[cfg(test)]
341const GCP_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-agent";
342
343/// Path of the committed default GCP sandbox Dockerfile, relative to the repository root.
344#[cfg(test)]
345const GCP_DEFAULT_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-gcp";
346
347/// Path of the committed default sandbox base Dockerfile, relative to the repository root.
348#[cfg(test)]
349const DEFAULT_SANDBOX_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-default";
350
351/// Path of the committed tool list a probe of the default sandbox base reads.
352#[cfg(test)]
353const DEFAULT_SANDBOX_TOOLS_FILE: &str = "docker/sandbox-default-tools.txt";
354
355/// Set to regenerate every committed file this module renders instead of comparing against them.
356/// Named for the agent Dockerfile; every generated header prints the name, so a rename rewrites all.
357#[cfg(test)]
358const SANDBOX_FILES_UPDATE: &str = "UPDATE_SANDBOX_AGENT_DOCKERFILE";
359
360/// Renders [`DEFAULT_SANDBOX_DOCKERFILE`], the tools-only base every default sandbox builds on.
361#[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/// Renders [`DEFAULT_SANDBOX_TOOLS_FILE`], one version command per line.
393#[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/// Where a GCP image's final stage starts.
410#[cfg(test)]
411enum GcpBase {
412    Image(&'static str),
413    /// A build-arg with no default, which whoever builds the image must pass.
414    BuildArg(&'static str),
415}
416
417/// Renders [`GCP_DOCKERFILE`], the minimal wolfi image.
418#[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/// Renders [`GCP_DEFAULT_DOCKERFILE`], the default GCP sandbox image: the agent on the default
430/// sandbox base ([`DEFAULT_SANDBOX_DOCKERFILE`]), which whoever builds it passes by digest.
431#[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/// Renders a GCP Dockerfile onto `base`, with `base_setup` run as root before the agent lands.
447///
448/// Everything outside the shared block is here because it is true of the GCP images alone: the
449/// `binary-selector` stage, which exists because the release workflow builds one manifest for two
450/// architectures from binaries cross-compiled outside Docker; and `RUST_LOG`, which the agent's own
451/// `EnvFilter` needs before it will emit anything.
452#[cfg(test)]
453fn gcp_dockerfile(title: &str, base: GcpBase, base_setup: &str) -> String {
454    let image = &GCP_AGENT_PLATFORM;
455    // An ARG read by a FROM must precede the first FROM, or it is scoped to a stage and empty.
456    // BuildKit reads a parser directive only on the first lines, before any other comment.
457    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    /// Where two texts first part, in terms a reader can act on. `assert_eq!` on a whole
544    /// Dockerfile prints two escaped blobs and says nothing about which line moved.
545    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    /// The whole file, not chosen properties. A mutation this comparison cannot see is one that
560    /// leaves the bytes alone, and there is no such mutation.
561    #[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    /// An image built without a Dockerfile carries what the CI images carry, so the env the
590    /// accessor hands out is read back from the committed file rather than restated.
591    #[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    /// Every consumer derives these, so nothing else compares them against a number. The
617    /// setup emitters tell the agent which uid to drop to; if that stops matching the uid the
618    /// image creates, the sandbox starts and every exec fails.
619    #[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    /// The ending an image declares and the isolation it claims come off one value, so they
633    /// cannot disagree. The AWS half is rendered at run time and reaches no committed file, which
634    /// is why the whole-file comparison above covers only the GCP side of it.
635    #[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/// Root-owned metadata copied from the base image at bundle creation, never from an exec caller.
645#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
646#[serde(rename_all = "camelCase", deny_unknown_fields)]
647pub struct SandboxImageCommand {
648    /// Original OCI USER, including an empty string for Docker's root default.
649    /// Absent only in released metadata whose boot command used the exec identity.
650    #[serde(default, skip_serializing_if = "Option::is_none")]
651    pub user: Option<String>,
652    /// OCI Entrypoint followed by Cmd; empty means there is no image command.
653    pub command: Vec<String>,
654    /// Image environment only, before runtime authorization and provider variables are added.
655    pub env: std::collections::BTreeMap<String, String>,
656    /// OCI WorkingDir, or / if the image does not declare one.
657    pub working_directory: String,
658}
659
660/// Installed outside the command-writable session directory.
661pub const IMAGE_COMMAND_PATH: &str = "/opt/alien/image-command.json";
662
663/// Per-boot agent credential read only through an authenticated native file API.
664pub const NATIVE_TOKEN_PATH: &str = "/opt/alien/native-token";