alien-core 3.3.29

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! What a sandbox image must carry for the agent to serve, and the Dockerfile text carrying it.
//!
//! Two kinds of image exist and neither is built the way the other is. AWS renders one per
//! deployment onto a customer-supplied base image; GCP builds static images in CI. Nothing at build
//! time reads the other side, and a value that disagrees is invisible until a session fails: an
//! agent listening on a port no caller dials, or an exec into a uid the image never created.
//!
//! So the values live here once and both kinds render the block that carries them from this
//! module. The same holds for the default sandbox base both kinds start from: its toolchain is
//! listed here once, and a probe reads that list rather than restating it. The Dockerfiles and the
//! tool list are committed as generated text because CI builds them with `docker build` and probes
//! them from a shell, neither of which can call a Rust function.

/// Path the agent binary is installed at inside every sandbox image.
///
/// An image that installs one path and entrypoints another exits before it serves, and the
/// session times out on connect.
pub const AGENT_PATH: &str = "/usr/local/bin/alien-sandbox-agent";

/// Port the agent serves unless the platform pins another.
///
/// Defined once because two independent copies are a runtime-only failure: the image build places
/// the agent on one port and the client dials the other, and nothing catches it until a sandbox
/// hangs. AWS scopes its endpoint token to an explicit port set, so this cannot be discovered.
pub const AGENT_PORT: u16 = 8971;

/// Mode of the agent binary, owned by `0:0` so the exec uid cannot rewrite its supervisor.
pub const AGENT_MODE: u32 = 0o755;

/// Name of the exec identity's passwd and group entries.
pub const EXEC_USER: &str = "sandbox";

/// Mode of the session root, which the exec uid owns.
pub const SESSION_ROOT_MODE: u32 = 0o700;

/// `RUST_LOG` for a GCP image, which the agent needs set before it logs anything.
pub const GCP_AGENT_LOG_FILTER: &str = "info";

/// How an image ends, and the isolation that ending permits.
///
/// One value rather than two, because `ALIEN_SANDBOX_ISOLATION` and the trailing `USER` describe
/// the same decision from opposite sides: an image that asks for `uid-split` under a non-root
/// `USER` has no privilege left to drop with, and every exec in it fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Isolation {
    /// The agent starts as root and drops to the exec uid before every spawn, so a command can
    /// never rewrite its own supervisor. The image declares no `USER`.
    UidSplit,
    /// The agent starts as the exec uid and supervises commands under it, which is all a runtime
    /// that refuses a root image can offer. The image ends `USER <uid>:<uid>`.
    Platform,
}

impl Isolation {
    /// The `ALIEN_SANDBOX_ISOLATION` value the agent parses.
    pub fn env_value(self) -> &'static str {
        match self {
            Self::UidSplit => "uid-split",
            Self::Platform => "platform",
        }
    }
}

/// How the agent decides a caller may be served.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Authorization {
    /// The connection is the proof. The agent serves an uncapabilitied request only from a socket
    /// peer it cannot trace back to the exec uid, which keeps the supervised command out.
    Transport,
    /// The caller presents a signed token, which is what a network anything can reach requires.
    Capability,
}

impl Authorization {
    /// The `ALIEN_SANDBOX_AUTHORIZATION` value the agent parses.
    pub fn env_value(self) -> &'static str {
        match self {
            Self::Transport => "transport",
            Self::Capability => "capability",
        }
    }
}

/// The values an image must carry for the agent to run in it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SandboxImage {
    /// Uid and gid the supervised command runs as.
    pub exec_uid: u32,
    /// Directory a session's files live under, and the only place `exec_uid` may write.
    pub session_root: &'static str,
    /// Port the agent serves, both its own protocol and any lifecycle hooks.
    pub port: u16,
    pub authorization: Authorization,
    pub isolation: Isolation,
}

impl SandboxImage {
    /// Gid the supervised command runs as, always equal to the exec uid.
    pub fn exec_gid(&self) -> u32 {
        self.exec_uid
    }

