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/// Header carrying a preview capability. Never `Authorization`: the caller's own bearer token
28/// belongs to the code inside the sandbox and reaches it untouched.
29pub const PREVIEW_CAPABILITY_HEADER: &str = "x-alien-preview-capability";
30
31/// Header naming the sandbox port a preview request is for.
32pub const PREVIEW_PORT_HEADER: &str = "x-alien-preview-port";
33
34/// Header a caller puts its own bearer in when the backend's edge consumes `Authorization` for
35/// its own credential (GCP). The agent, after the capability verifies, re-emits it as
36/// `Authorization` towards `127.0.0.1` only.
37pub const CALLER_AUTHORIZATION_HEADER: &str = "x-alien-caller-authorization";
38
39/// Environment variable naming the header a backend's callers use for their own bearer
40/// (`authorization` when unset). Set on backends whose edge replaces `Authorization`.
41pub const ENV_CALLER_AUTHORIZATION_HEADER: &str = "ALIEN_SANDBOX_CALLER_AUTHORIZATION_HEADER";
42
43/// Longest a preview capability lives, in seconds. A grant never outlives the session either.
44pub const PREVIEW_CAPABILITY_MAX_SECONDS: i64 = 15 * 60;
45
46/// Set by the Kubernetes backend only: the pod mounts the agent binary and `/opt/alien`
47/// read-only itself, so the agent verifies that instead of building a private mount namespace
48/// (a pod's default seccomp profile blocks `unshare`). The agent refuses to start if the mounts
49/// are not there, so setting it elsewhere cannot turn protection off.
50pub const ENV_PROTECTED_MOUNTS: &str = "ALIEN_SANDBOX_PROTECTED_MOUNTS";
51
52/// Comma-separated `host:port` addresses of the Kubernetes API server (its Service ClusterIP and
53/// the real endpoint IPs) that the startup gate must see dropped. The Operator sets it on every
54/// Kubernetes sandbox pod, because service links are off and the pod has no
55/// `KUBERNETES_SERVICE_HOST` to learn the address from.
56pub const ENV_MUST_DROP_KUBE_API: &str = "ALIEN_SANDBOX_MUST_DROP_KUBE_API";
57/// A public `host:port` the startup gate must also see dropped. The Operator sets it only where
58/// the declared egress forbids direct public traffic (`none`, and `internet`, which goes through
59/// the gateway). It is unset when the policy allows that address, so an `allow` pod is not
60/// refused for reaching it.
61pub const ENV_MUST_DROP_PUBLIC: &str = "ALIEN_SANDBOX_MUST_DROP_PUBLIC";
62/// The public address the Operator asks the gate to probe.
63pub const MUST_DROP_PUBLIC_PROBE: &str = "1.1.1.1:443";
64/// The agent's first argument that stages the protected files (the Kubernetes init container).
65pub const STAGE_PROTECTED_FILES_ARGUMENT: &str = "--stage-protected-files";
66/// Names inside the staging directory the pod mounts over the agent binary and `/opt/alien`.
67pub const STAGED_AGENT_NAME: &str = "agent";
68pub const STAGED_METADATA_NAME: &str = "opt";
69
70/// Mode of the agent binary, owned by `0:0` so the exec uid cannot rewrite its supervisor.
71pub const AGENT_MODE: u32 = 0o755;
72
73/// Name of the exec identity's passwd and group entries.
74pub const EXEC_USER: &str = "sandbox";
75
76/// Mode of the session root, which the exec uid owns.
77pub const SESSION_ROOT_MODE: u32 = 0o700;
78
79/// `RUST_LOG` for a GCP image, which the agent needs set before it logs anything.
80pub const GCP_AGENT_LOG_FILTER: &str = "info";
81
82/// Linux capabilities a root image process keeps: Docker's default set without `NET_RAW`.
83///
84/// `(name, number)` pairs, one list for both sides of the contract. The agent keeps exactly
85/// this set for the image's command and a Kubernetes pod grants exactly this set to the agent
86/// (`drop: [ALL]`, then these), so the agent can start the command with what it is entitled to
87/// and nothing more. Never `NET_ADMIN`, `SYS_ADMIN` or `NET_RAW`.
88pub 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
104/// [`IMAGE_ROOT_CAPABILITY_SET`] as the 32-bit `CapEff` mask the agent applies.
105pub 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/// How an image ends, and the isolation that ending permits.
116///
117/// One value rather than two, because `ALIEN_SANDBOX_ISOLATION` and the trailing `USER` describe
118/// the same decision from opposite sides: an image that asks for `uid-split` under a non-root
119/// `USER` has no privilege left to drop with, and every exec in it fails.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Isolation {
122    /// The agent starts as root and drops to the exec uid before every spawn, so a command can
123    /// never rewrite its own supervisor. The image declares no `USER`.
124    UidSplit,
125    /// The agent starts as the exec uid and supervises commands under it, which is all a runtime
126    /// that refuses a root image can offer. The image ends `USER <uid>:<uid>`.
127    Platform,
128}
129
130impl Isolation {
131    /// The `ALIEN_SANDBOX_ISOLATION` value the agent parses.
132    pub fn env_value(self) -> &'static str {
133        match self {
134            Self::UidSplit => "uid-split",
135            Self::Platform => "platform",
136        }
137    }
138}
139
140/// How the agent decides a caller may be served.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum Authorization {
143    /// The connection is the proof. The agent serves an uncapabilitied request only from a socket
144    /// peer it cannot trace back to the exec uid, which keeps the supervised command out.
145    Transport,
146    /// The caller presents a signed token, which is what a network anything can reach requires.
147    Capability,
148    /// A per-boot credential is read through the cloud's authenticated native file API.
149    NativeFile,
150}
151
152impl Authorization {
153    /// The `ALIEN_SANDBOX_AUTHORIZATION` value the agent parses.
154    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/// The values an image must carry for the agent to run in it.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub struct SandboxImage {
166    /// Uid the supervised command runs as, resolved from a non-root base USER or the default.
167    pub exec_uid: u32,
168    /// Primary gid from the base USER, which may differ from its uid.
169    pub exec_gid: u32,
170    /// Writable session directory. Image-owned directories may also be writable on VM backends.
171    pub session_root: &'static str,
172    /// Port the agent serves, both its own protocol and any lifecycle hooks.
173    pub port: u16,
174    pub authorization: Authorization,
175    pub isolation: Isolation,
176}
177
178impl SandboxImage {
179    /// Gid the supervised command runs as.
180    pub fn exec_gid(&self) -> u32 {
181        self.exec_gid
182    }
183
184    /// The agent's configuration contract as `(name, value)` pairs, in the order the `ENV` block
185    /// lists them.
186    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    /// The `uid:gid` the image runs as, or `None` when it declares no user and starts as root.
204    /// Why the gid is explicit is in the `USER` comment [`entrypoint`] renders.
205    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    /// The port the image exposes, as an OCI `ExposedPorts` key.
213    pub fn exposed_port(&self) -> String {
214        format!("{}/tcp", self.port)
215    }
216
217    /// The exec identity's `/etc/passwd` line, without a trailing newline.
218    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    /// The exec identity's `/etc/group` line, without a trailing newline.
228    pub fn group_entry(&self) -> String {
229        format!("{EXEC_USER}:x:{gid}:", gid = self.exec_gid())
230    }
231}
232
233/// The Lambda MicroVM image, rendered per deployment onto a customer base image.
234///
235/// The agent runs as root so it can drop to [`SandboxImage::exec_uid`] before every spawn; inside
236/// a MicroVM that is contained by hardware virtualisation, which is the tenant boundary. A
237/// shared-kernel backend must give the agent `CAP_SETUID` instead of root.
238pub 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
247/// GCP keeps a root supervisor separate from the non-root command identity.
248/// Live conformance must verify root execution and capability bounds because the
249/// provider's published custom-image requirements do not promise root support.
250/// Agent Platform serves the port the template declares; the agent keeps the shared port so a
251/// workload that binds 8080 itself does not collide with it (measured live: with the agent on
252/// 8080 a root supervisor that also binds 8080 exits at startup).
253pub 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
262/// Every variable a GCP Agent Platform image sets: the contract, then `RUST_LOG`.
263pub 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    // The edge consumes `Authorization` for its own JWT, so a caller's bearer travels in a
268    // header of its own and the agent re-emits it towards the code inside.
269    env.push((
270        ENV_CALLER_AUTHORIZATION_HEADER,
271        CALLER_AUTHORIZATION_HEADER.into(),
272    ));
273    env
274}
275
276/// Azure serves the agent through a published port and an authenticated native file read.
277/// Its native exec path is never used for packaged images because it grants excess capabilities.
278pub const AZURE_SANDBOX: SandboxImage = SandboxImage {
279    exec_uid: 1000,
280    exec_gid: 1000,
281    session_root: "/sandbox",
282    port: AGENT_PORT,
283    authorization: Authorization::NativeFile,
284    isolation: Isolation::UidSplit,
285};
286
287/// A Kubernetes sandbox pod. The cluster's sandboxed runtime is the tenant boundary and refuses to
288/// start a root container here (`runAsNonRoot`), so the agent starts as the exec uid and
289/// supervises under it. Anything on the cluster network can reach the pod, so a caller presents a
290/// signed capability. The exec uid is a default: a non-root base `USER` replaces it.
291pub const KUBERNETES_SANDBOX: SandboxImage = SandboxImage {
292    exec_uid: 1000,
293    exec_gid: 1000,
294    session_root: "/sandbox",
295    port: AGENT_PORT,
296    authorization: Authorization::Capability,
297    isolation: Isolation::Platform,
298};
299
300/// The image every default sandbox builds on, by index digest so both architectures are pinned.
301///
302/// Bumped by hand, then regenerated: Renovate skips the generated Dockerfiles and does not read
303/// this file.
304pub const DEFAULT_SANDBOX_BASE_IMAGE: &str = "public.ecr.aws/docker/library/buildpack-deps:26.04@sha256:159ea382e6fb39e62480ee932113f885f7bd787cd4895fc4dc71aebb175077fd";
305
306/// The image uv and uvx are copied out of, by index digest.
307pub const DEFAULT_SANDBOX_UV_IMAGE: &str = "ghcr.io/astral-sh/uv:0.12.21@sha256:a7aed3216253ee804de3e2d8afa5073baa1a177335345d43845cd4165e43b711";
308
309/// A tool the default sandbox base ships, and the command that shows it runs.
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub struct SandboxTool {
312    /// The Ubuntu archive package it comes from, or `None` for one copied out of
313    /// [`DEFAULT_SANDBOX_UV_IMAGE`].
314    pub package: Option<&'static str>,
315    /// Prints the tool's version and exits zero.
316    pub version_command: &'static str,
317}
318
319/// The toolchain of the default sandbox base, and the one list its probes read.
320///
321/// Every tool lands in `/usr/bin` or `/usr/local/bin`: a supervised command gets a fixed `PATH`
322/// and never the image's `ENV`, so a tool anywhere else is invisible to it.
323pub const DEFAULT_SANDBOX_TOOLS: &[SandboxTool] = &[
324    SandboxTool {
325        package: Some("nftables"),
326        version_command: "/usr/sbin/nft --version",
327    },
328    SandboxTool {
329        package: Some("iptables"),
330        version_command: "iptables-nft --version",
331    },
332    SandboxTool {
333        package: Some("nodejs"),
334        version_command: "node --version",
335    },
336    SandboxTool {
337        package: Some("npm"),
338        version_command: "npm --version",
339    },
340    SandboxTool {
341        package: Some("ripgrep"),
342        version_command: "rg --version",
343    },
344    SandboxTool {
345        package: Some("jq"),
346        version_command: "jq --version",
347    },
348    SandboxTool {
349        package: Some("zip"),
350        version_command: "zip -v",
351    },
352    SandboxTool {
353        package: Some("less"),
354        version_command: "less --version",
355    },
356    SandboxTool {
357        package: Some("nano"),
358        version_command: "nano --version",
359    },
360    SandboxTool {
361        package: Some("vim-tiny"),
362        version_command: "vim.tiny --version",
363    },
364    SandboxTool {
365        package: Some("htop"),
366        version_command: "htop --version",
367    },
368    SandboxTool {
369        package: None,
370        version_command: "uv --version",
371    },
372    SandboxTool {
373        package: None,
374        version_command: "uvx --version",
375    },
376];
377
378/// The `RUN` step creating the exec identity and the session root it owns.
379pub fn identity_setup(image: &SandboxImage) -> String {
380    format!(
381        r#"RUN test ! -L /etc/passwd && test ! -L /etc/group && test ! -L {root} \
382 && touch /etc/passwd /etc/group \
383 && chown 0:0 /etc/passwd /etc/group && chmod 0644 /etc/passwd /etc/group \
384 && (awk -F: '$3 == {uid} {{ found=1 }} END {{ exit !found }}' /etc/passwd || printf '{passwd}\n' >> /etc/passwd) \
385 && (awk -F: '$3 == {gid} {{ found=1 }} END {{ exit !found }}' /etc/group || printf '{group}\n' >> /etc/group) \
386 && mkdir -p {root} \
387 && chown {uid}:{gid} {root} \
388 && chmod {SESSION_ROOT_MODE:04o} {root}"#,
389        passwd = image.passwd_entry(),
390        group = image.group_entry(),
391        root = image.session_root,
392        uid = image.exec_uid,
393        gid = image.exec_gid(),
394    )
395}
396
397/// The `ENV` block carrying the agent's configuration contract.
398pub fn contract_env(image: &SandboxImage) -> String {
399    let vars: Vec<String> = image
400        .contract_env_vars()
401        .iter()
402        .map(|(name, value)| format!("{name}={value}"))
403        .collect();
404    format!("ENV {}", vars.join(" \\\n    "))
405}
406
407/// `EXPOSE`, the image's ending, and the `ENTRYPOINT`.
408pub fn entrypoint(image: &SandboxImage) -> String {
409    let ending = match image.user() {
410        None => String::new(),
411        Some(user) => format!(
412            "# Explicit gid so a runtime that does not read /etc/passwd cannot start the agent in \
413             group 0, which\n# makes the exec drop a privilege crossing whose setgroups needs a \
414             CAP_SETGID this image lacks, so\n# every exec fails.\nUSER {user}\n"
415        ),
416    };
417    format!(
418        "EXPOSE {port}\n{ending}ENTRYPOINT [\"{AGENT_PATH}\"]",
419        port = image.exposed_port()
420    )
421}
422
423/// Path of the committed minimal wolfi GCP Dockerfile, relative to the repository root.
424#[cfg(test)]
425const GCP_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-agent";
426
427/// Path of the committed default GCP sandbox Dockerfile, relative to the repository root.
428#[cfg(test)]
429const GCP_DEFAULT_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-gcp";
430
431/// Path of the committed default sandbox base Dockerfile, relative to the repository root.
432#[cfg(test)]
433const DEFAULT_SANDBOX_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-default";
434
435/// Path of the committed tool list a probe of the default sandbox base reads.
436#[cfg(test)]
437const DEFAULT_SANDBOX_TOOLS_FILE: &str = "docker/sandbox-default-tools.txt";
438
439/// Set to regenerate every committed file this module renders instead of comparing against them.
440/// Named for the agent Dockerfile; every generated header prints the name, so a rename rewrites all.
441#[cfg(test)]
442const SANDBOX_FILES_UPDATE: &str = "UPDATE_SANDBOX_AGENT_DOCKERFILE";
443
444/// Renders [`DEFAULT_SANDBOX_DOCKERFILE`], the tools-only base every default sandbox builds on.
445#[cfg(test)]
446fn default_sandbox_dockerfile() -> String {
447    let packages: Vec<&str> = DEFAULT_SANDBOX_TOOLS
448        .iter()
449        .filter_map(|tool| tool.package)
450        .collect();
451    format!(
452        r#"# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
453# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
454#
455# Multi-arch tools-only base for the default sandbox images, with no agent. An image that runs the
456# agent adds it and its own ending on top, and a runtime with no in-guest agent runs this as is,
457# so it declares no USER, ENTRYPOINT or ENV.
458
459FROM {DEFAULT_SANDBOX_BASE_IMAGE}
460
461# No version pins: the -updates and -security pockets supersede a pinned version and the arm64
462# ports lag behind, so a pin breaks the build. The published digest is what fixes the versions.
463# ca-certificates is already in the base; naming it upgrades the trust store to the archive's
464# current one instead of the one frozen in the base digest.
465RUN apt-get update \
466 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
467      ca-certificates {packages} \
468 && rm -rf /var/lib/apt/lists/*
469
470COPY --from={DEFAULT_SANDBOX_UV_IMAGE} /uv /uvx /usr/local/bin/
471"#,
472        packages = packages.join(" "),
473    )
474}
475
476/// Renders [`DEFAULT_SANDBOX_TOOLS_FILE`], one version command per line.
477#[cfg(test)]
478fn default_sandbox_tools_list() -> String {
479    let mut list = format!(
480        "# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
481# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
482#
483# One command per tool the default sandbox base ships; each prints a version and exits zero.
484"
485    );
486    for tool in DEFAULT_SANDBOX_TOOLS {
487        list.push_str(tool.version_command);
488        list.push('\n');
489    }
490    list
491}
492
493/// Where a GCP image's final stage starts.
494#[cfg(test)]
495enum GcpBase {
496    Image(&'static str),
497    /// A build-arg with no default, which whoever builds the image must pass.
498    BuildArg(&'static str),
499}
500
501/// Renders [`GCP_DOCKERFILE`], the minimal wolfi image.
502#[cfg(test)]
503fn gcp_agent_platform_dockerfile() -> String {
504    gcp_dockerfile(
505        "Multi-arch build for the alien-sandbox-agent Docker image",
506        GcpBase::Image("docker.io/chainguard/wolfi-base:latest"),
507        "# git is for the sandboxed command, not the agent, and pulls 24 transitive packages. That cost
508# lands here because this image is the sandbox, with no customer base image underneath to carry it.
509RUN apk add --no-cache git",
510    )
511}
512
513/// Renders [`GCP_DEFAULT_DOCKERFILE`], the default GCP sandbox image: the agent on the default
514/// sandbox base ([`DEFAULT_SANDBOX_DOCKERFILE`]), which whoever builds it passes by digest.
515#[cfg(test)]
516fn gcp_default_sandbox_dockerfile() -> String {
517    assert_eq!(
518        GCP_AGENT_PLATFORM.exec_uid, 1000,
519        "the userdel below exists only because Ubuntu's own user holds the exec uid"
520    );
521    gcp_dockerfile(
522        "Multi-arch build for the default GCP sandbox image: the default sandbox base plus the agent",
523        GcpBase::BuildArg("SANDBOX_DEFAULT_BASE"),
524        "# Ubuntu ships `ubuntu` at uid 1000. Appending a second entry for that uid leaves `id` and every
525# tool resolving it to `ubuntu`, so the exec user would not be `sandbox`.
526RUN userdel --remove ubuntu",
527    )
528}
529
530/// Renders a GCP Dockerfile onto `base`, with `base_setup` run as root before the agent lands.
531///
532/// Everything outside the shared block is here because it is true of the GCP images alone: the
533/// `binary-selector` stage, which exists because the release workflow builds one manifest for two
534/// architectures from binaries cross-compiled outside Docker; and `RUST_LOG`, which the agent's own
535/// `EnvFilter` needs before it will emit anything.
536#[cfg(test)]
537fn gcp_dockerfile(title: &str, base: GcpBase, base_setup: &str) -> String {
538    let image = &GCP_AGENT_PLATFORM;
539    // An ARG read by a FROM must precede the first FROM, or it is scoped to a stage and empty.
540    // BuildKit reads a parser directive only on the first lines, before any other comment.
541    let (directive, base_arg, base) = match base {
542        GcpBase::Image(reference) => (String::new(), String::new(), reference.to_string()),
543        GcpBase::BuildArg(name) => (
544            "# check=skip=InvalidDefaultArgInFrom\n".to_string(),
545            format!(
546                "# No default: the base's digest exists only once it is built, so whoever builds \
547                 this image\n# passes it. The check directive on line 1 is for this.\nARG {name}\n\n"
548            ),
549            format!("${{{name}}}"),
550        ),
551    };
552    format!(
553        r#"{directive}# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
554# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
555#
556# {title}
557# Run directly as the GCP Agent Platform sandbox; nothing layers on top of it
558
559{base_arg}FROM docker.io/chainguard/wolfi-base:latest AS binary-selector
560
561COPY target/aarch64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-aarch64
562COPY target/x86_64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-x86_64
563
564ARG TARGETARCH
565RUN case "$TARGETARCH" in \
566       amd64)  cp /tmp/alien-sandbox-agent-x86_64 /tmp/alien-sandbox-agent ;; \
567       arm64)  cp /tmp/alien-sandbox-agent-aarch64 /tmp/alien-sandbox-agent ;; \
568       *)      echo "unsupported TARGETARCH '$TARGETARCH'" >&2; exit 1 ;; \
569    esac
570
571FROM {base}
572
573{base_setup}
574
575# Root-owned and unwritable by uid {exec_uid}: the supervised command runs under that uid and must not
576# be able to rewrite its own supervisor.
577COPY --from=binary-selector --chown=0:0 --chmod={AGENT_MODE:04o} \
578     /tmp/alien-sandbox-agent {AGENT_PATH}
579
580# Numeric ids and a plain append rather than adduser, which differs across base distributions.
581# Linux runs a process under a uid with no passwd entry, but tooling inside the sandbox reads one.
582{identity}
583
584# The template carries no env, so the contract lives here, and none of it is optional. transport
585# serves an uncapabilitied request only from a socket `peer::transport_may_serve` cannot trace
586# back to the exec uid, and the agent refuses the mode where /proc/net/tcp is unreadable.
587{env}
588
589# The release build resolves tracing-subscriber once across every package it names, and five of
590# them ask for env-filter, so the agent's fmt::init() has an EnvFilter under it. Unset, that
591# filter discards the startup warning saying this image serves requests without a capability.
592ENV RUST_LOG={GCP_AGENT_LOG_FILTER} \
593    ALIEN_SANDBOX_IMAGE_COMMAND=true
594
595# The edge consumes `Authorization` for its own credential, so a preview caller's bearer arrives in
596# this header and the agent hands it to the code inside as `Authorization`.
597ENV {ENV_CALLER_AUTHORIZATION_HEADER}={CALLER_AUTHORIZATION_HEADER}
598
599# These published agent images have no application startup command. Declare that explicitly so
600# inherited base CMD values cannot become agent arguments or a second shell process.
601RUN mkdir -p /opt/alien \
602 && printf '%s\n' '{empty_image_command}' > {IMAGE_COMMAND_PATH} \
603 && chmod 0444 {IMAGE_COMMAND_PATH}
604
605{entrypoint}
606CMD []
607"#,
608        empty_image_command = serde_json::to_string(&SandboxImageCommand {
609            user: Some(String::new()),
610            working_directory: "/".into(),
611            ..Default::default()
612        })
613        .expect("static default image command must serialize"),
614        exec_uid = image.exec_uid,
615        identity = identity_setup(image),
616        env = contract_env(image),
617        entrypoint = entrypoint(image),
618    )
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624
625    /// A root-supervisor workload commonly binds 8080 itself; the agent must not take it.
626    #[test]
627    fn the_gcp_agent_leaves_port_8080_to_the_workload() {
628        assert_ne!(GCP_AGENT_PLATFORM.port, 8080);
629        assert_eq!(GCP_AGENT_PLATFORM.port, AGENT_PORT);
630    }
631
632    /// The published contract value (Docker's default set without `NET_RAW`); the name list the
633    /// pod grants must equal the mask the agent applies.
634    #[test]
635    fn root_capability_set_is_dockers_default_without_net_raw() {
636        assert_eq!(IMAGE_ROOT_CAPABILITY_MASK, 0xa80405fb);
637        for forbidden in ["NET_ADMIN", "SYS_ADMIN", "NET_RAW"] {
638            assert!(IMAGE_ROOT_CAPABILITY_SET
639                .iter()
640                .all(|(name, _)| *name != forbidden));
641        }
642    }
643
644    fn committed_path(relative: &str) -> std::path::PathBuf {
645        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
646            .join("../..")
647            .join(relative)
648    }
649
650    /// Where two texts first part, in terms a reader can act on. `assert_eq!` on a whole
651    /// Dockerfile prints two escaped blobs and says nothing about which line moved.
652    fn first_difference(committed: &str, rendered: &str) -> String {
653        for (index, (left, right)) in committed.lines().zip(rendered.lines()).enumerate() {
654            if left != right {
655                let line = index + 1;
656                return format!("line {line}: committed {left:?}, contract renders {right:?}");
657            }
658        }
659        format!(
660            "committed has {} lines, the contract renders {}",
661            committed.lines().count(),
662            rendered.lines().count()
663        )
664    }
665
666    /// The whole file, not chosen properties. A mutation this comparison cannot see is one that
667    /// leaves the bytes alone, and there is no such mutation.
668    #[test]
669    fn the_committed_gcp_dockerfiles_are_what_the_contract_renders() {
670        for (file, rendered) in [
671            (GCP_DOCKERFILE, gcp_agent_platform_dockerfile()),
672            (GCP_DEFAULT_DOCKERFILE, gcp_default_sandbox_dockerfile()),
673            (DEFAULT_SANDBOX_DOCKERFILE, default_sandbox_dockerfile()),
674            (DEFAULT_SANDBOX_TOOLS_FILE, default_sandbox_tools_list()),
675        ] {
676            let path = committed_path(file);
677
678            if std::env::var_os(SANDBOX_FILES_UPDATE).is_some() {
679                std::fs::write(&path, &rendered)
680                    .unwrap_or_else(|error| panic!("{} must be writable: {error}", path.display()));
681                continue;
682            }
683
684            let committed = std::fs::read_to_string(&path)
685                .unwrap_or_else(|error| panic!("{} must be readable: {error}", path.display()));
686            assert!(
687                committed == rendered,
688                "{file} has drifted from the contract it is rendered from.\n\
689                 {}\n\
690                 Regenerate it: {SANDBOX_FILES_UPDATE}=1 cargo test -p alien-core --lib sandbox_image",
691                first_difference(&committed, &rendered)
692            );
693        }
694    }
695
696    /// An image built without a Dockerfile carries what the CI images carry, so the env the
697    /// accessor hands out is read back from the committed file rather than restated.
698    #[test]
699    fn the_gcp_env_accessor_is_every_env_the_committed_dockerfile_sets() {
700        let committed = std::fs::read_to_string(committed_path(GCP_DEFAULT_DOCKERFILE)).unwrap();
701        let mut set = Vec::new();
702        let mut in_env = false;
703        for line in committed.lines() {
704            let line = line.trim();
705            let rest = match line.strip_prefix("ENV ") {
706                Some(rest) => rest,
707                None if in_env => line,
708                None => continue,
709            };
710            in_env = rest.ends_with('\\');
711            for pair in rest.trim_end_matches('\\').split_whitespace() {
712                let (name, value) = pair.split_once('=').expect("ENV name=value");
713                set.push((name.to_string(), value.to_string()));
714            }
715        }
716        let accessor: Vec<(String, String)> = gcp_agent_platform_env()
717            .into_iter()
718            .map(|(name, value)| (name.to_string(), value))
719            .collect();
720        assert_eq!(accessor, set);
721    }
722
723    /// Every consumer derives these, so nothing else compares them against a number. The
724    /// setup emitters tell the agent which uid to drop to; if that stops matching the uid the
725    /// image creates, the sandbox starts and every exec fails.
726    #[test]
727    fn the_two_images_carry_the_identities_their_stacks_were_built_against() {
728        assert_eq!(AWS_MICROVM.port, 8971);
729        assert_eq!(AWS_MICROVM.exec_uid, 60000);
730        assert_eq!(AWS_MICROVM.session_root, "/sandbox");
731        assert_eq!(GCP_AGENT_PLATFORM.port, 8971);
732        assert_eq!(GCP_AGENT_PLATFORM.exec_uid, 1000);
733        assert_eq!(GCP_AGENT_PLATFORM.session_root, "/sandbox");
734        for image in [&AWS_MICROVM, &GCP_AGENT_PLATFORM] {
735            assert_ne!(image.exec_uid, 0, "the exec uid must never be root");
736        }
737    }
738
739    /// The ending an image declares and the isolation it claims come off one value, so they
740    /// cannot disagree. The AWS half is rendered at run time and reaches no committed file, which
741    /// is why the whole-file comparison above covers only the GCP side of it.
742    #[test]
743    fn the_ending_an_image_declares_follows_its_isolation() {
744        assert!(!entrypoint(&AWS_MICROVM).contains("USER "));
745        assert!(contract_env(&AWS_MICROVM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
746        assert_eq!(GCP_AGENT_PLATFORM.isolation, Isolation::UidSplit);
747        assert!(contract_env(&GCP_AGENT_PLATFORM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
748    }
749}
750
751/// Root-owned metadata copied from the base image at bundle creation, never from an exec caller.
752#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
753#[serde(rename_all = "camelCase", deny_unknown_fields)]
754pub struct SandboxImageCommand {
755    /// Original OCI USER, including an empty string for Docker's root default.
756    /// Absent only in released metadata whose boot command used the exec identity.
757    #[serde(default, skip_serializing_if = "Option::is_none")]
758    pub user: Option<String>,
759    /// OCI Entrypoint followed by Cmd; empty means there is no image command.
760    pub command: Vec<String>,
761    /// Image environment only, before runtime authorization and provider variables are added.
762    pub env: std::collections::BTreeMap<String, String>,
763    /// OCI WorkingDir, or / if the image does not declare one.
764    pub working_directory: String,
765}
766
767/// Installed outside the command-writable session directory.
768pub const IMAGE_COMMAND_PATH: &str = "/opt/alien/image-command.json";
769
770/// Per-boot agent credential read only through an authenticated native file API.
771pub const NATIVE_TOKEN_PATH: &str = "/opt/alien/native-token";