    /// The agent's configuration contract as `(name, value)` pairs, in the order the `ENV` block
    /// lists them.
    pub fn contract_env_vars(&self) -> [(&'static str, String); 6] {
        [
            ("ALIEN_SANDBOX_ROOT", self.session_root.to_string()),
            ("ALIEN_SANDBOX_PORT", self.port.to_string()),
            (
                "ALIEN_SANDBOX_AUTHORIZATION",
                self.authorization.env_value().to_string(),
            ),
            ("ALIEN_SANDBOX_EXEC_UID", self.exec_uid.to_string()),
            ("ALIEN_SANDBOX_EXEC_GID", self.exec_gid().to_string()),
            (
                "ALIEN_SANDBOX_ISOLATION",
                self.isolation.env_value().to_string(),
            ),
        ]
    }

    /// The `uid:gid` the image runs as, or `None` when it declares no user and starts as root.
    /// Why the gid is explicit is in the `USER` comment [`entrypoint`] renders.
    pub fn user(&self) -> Option<String> {
        match self.isolation {
            Isolation::UidSplit => None,
            Isolation::Platform => Some(format!("{}:{}", self.exec_uid, self.exec_gid())),
        }
    }

    /// The port the image exposes, as an OCI `ExposedPorts` key.
    pub fn exposed_port(&self) -> String {
        format!("{}/tcp", self.port)
    }

    /// The exec identity's `/etc/passwd` line, without a trailing newline.
    pub fn passwd_entry(&self) -> String {
        format!(
            "{EXEC_USER}:x:{uid}:{gid}::{root}:/sbin/nologin",
            uid = self.exec_uid,
            gid = self.exec_gid(),
            root = self.session_root,
        )
    }

    /// The exec identity's `/etc/group` line, without a trailing newline.
    pub fn group_entry(&self) -> String {
        format!("{EXEC_USER}:x:{gid}:", gid = self.exec_gid())
    }
}

/// The Lambda MicroVM image, rendered per deployment onto a customer base image.
///
/// The agent runs as root so it can drop to [`SandboxImage::exec_uid`] before every spawn; inside
/// a MicroVM that is contained by hardware virtualisation, which is the tenant boundary. A
/// shared-kernel backend must give the agent `CAP_SETUID` instead of root.
pub const AWS_MICROVM: SandboxImage = SandboxImage {
    exec_uid: 60000,
    session_root: "/sandbox",
    port: AGENT_PORT,
    authorization: Authorization::Transport,
    isolation: Isolation::UidSplit,
};

/// The GCP Agent Platform image, built once in CI and run with nothing layered on top.
///
/// 1000 is the conventional first non-root uid, chosen over the 60000 [`AWS_MICROVM`] uses because
/// that value was never tried against Agent Platform. One uid covers the agent and the commands it
/// supervises: Agent Platform refuses an image that requires root, so there is no second uid to
/// drop to.
///
/// Agent Platform is only known to serve 8080, on the image and on the declared template port
/// alike, and whether it honours a declared port or assumes 8080 has never been established.
/// 8080 is right under either answer; any other number is right under only one.
pub const GCP_AGENT_PLATFORM: SandboxImage = SandboxImage {
    exec_uid: 1000,
    session_root: "/sandbox",
    port: 8080,
    authorization: Authorization::Transport,
    isolation: Isolation::Platform,
};

/// Every variable a GCP Agent Platform image sets: the contract, then `RUST_LOG`.
pub fn gcp_agent_platform_env() -> Vec<(&'static str, String)> {
    let mut env = GCP_AGENT_PLATFORM.contract_env_vars().to_vec();
    env.push(("RUST_LOG", GCP_AGENT_LOG_FILTER.to_string()));
    env
}

/// The image every default sandbox builds on, by index digest so both architectures are pinned.
///
/// Bumped by hand, then regenerated: Renovate skips the generated Dockerfiles and does not read
/// this file.
pub const DEFAULT_SANDBOX_BASE_IMAGE: &str = "public.ecr.aws/docker/library/buildpack-deps:26.04@sha256:159ea382e6fb39e62480ee932113f885f7bd787cd4895fc4dc71aebb175077fd";

/// The image uv and uvx are copied out of, by index digest.
pub const DEFAULT_SANDBOX_UV_IMAGE: &str = "ghcr.io/astral-sh/uv:0.12.21@sha256:a7aed3216253ee804de3e2d8afa5073baa1a177335345d43845cd4165e43b711";

/// A tool the default sandbox base ships, and the command that shows it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SandboxTool {
    /// The Ubuntu archive package it comes from, or `None` for one copied out of
    /// [`DEFAULT_SANDBOX_UV_IMAGE`].
    pub package: Option<&'static str>,
    /// Prints the tool's version and exits zero.
    pub version_command: &'static str,
}

/// The toolchain of the default sandbox base, and the one list its probes read.
///
/// Every tool lands in `/usr/bin` or `/usr/local/bin`: a supervised command gets a fixed `PATH`
/// and never the image's `ENV`, so a tool anywhere else is invisible to it.
pub const DEFAULT_SANDBOX_TOOLS: &[SandboxTool] = &[
    SandboxTool {
        package: Some("nftables"),
        version_command: "/usr/sbin/nft --version",
    },
    SandboxTool {
        package: Some("iptables"),
        version_command: "iptables-nft --version",
    },
    SandboxTool {
        package: Some("nodejs"),
        version_command: "node --version",
    },
    SandboxTool {
        package: Some("npm"),
        version_command: "npm --version",
    },
    SandboxTool {
        package: Some("ripgrep"),
        version_command: "rg --version",
    },
    SandboxTool {
        package: Some("jq"),
        version_command: "jq --version",
    },
    SandboxTool {
        package: Some("zip"),
        version_command: "zip -v",
    },
    SandboxTool {
        package: Some("less"),
        version_command: "less --version",
    },
    SandboxTool {
        package: Some("nano"),
        version_command: "nano --version",
    },
    SandboxTool {
        package: Some("vim-tiny"),
        version_command: "vim.tiny --version",
    },
    SandboxTool {
        package: Some("htop"),
        version_command: "htop --version",
    },
    SandboxTool {
        package: None,
        version_command: "uv --version",
    },
    SandboxTool {
        package: None,
        version_command: "uvx --version",
    },
];

/// The `RUN` step creating the exec identity and the session root it owns.
pub fn identity_setup(image: &SandboxImage) -> String {
    format!(
        r#"RUN printf '{passwd}\n' >> /etc/passwd \
 && printf '{group}\n' >> /etc/group \
 && mkdir -p {root} \
 && chown {uid}:{gid} {root} \
 && chmod {SESSION_ROOT_MODE:04o} {root}"#,
        passwd = image.passwd_entry(),
        group = image.group_entry(),
        root = image.session_root,
        uid = image.exec_uid,
        gid = image.exec_gid(),
    )
}

/// The `ENV` block carrying the agent's configuration contract.
pub fn contract_env(image: &SandboxImage) -> String {
    let vars: Vec<String> = image
        .contract_env_vars()
        .iter()
        .map(|(name, value)| format!("{name}={value}"))
        .collect();
    format!("ENV {}", vars.join(" \\\n    "))
}

/// `EXPOSE`, the image's ending, and the `ENTRYPOINT`.
pub fn entrypoint(image: &SandboxImage) -> String {
    let ending = match image.user() {
        None => String::new(),
        Some(user) => format!(
            "# Explicit gid so a runtime that does not read /etc/passwd cannot start the agent in \
             group 0, which\n# makes the exec drop a privilege crossing whose setgroups needs a \
             CAP_SETGID this image lacks, so\n# every exec fails.\nUSER {user}\n"
        ),
    };
    format!(
        "EXPOSE {port}\n{ending}ENTRYPOINT [\"{AGENT_PATH}\"]",
        port = image.exposed_port()
    )
}

/// Path of the committed minimal wolfi GCP Dockerfile, relative to the repository root.
#[cfg(test)]
const GCP_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-agent";

/// Path of the committed default GCP sandbox Dockerfile, relative to the repository root.
#[cfg(test)]
const GCP_DEFAULT_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-gcp";

/// Path of the committed default sandbox base Dockerfile, relative to the repository root.
#[cfg(test)]
const DEFAULT_SANDBOX_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-default";

/// Path of the committed tool list a probe of the default sandbox base reads.
#[cfg(test)]
const DEFAULT_SANDBOX_TOOLS_FILE: &str = "docker/sandbox-default-tools.txt";

/// Set to regenerate every committed file this module renders instead of comparing against them.
/// Named for the agent Dockerfile; every generated header prints the name, so a rename rewrites all.
#[cfg(test)]
const SANDBOX_FILES_UPDATE: &str = "UPDATE_SANDBOX_AGENT_DOCKERFILE";

/// Renders [`DEFAULT_SANDBOX_DOCKERFILE`], the tools-only base every default sandbox builds on.
#[cfg(test)]
fn default_sandbox_dockerfile() -> String {
    let packages: Vec<&str> = DEFAULT_SANDBOX_TOOLS
        .iter()
        .filter_map(|tool| tool.package)
        .collect();
    format!(
        r#"# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
#
# Multi-arch tools-only base for the default sandbox images, with no agent. An image that runs the
# agent adds it and its own ending on top, and a runtime with no in-guest agent runs this as is,
# so it declares no USER, ENTRYPOINT or ENV.

FROM {DEFAULT_SANDBOX_BASE_IMAGE}

# No version pins: the -updates and -security pockets supersede a pinned version and the arm64
# ports lag behind, so a pin breaks the build. The published digest is what fixes the versions.
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
      {packages} \
 && rm -rf /var/lib/apt/lists/*

COPY --from={DEFAULT_SANDBOX_UV_IMAGE} /uv /uvx /usr/local/bin/
"#,
        packages = packages.join(" "),
    )
}

/// Renders [`DEFAULT_SANDBOX_TOOLS_FILE`], one version command per line.
#[cfg(test)]
fn default_sandbox_tools_list() -> String {
    let mut list = format!(
        "# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
#
# One command per tool the default sandbox base ships; each prints a version and exits zero.
"
    );
    for tool in DEFAULT_SANDBOX_TOOLS {
        list.push_str(tool.version_command);
        list.push('\n');
    }
    list
}

/// Where a GCP image's final stage starts.
#[cfg(test)]
enum GcpBase {
    Image(&'static str),
    /// A build-arg with no default, which whoever builds the image must pass.
    BuildArg(&'static str),
}

/// Renders [`GCP_DOCKERFILE`], the minimal wolfi image.
#[cfg(test)]
fn gcp_agent_platform_dockerfile() -> String {
    gcp_dockerfile(
        "Multi-arch build for the alien-sandbox-agent Docker image",
        GcpBase::Image("docker.io/chainguard/wolfi-base:latest"),
        "# git is for the sandboxed command, not the agent, and pulls 24 transitive packages. That cost
# lands here because this image is the sandbox, with no customer base image underneath to carry it.
RUN apk add --no-cache git",
    )
}

/// Renders [`GCP_DEFAULT_DOCKERFILE`], the default GCP sandbox image: the agent on the default
/// sandbox base ([`DEFAULT_SANDBOX_DOCKERFILE`]), which whoever builds it passes by digest.
#[cfg(test)]
fn gcp_default_sandbox_dockerfile() -> String {
    assert_eq!(
        GCP_AGENT_PLATFORM.exec_uid, 1000,
        "the userdel below exists only because Ubuntu's own user holds the exec uid"
    );
    gcp_dockerfile(
        "Multi-arch build for the default GCP sandbox image: the default sandbox base plus the agent",
        GcpBase::BuildArg("SANDBOX_DEFAULT_BASE"),
        "# Ubuntu ships `ubuntu` at uid 1000. Appending a second entry for that uid leaves `id` and every
# tool resolving it to `ubuntu`, so the exec user would not be `sandbox`.
RUN userdel --remove ubuntu",
    )
}

/// Renders a GCP Dockerfile onto `base`, with `base_setup` run as root before the agent lands.
///
/// Everything outside the shared block is here because it is true of the GCP images alone: the
/// `binary-selector` stage, which exists because the release workflow builds one manifest for two
/// architectures from binaries cross-compiled outside Docker; and `RUST_LOG`, which the agent's own
/// `EnvFilter` needs before it will emit anything.
#[cfg(test)]
fn gcp_dockerfile(title: &str, base: GcpBase, base_setup: &str) -> String {
    let image = &GCP_AGENT_PLATFORM;
    // An ARG read by a FROM must precede the first FROM, or it is scoped to a stage and empty.
    // BuildKit reads a parser directive only on the first lines, before any other comment.
    let (directive, base_arg, base) = match base {
        GcpBase::Image(reference) => (String::new(), String::new(), reference.to_string()),
        GcpBase::BuildArg(name) => (
            "# check=skip=InvalidDefaultArgInFrom\n".to_string(),
            format!(
                "# No default: the base's digest exists only once it is built, so whoever builds \
                 this image\n# passes it. The check directive on line 1 is for this.\nARG {name}\n\n"
            ),
            format!("${{{name}}}"),
        ),
    };
    format!(
        r#"{directive}# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
# Regenerate with {SANDBOX_FILES_UPDATE}=1 in front of that command.
#
# {title}
# Run directly as the GCP Agent Platform sandbox; nothing layers on top of it

{base_arg}FROM docker.io/chainguard/wolfi-base:latest AS binary-selector

COPY target/aarch64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-aarch64
COPY target/x86_64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-x86_64

ARG TARGETARCH
RUN case "$TARGETARCH" in \
       amd64)  cp /tmp/alien-sandbox-agent-x86_64 /tmp/alien-sandbox-agent ;; \
       arm64)  cp /tmp/alien-sandbox-agent-aarch64 /tmp/alien-sandbox-agent ;; \
       *)      echo "unsupported TARGETARCH '$TARGETARCH'" >&2; exit 1 ;; \
    esac

FROM {base}

{base_setup}

# Root-owned and unwritable by uid {exec_uid}: the supervised command runs under that uid and must not
# be able to rewrite its own supervisor.
COPY --from=binary-selector --chown=0:0 --chmod={AGENT_MODE:04o} \
     /tmp/alien-sandbox-agent {AGENT_PATH}

# Numeric ids and a plain append rather than adduser, which differs across base distributions.
# Linux runs a process under a uid with no passwd entry, but tooling inside the sandbox reads one.
{identity}

# The template carries no env, so the contract lives here, and none of it is optional. transport
# serves an uncapabilitied request only from a socket `peer::transport_may_serve` cannot trace
# back to the exec uid, and the agent refuses the mode where /proc/net/tcp is unreadable.
{env}

# The release build resolves tracing-subscriber once across every package it names, and five of
# them ask for env-filter, so the agent's fmt::init() has an EnvFilter under it. Unset, that
# filter discards the startup warning saying this image serves requests without a capability.
ENV RUST_LOG={GCP_AGENT_LOG_FILTER}

{entrypoint}
"#,
        exec_uid = image.exec_uid,
        identity = identity_setup(image),
        env = contract_env(image),
        entrypoint = entrypoint(image),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn committed_path(relative: &str) -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .join(relative)
    }

    /// Where two texts first part, in terms a reader can act on. `assert_eq!` on a whole
    /// Dockerfile prints two escaped blobs and says nothing about which line moved.
    fn first_difference(committed: &str, rendered: &str) -> String {
        for (index, (left, right)) in committed.lines().zip(rendered.lines()).enumerate() {
            if left != right {
                let line = index + 1;
                return format!("line {line}: committed {left:?}, contract renders {right:?}");
            }
        }
        format!(
            "committed has {} lines, the contract renders {}",
            committed.lines().count(),
            rendered.lines().count()
        )
    }

    /// The whole file, not chosen properties. A mutation this comparison cannot see is one that
    /// leaves the bytes alone, and there is no such mutation.
    #[test]
    fn the_committed_gcp_dockerfiles_are_what_the_contract_renders() {
        for (file, rendered) in [
            (GCP_DOCKERFILE, gcp_agent_platform_dockerfile()),
            (GCP_DEFAULT_DOCKERFILE, gcp_default_sandbox_dockerfile()),
            (DEFAULT_SANDBOX_DOCKERFILE, default_sandbox_dockerfile()),
            (DEFAULT_SANDBOX_TOOLS_FILE, default_sandbox_tools_list()),
        ] {
            let path = committed_path(file);

            if std::env::var_os(SANDBOX_FILES_UPDATE).is_some() {
                std::fs::write(&path, &rendered)
                    .unwrap_or_else(|error| panic!("{} must be writable: {error}", path.display()));
                continue;
            }

            let committed = std::fs::read_to_string(&path)
                .unwrap_or_else(|error| panic!("{} must be readable: {error}", path.display()));
            assert!(
                committed == rendered,
                "{file} has drifted from the contract it is rendered from.\n\
                 {}\n\
                 Regenerate it: {SANDBOX_FILES_UPDATE}=1 cargo test -p alien-core --lib sandbox_image",
                first_difference(&committed, &rendered)
            );
        }
    }

    /// An image built without a Dockerfile carries what the CI images carry, so the env the
    /// accessor hands out is read back from the committed file rather than restated.
    #[test]
    fn the_gcp_env_accessor_is_every_env_the_committed_dockerfile_sets() {
        let committed = std::fs::read_to_string(committed_path(GCP_DEFAULT_DOCKERFILE)).unwrap();
        let mut set = Vec::new();
        let mut in_env = false;
        for line in committed.lines() {
            let line = line.trim();
            let rest = match line.strip_prefix("ENV ") {
                Some(rest) => rest,
                None if in_env => line,
                None => continue,
            };
            in_env = rest.ends_with('\\');
            for pair in rest.trim_end_matches('\\').split_whitespace() {
                let (name, value) = pair.split_once('=').expect("ENV name=value");
                set.push((name.to_string(), value.to_string()));
            }
        }
        let accessor: Vec<(String, String)> = gcp_agent_platform_env()
            .into_iter()
            .map(|(name, value)| (name.to_string(), value))
            .collect();
        assert_eq!(accessor, set);
    }

    /// Every consumer derives these, so nothing else compares them against a number. The
    /// setup emitters tell the agent which uid to drop to; if that stops matching the uid the
    /// image creates, the sandbox starts and every exec fails.
    #[test]
    fn the_two_images_carry_the_identities_their_stacks_were_built_against() {
        assert_eq!(AWS_MICROVM.port, 8971);
        assert_eq!(AWS_MICROVM.exec_uid, 60000);
        assert_eq!(AWS_MICROVM.session_root, "/sandbox");
        assert_eq!(GCP_AGENT_PLATFORM.port, 8080);
        assert_eq!(GCP_AGENT_PLATFORM.exec_uid, 1000);
        assert_eq!(GCP_AGENT_PLATFORM.session_root, "/sandbox");
        for image in [&AWS_MICROVM, &GCP_AGENT_PLATFORM] {
            assert_ne!(image.exec_uid, 0, "the exec uid must never be root");
        }
    }

    /// The ending an image declares and the isolation it claims come off one value, so they
    /// cannot disagree. The AWS half is rendered at run time and reaches no committed file, which
    /// is why the whole-file comparison above covers only the GCP side of it.
    #[test]
    fn the_ending_an_image_declares_follows_its_isolation() {
        assert!(!entrypoint(&AWS_MICROVM).contains("USER "));
        assert!(contract_env(&AWS_MICROVM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
        assert!(entrypoint(&GCP_AGENT_PLATFORM).contains("\nUSER 1000:1000\n"));
        assert!(contract_env(&GCP_AGENT_PLATFORM).contains("ALIEN_SANDBOX_ISOLATION=platform"));
    }
}

/// Root-owned metadata copied from the base image at bundle creation, never from an exec caller.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SandboxImageCommand {
    /// OCI Entrypoint followed by Cmd; empty means there is no image command.
    pub command: Vec<String>,
    /// Image environment only, before runtime authorization and provider variables are added.
    pub env: std::collections::BTreeMap<String, String>,
    /// OCI WorkingDir, or / if the image does not declare one.
    pub working_directory: String,
}

/// Installed outside the command-writable session directory.
pub const IMAGE_COMMAND_PATH: &str = "/opt/alien/image-command.json";