Skip to main content

microvms_app/control/
artifact.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The build artifact: a zip of the daemon binary, a Dockerfile, and — when the caller
3//! passes [`ProjectFiles`] — the project's dependency files.
4//!
5//! What `CreateMicrovmImage`'s `codeArtifact.uri` points at (`sandbox.py:523`
6//! `build_artifact`). Two entries always, both carrying a measured constraint, plus an
7//! ecosystem-named manifest/lockfile pair when the image bakes an environment layer (#74).
8//!
9//! # The execute bit has to be in the zip entry
10//!
11//! A build that copies a non-executable binary produces an image whose `CMD` fails, and
12//! the failure surfaces as a **run-hook timeout** — which says nothing about permissions,
13//! and sends the reader to look at the daemon's startup path instead of at the archive.
14//! So the `agentd` entry sets mode `0o755` explicitly rather than inheriting whatever the
15//! host file had.
16//!
17//! # The agent token is never in here (TRAP-5's other half)
18//!
19//! The artifact becomes a **shared image snapshot**: every MicroVM launched from the image
20//! sees the same bytes. A per-VM secret in there is a per-VM secret shared with every VM.
21//! So the token travels through `runHookPayload` at launch instead, and this function has
22//! no parameter that could carry one — see [`crate::control::microvm`]. The test at the
23//! bottom of this file scans the produced zip's raw bytes for a token value to prove the
24//! path stays closed, which is a byte scan rather than an API review because the leak
25//! would be a *value* appearing somewhere, not a parameter being declared.
26
27use std::io::Write as _;
28use std::time::Duration;
29
30use crate::error::{Error, ErrorKind};
31
32/// The Dockerfile entry's name, which the build looks for by convention.
33const DOCKERFILE_ENTRY: &str = "Dockerfile";
34
35/// The daemon entry's name, matching the `CMD ["/agentd"]` the Dockerfile sets.
36const AGENTD_ENTRY: &str = "agentd";
37
38/// The mode the daemon entry carries.
39///
40/// See the module docs: a non-executable binary here becomes a run-hook timeout later.
41const AGENTD_MODE: u32 = 0o755;
42
43/// An ecosystem whose dependency files may enter the build artifact (#74).
44///
45/// The variant fixes **both entry names**. That is the TRAP-5 half of the design: the
46/// artifact is a shared image snapshot, so what may enter it is an allowlist of
47/// dependency-defining files, not a caller-named list — there is no field anywhere in this
48/// module a caller could put `.env` or a credentials file's name into. The byte-scan test
49/// at the bottom of this file covers the entries this type admits.
50#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51pub enum Ecosystem {
52    /// Python under uv: `pyproject.toml` + `uv.lock`.
53    Uv,
54    /// Node under npm: `package.json` + `package-lock.json`.
55    Npm,
56    /// Rust under cargo: `Cargo.toml` + `Cargo.lock`.
57    Cargo,
58}
59
60impl Ecosystem {
61    /// Every ecosystem, in detection order.
62    pub const ALL: [Self; 3] = [Self::Uv, Self::Npm, Self::Cargo];
63
64    /// The manifest's file name, which is also its zip entry name.
65    pub fn manifest_name(self) -> &'static str {
66        match self {
67            Self::Uv => "pyproject.toml",
68            Self::Npm => "package.json",
69            Self::Cargo => "Cargo.toml",
70        }
71    }
72
73    /// The lockfile's file name, which is also its zip entry name — and the file the
74    /// environment layer is keyed on (#74).
75    pub fn lockfile_name(self) -> &'static str {
76        match self {
77            Self::Uv => "uv.lock",
78            Self::Npm => "package-lock.json",
79            Self::Cargo => "Cargo.lock",
80        }
81    }
82
83    /// The whole `RUN` line that installs the environment layer: toolchain bootstrap on
84    /// the managed al2023 base, then the lockfile-faithful install.
85    ///
86    /// # The install commands are the lockfile-faithful spellings
87    ///
88    /// `uv sync --locked`, `npm ci`, and `cargo fetch --locked` each **refuse** a lockfile
89    /// that disagrees with its manifest rather than quietly re-resolving — which is what
90    /// keeps the baked layer the thing the content hash says it is. `uv sync` without
91    /// `--locked`, `npm install`, or a bare `cargo fetch` would install *something* and
92    /// the hash would then name an environment the build did not produce.
93    ///
94    /// # The bootstrap packages are measured, the full build is not yet
95    ///
96    /// The managed base is al2023-minimal and ships no toolchain, so each line installs
97    /// its own. Package names and the binaries they land were verified against the
98    /// Amazon Linux 2023 repos (2026-08-31): `python3.12-pip` puts `pip3.12` on PATH,
99    /// `nodejs22-npm` puts `npm` and `node` on PATH, `cargo` puts `cargo` on PATH.
100    /// `install_weak_deps=0` keeps the layer minimal. A full in-guest build of each line
101    /// is the live-conformance scenario #74's acceptance defers to — see the issue.
102    ///
103    /// Cargo is the one that needs a stub: `cargo fetch` refuses a package with no
104    /// targets, so the line creates an empty `src/main.rs` first. The working tree synced
105    /// at launch lands over it.
106    pub fn install_run_line(self) -> &'static str {
107        match self {
108            Self::Uv => {
109                "RUN dnf -y --setopt=install_weak_deps=0 install python3.12 python3.12-pip \
110                 && dnf clean all && pip3.12 install --no-cache-dir uv && uv sync --locked"
111            }
112            Self::Npm => {
113                "RUN dnf -y --setopt=install_weak_deps=0 install nodejs22-npm \
114                 && dnf clean all && npm ci"
115            }
116            Self::Cargo => {
117                "RUN dnf -y --setopt=install_weak_deps=0 install cargo \
118                 && dnf clean all && mkdir -p src && touch src/main.rs \
119                 && cargo fetch --locked"
120            }
121        }
122    }
123}
124
125/// A project's dependency files: the lockfile plus the manifest that owns it.
126///
127/// Bytes rather than paths, for the reason [`build_artifact`]'s `binary` is bytes: the
128/// caller owns the read, and this module keeps no filesystem behaviour to stub in a test.
129/// The entry names come from [`Ecosystem`], never from the caller — see the type's docs
130/// for why that is a TRAP-5 property rather than a convenience.
131#[derive(Clone, Debug, Eq, PartialEq)]
132pub struct ProjectFiles {
133    /// Which ecosystem's pair this is, fixing both entry names.
134    pub ecosystem: Ecosystem,
135    /// The manifest's bytes (`pyproject.toml`, `package.json`, `Cargo.toml`).
136    pub manifest: Vec<u8>,
137    /// The lockfile's bytes (`uv.lock`, `package-lock.json`, `Cargo.lock`).
138    pub lockfile: Vec<u8>,
139}
140
141/// Zips `binary` with `dockerfile` — and, when given, the project's dependency files —
142/// into the bytes `codeArtifact.uri` will point at.
143///
144/// `binary` is the daemon's bytes rather than a path, so the caller owns the read and this
145/// function has no filesystem behaviour to stub in a test. `project` adds exactly two more
146/// entries, named by its [`Ecosystem`], at the archive root beside the Dockerfile — which
147/// is the build context root, so a `COPY pyproject.toml uv.lock …` in the Dockerfile finds
148/// them.
149pub fn build_artifact(
150    binary: &[u8],
151    dockerfile: &str,
152    project: Option<&ProjectFiles>,
153) -> Result<Vec<u8>, Error> {
154    build_artifact_with_context(binary, dockerfile, project, None)
155}
156
157/// The mode every non-executable artifact entry carries.
158const FILE_MODE: u32 = 0o644;
159
160/// [`build_artifact`] plus a build context: the context's files at their relative paths
161/// beside the Dockerfile, which is the build context root, so the Dockerfile's `COPY` lines
162/// find them (IMAGE-7).
163///
164/// # One set of inputs, one object
165///
166/// Every entry carries the DOS epoch (1980-01-01) as its date and a fixed mode — `0o755` for
167/// the daemon and for context files with an execute bit, `0o644` for everything else — under
168/// Unix as the host system, and the entries are written in a fixed order: `Dockerfile`, `agentd`, the project pair, then
169/// the context sorted by name. So equal inputs produce byte-identical archives on any host
170/// at any time, and a content-addressed S3 key holds one object rather than whichever
171/// upload landed last. (Byte identity across `zip` crate versions is not promised; the image
172/// name hashes the inputs, not these bytes, for exactly that reason — see
173/// [`artifact_content_hash`].)
174///
175/// Refuses a `binary` that isn't an aarch64 ELF, empty included (#257): every artifact
176/// carries the daemon as its `CMD`, and a build finds the wrong one only as a run-hook
177/// timeout. Refuses a context entry that repeats a project file's name, since one archive
178/// cannot hold two entries of one name.
179pub fn build_artifact_with_context(
180    binary: &[u8],
181    dockerfile: &str,
182    project: Option<&ProjectFiles>,
183    context: Option<&super::context::BuildContext>,
184) -> Result<Vec<u8>, Error> {
185    use zip::write::{SimpleFileOptions, ZipWriter};
186
187    microvms_domain::provision::require_aarch64(binary)?;
188    if let (Some(project), Some(context)) = (project, context)
189        && let Some(entry) = context.entries().iter().find(|entry| {
190            entry.name == project.ecosystem.manifest_name()
191                || entry.name == project.ecosystem.lockfile_name()
192        })
193    {
194        return Err(Error::invalid_arg(format!(
195            "the build context has {:?} at its root, which the project files already carry;              drop one of the two.",
196            entry.name
197        )));
198    }
199
200    let mut writer = ZipWriter::new(std::io::Cursor::new(Vec::new()));
201    // Unix as every entry's host system: left unset, zip records the host the build runs on,
202    // MS-DOS on Windows, where a reader that follows the record reads these modes as DOS
203    // attributes (zip 9 gives `0o664`, so the daemon loses its execute bit) and the bytes
204    // differ from a Linux or macOS build of the same inputs.
205    let options = |mode: u32| {
206        SimpleFileOptions::default()
207            .compression_method(zip::CompressionMethod::Deflated)
208            .last_modified_time(zip::DateTime::default())
209            .system(zip::System::Unix)
210            .unix_permissions(mode)
211    };
212
213    let mut write_entry = |name: &str, bytes: &[u8], mode: u32| {
214        writer
215            .start_file(name, options(mode))
216            .and_then(|()| writer.write_all(bytes).map_err(Into::into))
217            .map_err(|error| {
218                Error::new(
219                    ErrorKind::Unexpected,
220                    format!("could not add {name} to the build artifact: {error}"),
221                )
222            })
223    };
224
225    write_entry(DOCKERFILE_ENTRY, dockerfile.as_bytes(), FILE_MODE)?;
226    write_entry(AGENTD_ENTRY, binary, AGENTD_MODE)?;
227    if let Some(project) = project {
228        write_entry(
229            project.ecosystem.manifest_name(),
230            &project.manifest,
231            FILE_MODE,
232        )?;
233        write_entry(
234            project.ecosystem.lockfile_name(),
235            &project.lockfile,
236            FILE_MODE,
237        )?;
238    }
239    if let Some(context) = context {
240        for entry in context.entries() {
241            write_entry(&entry.name, &entry.bytes, entry.mode)?;
242        }
243    }
244
245    let bytes = writer
246        .finish()
247        .map_err(|error| {
248            Error::new(
249                ErrorKind::Unexpected,
250                format!("could not finish the build artifact: {error}"),
251            )
252        })?
253        .into_inner();
254    Ok(bytes)
255}
256
257/// The sha256 of the artifact's inputs, as lowercase hex.
258///
259/// # What is hashed, and why not the zip
260///
261/// The **inputs** — the daemon binary's bytes, the Dockerfile text, and the project
262/// files when the artifact carries them — rather than the bytes [`build_artifact`]
263/// produces. The zip is a container: its byte identity depends on the `zip` crate's
264/// version, its compression level, and its header defaults, so an upgraded dependency
265/// would silently change every image name and orphan every reuse. The inputs are what a
266/// build actually consumes, and two builds with equal inputs produce interchangeable
267/// images — which is the property content-addressed reuse rests on.
268///
269/// Each input is length-prefixed before hashing, so `(binary="ab", dockerfile="c")` and
270/// `(binary="a", dockerfile="bc")` are different hashes rather than one concatenation.
271/// A project file contributes its entry **name and bytes**, both length-prefixed, so the
272/// same bytes under a different ecosystem — `Cargo.lock` and `package-lock.json` holding
273/// identical text — are different identities too.
274///
275/// # `None` is the historical digest, deliberately
276///
277/// With no project files the digest stream is byte-identical to what this function
278/// produced before #74, so every projectless image name in every account survives the
279/// change — the alternative orphans exactly the reuse this hash exists to serve. The
280/// pinned vector in the tests is what holds that fixed. This is #74's key: two projects
281/// with identical lockfiles share an image, and a lockfile edit is a new name and a
282/// fresh build.
283pub fn artifact_content_hash(
284    binary: &[u8],
285    dockerfile: &str,
286    project: Option<&ProjectFiles>,
287) -> String {
288    artifact_content_hash_with_context(binary, dockerfile, project, None)
289}
290
291/// The tag that opens the build context's part of the digest stream.
292///
293/// A project file contributes a fixed file name, so no project entry can begin with this
294/// tag's length and bytes: the two sections cannot be confused for each other.
295const CONTEXT_TAG: &[u8] = b"microvms-build-context/1";
296
297/// [`artifact_content_hash`] extended with a build context (IMAGE-6).
298///
299/// With no context, or an empty one, the stream is byte-for-byte the one
300/// `artifact_content_hash` hashed before #221 — an empty context adds no entry, so it is the
301/// same artifact — and the pinned vector in the tests holds that fixed, so no `build --reuse`
302/// or `AgentVm` image name moves. A non-empty context appends [`CONTEXT_TAG`], the entry
303/// count, and each entry's name, mode, and bytes, the name and bytes length-prefixed. The
304/// entries are sorted by name ([`super::context::BuildContext`]), so the order a filesystem
305/// listed them in is not part of the identity; the mode is, because `COPY` keeps it.
306pub fn artifact_content_hash_with_context(
307    binary: &[u8],
308    dockerfile: &str,
309    project: Option<&ProjectFiles>,
310    context: Option<&super::context::BuildContext>,
311) -> String {
312    use sha2::{Digest as _, Sha256};
313
314    let mut hasher = Sha256::new();
315    hasher.update((binary.len() as u64).to_be_bytes());
316    hasher.update(binary);
317    hasher.update((dockerfile.len() as u64).to_be_bytes());
318    hasher.update(dockerfile.as_bytes());
319    if let Some(project) = project {
320        for (name, bytes) in [
321            (project.ecosystem.manifest_name(), &project.manifest),
322            (project.ecosystem.lockfile_name(), &project.lockfile),
323        ] {
324            hasher.update((name.len() as u64).to_be_bytes());
325            hasher.update(name.as_bytes());
326            hasher.update((bytes.len() as u64).to_be_bytes());
327            hasher.update(bytes);
328        }
329    }
330    if let Some(context) = context.filter(|context| !context.entries().is_empty()) {
331        hasher.update((CONTEXT_TAG.len() as u64).to_be_bytes());
332        hasher.update(CONTEXT_TAG);
333        hasher.update((context.entries().len() as u64).to_be_bytes());
334        for entry in context.entries() {
335            hasher.update((entry.name.len() as u64).to_be_bytes());
336            hasher.update(entry.name.as_bytes());
337            hasher.update(entry.mode.to_be_bytes());
338            hasher.update((entry.bytes.len() as u64).to_be_bytes());
339            hasher.update(&entry.bytes);
340        }
341    }
342    const_hex::encode(hasher.finalize())
343}
344
345/// A base image: the platform ARN, the Dockerfile `FROM` that pairs with it, and whether
346/// it declares a `WORKDIR`.
347///
348/// All three together because the first two **must** agree and used to be able to
349/// disagree: the Python client's `DEFAULT_BASE_IMAGE` named the managed base for
350/// `baseImageArn` while `default_dockerfile` hardcoded an unrelated registry literal in
351/// its `FROM`, so changing either left the other pointing somewhere else
352/// (`sandbox.py:410-444`). Pairing them means a caller selects one thing and both fields
353/// follow.
354#[derive(Clone, Debug, Eq, PartialEq)]
355pub struct BaseImage {
356    /// Goes into `baseImageArn` — the platform's managed base, not a registry ref.
357    pub name: String,
358    /// Goes into the Dockerfile `FROM` — the registry ref measured alongside `name`.
359    pub docker_ref: String,
360    /// What `docker inspect` reports for `WorkingDir`. Empty means it declares none.
361    ///
362    /// A field rather than a lookup because a caller with a purpose-built image is the
363    /// only one who can say what their image declares, and this client cannot read it
364    /// without pulling the manifest.
365    pub working_dir: String,
366}
367
368impl BaseImage {
369    /// The managed base every `docs/PLATFORM.md` measurement from 2026-08-06 onward used,
370    /// paired with the registry ref those same builds used as `FROM`.
371    ///
372    /// `working_dir` is empty, and that is measured rather than assumed:
373    /// `al2023-minimal`, `python:3.12-slim`, and `node:20-slim` all leave `WorkingDir`
374    /// empty (2026-08-05), which is what makes [`require_workdir`] necessary.
375    pub fn al2023() -> Self {
376        Self {
377            name: "al2023-1".to_string(),
378            docker_ref: "public.ecr.aws/amazonlinux/amazonlinux:2023-minimal".to_string(),
379            working_dir: String::new(),
380        }
381    }
382
383    /// The base image a task Dockerfile pairs with: the managed base's `name` (so
384    /// `baseImageArn` is unchanged) and the Dockerfile's own first `FROM` as `docker_ref`
385    /// (IMAGE-4).
386    ///
387    /// # The pairing the other way round
388    ///
389    /// [`require_matching_from`] refuses a Dockerfile whose first `FROM` is not the base's
390    /// `docker_ref`. That is the right guard where this client derives the Dockerfile from
391    /// the base; a task Dockerfile chooses its own `FROM`, so the pairing has to run from the
392    /// Dockerfile to the base, and every harness wrote the same inversion by hand (#220).
393    /// Here the ref is taken whole — `--platform` and `AS` decoration dropped by
394    /// [`dockerfile_from_ref`], a digest pin kept — so the guard's comparison is the ref
395    /// against itself and it passes by construction.
396    ///
397    /// `working_dir` is empty: this cannot read the `FROM` image's `WorkingDir` without
398    /// pulling its manifest, and empty is what every measured public base declares (see
399    /// [`BaseImage::al2023`]). A task that relies on one sets `WORKDIR`, which
400    /// [`require_workdir`] reads from the Dockerfile.
401    ///
402    /// Refuses a Dockerfile with no `FROM`: there is no ref to take.
403    pub fn from_dockerfile(dockerfile: &str) -> Result<Self, Error> {
404        match dockerfile_from_ref(dockerfile) {
405            Some(docker_ref) => Ok(Self {
406                docker_ref: docker_ref.to_string(),
407                ..Self::al2023()
408            }),
409            None => Err(Error::invalid_arg(
410                "the Dockerfile has no FROM, so there is no image reference to pair the \
411                 managed base with. Derive the base from the Dockerfile the task builds \
412                 from."
413                    .to_string(),
414            )),
415        }
416    }
417
418    /// The `baseImageArn` for this base in `region`.
419    ///
420    /// # `microvm-image:<name>`, with a colon, and it is not just the managed base
421    ///
422    /// This was the only place in the repo building the colon form; the fakes and the
423    /// encoding test all used `microvm-image/<name>`, so the repo held two beliefs about the
424    /// shape of the identifier every image call takes. The model's `TaggableResource` pattern
425    /// admits only `(capacity-provider|network-connector|microvm-image):[a-zA-Z0-9-_]+`, and
426    /// a live read settled it: `ListMicrovmImages` in us-east-1 returns
427    /// `arn:aws:lambda:us-east-1:<account>:microvm-image:coding-agents-on-bedrock` for a
428    /// customer image, and `GetMicrovmImage` accepts exactly that (measured 2026-08-15).
429    ///
430    /// So the colon is right for **both** the managed base and a customer image; there is no
431    /// two-form rule, and this comment used to imply there was. The slash form fails as
432    /// `AccessDeniedException` rather than as a validation error, because IAM evaluates the
433    /// malformed ARN as a resource with no matching policy — a permissions message for a
434    /// resource that exists.
435    pub fn arn(&self, region: &crate::region::Region) -> String {
436        format!(
437            "arn:aws:lambda:{}:aws:microvm-image:{}",
438            region.as_str(),
439            self.name
440        )
441    }
442}
443
444impl Default for BaseImage {
445    fn default() -> Self {
446        Self::al2023()
447    }
448}
449
450/// Where the environment layer lives when the caller named no workdir of their own.
451///
452/// A constant rather than `/` because the install commands resolve everything against the
453/// current directory — `uv sync` writes `.venv` beside the manifest, `npm ci` writes
454/// `node_modules` — and the working tree synced at launch has to land in the same place
455/// for the layer to be *its* environment.
456pub const DEFAULT_PROJECT_WORKDIR: &str = "/project";
457
458/// A Dockerfile that makes the daemon the container `CMD`.
459///
460/// `ENTRYPOINT []` plus `CMD ["/agentd"]` is the deployment invariant the trust boundary
461/// rests on: it is what guarantees no task workload runs before the platform's run hook
462/// lands. It is also what makes an omitted `cwd` inherit the image `WORKDIR`, since the
463/// daemon's own cwd is the image's.
464///
465/// The `FROM` is derived from `base` rather than written here, so it cannot disagree with
466/// the `baseImageArn` the create call sends.
467///
468/// `project` bakes the environment layer (#74): the manifest+lockfile pair is copied into
469/// the working directory — `workdir` when given, [`DEFAULT_PROJECT_WORKDIR`] otherwise —
470/// and the ecosystem's [`Ecosystem::install_run_line`] installs from the lockfile. Without
471/// it the derived Dockerfile installs nothing, which was the measured state this closes:
472/// every launch then pays dependency installation inside the guest, the 31–48% of launch
473/// time `docs/STRATEGY.md` attributes to environment init.
474///
475/// The invariant is *unenforced*: a base image that starts its own background process
476/// before bootstrap breaks it, and enforcing that belongs to whoever builds the image
477/// (`docs/PROTOCOL.md`, "Trust boundary").
478pub fn default_dockerfile(
479    port: u16,
480    workdir: Option<&str>,
481    base: &BaseImage,
482    project: Option<Ecosystem>,
483) -> String {
484    format!(
485        "FROM {}\n{}",
486        base.docker_ref,
487        agentd_stanza(port, workdir, project)
488    )
489}
490
491/// The agentd stanza: every line [`default_dockerfile`] writes after its `FROM`, and every
492/// line [`wrap_dockerfile`] appends to a task Dockerfile (IMAGE-1).
493///
494/// # One source, and why it is this function rather than a constant
495///
496/// Two copies of these lines drift: a harness that carried the stanza as a string literal
497/// of its own (#220) had to track every change here by hand, and the day one side gained a
498/// line the other did not, the image a task built and the image the default build produced
499/// stopped agreeing about how the daemon starts. So both callers render this one function,
500/// and `wrapping_a_bare_from_is_the_default_dockerfile_minus_nothing` holds them equal:
501/// `wrap_dockerfile("FROM x\n")` is the default Dockerfile for a base whose ref is `x`.
502///
503/// The text is byte-for-byte what `default_dockerfile` emitted before the split, which is
504/// what keeps every content-addressed image name (`build --reuse`, `AgentVm::image_name`)
505/// derived from the default Dockerfile valid: the name hashes the Dockerfile text.
506fn agentd_stanza(port: u16, workdir: Option<&str>, project: Option<Ecosystem>) -> String {
507    let mut lines = vec![
508        "COPY agentd /agentd".to_string(),
509        "RUN chmod 0755 /agentd".to_string(),
510    ];
511    let workdir = match (workdir.filter(|dir| !dir.is_empty()), project) {
512        (Some(dir), _) => Some(dir),
513        // The layer needs a directory to live in even when the caller named none.
514        (None, Some(_)) => Some(DEFAULT_PROJECT_WORKDIR),
515        (None, None) => None,
516    };
517    if let Some(workdir) = workdir {
518        lines.push(format!("RUN mkdir -p {workdir}"));
519        lines.push(format!("WORKDIR {workdir}"));
520    }
521    if let Some(ecosystem) = project {
522        // Relative destination, resolving against the WORKDIR set above — the same
523        // directory the install command runs in.
524        lines.push(format!(
525            "COPY {} {} ./",
526            ecosystem.manifest_name(),
527            ecosystem.lockfile_name(),
528        ));
529        lines.push(ecosystem.install_run_line().to_string());
530    }
531    lines.extend([
532        format!("ENV AGENTD_PORT={port}"),
533        "ENV AGENTD_LOG=info".to_string(),
534        format!("EXPOSE {port}"),
535        "ENTRYPOINT []".to_string(),
536        r#"CMD ["/agentd"]"#.to_string(),
537        String::new(),
538    ]);
539    lines.join("\n")
540}
541
542/// What [`wrap_dockerfile`] needs besides the task text.
543#[derive(Clone, Debug, Eq, PartialEq)]
544pub struct WrapOptions {
545    /// The agent port the stanza's `ENV AGENTD_PORT` and `EXPOSE` name. It must be the port
546    /// the create call sends as `hooks.port` — [`ControlPlane::port`](super::ControlPlane::port)
547    /// — which [`require_matching_agentd_port`] checks at the create call.
548    pub port: u16,
549    /// A working directory for the stanza to create and set, exactly as
550    /// [`default_dockerfile`] writes one. One absolute path; `Some("")` reads as `None`, the
551    /// same way the default generator reads it.
552    pub workdir: Option<String>,
553    /// The caller relies on the image `WORKDIR` — an exec with no `cwd` runs there — so one
554    /// must be declared: by the task Dockerfile or by [`WrapOptions::workdir`]. Off by
555    /// default, because a task with no `WORKDIR` runs its commands in `/` under Docker too,
556    /// and a harness reproducing that has nothing to refuse.
557    pub inherit_workdir: bool,
558}
559
560impl Default for WrapOptions {
561    fn default() -> Self {
562        Self {
563            port: super::DEFAULT_AGENT_PORT,
564            workdir: None,
565            inherit_workdir: false,
566        }
567    }
568}
569
570/// A task Dockerfile with the agentd stanza appended: the one call a harness needs to go
571/// from the Dockerfile a task brings to one this client can build (#220).
572///
573/// The result is the task text verbatim, a newline if it lacked one, `USER root` when the
574/// task's last `USER` is anyone else, and then [`default_dockerfile`]'s stanza for
575/// `opts.port` and `opts.workdir` — the same function, so the two cannot drift (IMAGE-1).
576/// The stanza's `ENTRYPOINT []` and `CMD ["/agentd"]` are the result's last instructions,
577/// so whatever entrypoint, command, or port the task set, the daemon is the container's
578/// process and listens where the hooks are called (IMAGE-2). Pair it with
579/// [`BaseImage::from_dockerfile`] for the create call's `FROM` guard (IMAGE-4).
580///
581/// # `USER root`, only when the task changed user
582///
583/// The daemon demotes each exec to the user it names, which takes root; a task that ends on
584/// `USER app` would otherwise start the daemon as `app`. The line is written only when the
585/// last `USER` is not root, so a task that never changes user wraps to exactly the default
586/// stanza — writing it unconditionally would make the default Dockerfile and the wrap of a
587/// bare `FROM` two different texts (`crates/model/src/wrap.rs`, `AlwaysUserRoot`).
588///
589/// # What is refused, and why each is a refusal (IMAGE-3)
590///
591/// Each is a Dockerfile the build would accept and the guest would then fail on, one build
592/// cycle later and naming none of the cause:
593///
594/// * **No `FROM`.** Nothing to append to, and no base to derive.
595/// * **An unfinished last instruction.** A trailing line continuation — in the escape
596///   character the `# escape=` directive selects, across the blank and comment lines Docker
597///   skips inside one — joins the stanza's `COPY agentd /agentd` into the task's last
598///   instruction; an unterminated heredoc swallows the whole stanza as its body. Either way
599///   the image has no daemon and the build fails as a run-hook timeout.
600/// * **A keepalive at or over the client's stream idle timeout**, for the reason
601///   [`require_keepalive_under_idle_timeout`] gives.
602/// * **A port of 0, or a workdir that is not one absolute path.** A relative `WORKDIR`
603///   resolves against whatever the task left, whitespace splits `RUN mkdir -p` into several
604///   directories, and a line break writes an instruction the caller never saw.
605/// * **`inherit_workdir` with no `WORKDIR` anywhere**, for the reason [`require_workdir`]
606///   gives.
607///
608/// The scan reads instructions the way the Dockerfile parser does for these questions —
609/// escape directive, continuations, comments, heredoc bodies — and no further: it finds a
610/// Dockerfile that cannot take the stanza, it does not validate one.
611pub fn wrap_dockerfile(task: &str, opts: &WrapOptions) -> Result<String, Error> {
612    let scan = validate_wrap(task, opts)?;
613    let workdir = opts.workdir.as_deref().filter(|dir| !dir.is_empty());
614    let stanza = agentd_stanza(opts.port, workdir, None);
615    let mut wrapped = String::with_capacity(task.len() + stanza.len() + 16);
616    wrapped.push_str(task);
617    if !task.ends_with('\n') {
618        wrapped.push('\n');
619    }
620    if scan
621        .last_user
622        .as_deref()
623        .is_some_and(|user| !is_root_user(user))
624    {
625        wrapped.push_str("USER root\n");
626    }
627    wrapped.push_str(&stanza);
628    Ok(wrapped)
629}
630
631/// Preserve the final Dockerfile USER as the default identity for workload execs.
632///
633/// This is opt-in: [`wrap_dockerfile`] retains its historical root-default behavior.
634/// The builder, not the client, resolves final-stage inheritance, USER variables,
635/// names and numeric ids. A build-only agentd invocation records its effective uid
636/// and primary gid, then the stanza restores root and seals that record. No workload
637/// starts before readiness, and the daemon remains the image's CMD.
638///
639/// An explicit `AGENTD_DEFAULT_USER` in the image overrides the captured identity,
640/// including an empty value (which refuses implicit-user execs). A request's `user`
641/// overrides either default; its `group` overrides the default primary gid. The
642/// captured ids are fixed at build time; passwd identity variables are still
643/// resolved per request. Supplementary groups follow the daemon's existing policy
644/// and are cleared. The builder must support `COPY --chmod`.
645pub fn wrap_dockerfile_preserving_user(task: &str, opts: &WrapOptions) -> Result<String, Error> {
646    validate_wrap(task, opts)?;
647    let workdir = opts.workdir.as_deref().filter(|dir| !dir.is_empty());
648    let stanza = agentd_stanza(opts.port, workdir, None);
649    let mut wrapped = String::with_capacity(task.len() + stanza.len() + 256);
650    wrapped.push_str(task);
651    if !task.ends_with('\n') {
652        wrapped.push('\n');
653    }
654    // Reuse the required context asset as a writable placeholder. This works even
655    // for a numeric USER with no writable directory or shell in the final image.
656    wrapped.push_str(concat!(
657        "COPY --chmod=0755 agentd /agentd\n",
658        "COPY --chmod=0666 agentd /agentd-image-user.json\n",
659        "RUN [\"/agentd\", \"--capture-image-user\"]\n",
660        "USER 0:0\n",
661        "RUN [\"/agentd\", \"--seal-image-user\"]\n",
662        "ENV AGENTD_PRESERVE_IMAGE_USER=1\n",
663    ));
664    wrapped.push_str(&stanza);
665    Ok(wrapped)
666}
667
668fn validate_wrap(task: &str, opts: &WrapOptions) -> Result<Instructions, Error> {
669    if dockerfile_from_ref(task).is_none() {
670        return Err(Error::invalid_arg(
671            "the task Dockerfile has no FROM, so there is no image to append the agentd \
672             stanza to and no base image to pair with it. Wrap the Dockerfile the task \
673             builds from, or pass `FROM <image>` for a task that names only an image."
674                .to_string(),
675        ));
676    }
677    let scan = Instructions::scan(task);
678    if let Some(terminator) = scan.open_heredoc {
679        return Err(Error::invalid_arg(format!(
680            "the task Dockerfile ends inside a heredoc that is never terminated (no line \
681             {terminator:?} closes it), so every line appended after it — the whole agentd \
682             stanza — would become the heredoc's body. The image would build with no daemon \
683             in it and fail as a run-hook timeout. Terminate the heredoc."
684        )));
685    }
686    if scan.continued {
687        return Err(Error::invalid_arg(format!(
688            "the task Dockerfile's last instruction ends with a line continuation ({:?}), so \
689             the first line appended after it — the agentd stanza's `COPY agentd /agentd` — \
690             would be joined into that instruction instead of running. The image would build \
691             with no daemon in it and fail as a run-hook timeout. Finish the instruction, or \
692             drop the trailing {:?}.",
693            scan.escape, scan.escape,
694        )));
695    }
696    require_keepalive_under_idle_timeout(crate::session::exec::DEFAULT_STREAM_IDLE_TIMEOUT, task)?;
697    super::require_valid_port("port", opts.port)?;
698    let workdir = opts.workdir.as_deref().filter(|dir| !dir.is_empty());
699    if let Some(dir) = workdir
700        && (!dir.starts_with('/') || dir.chars().any(|c| c.is_whitespace() || c.is_control()))
701    {
702        return Err(Error::invalid_arg(format!(
703            "the workdir {dir:?} is not one absolute path. The stanza writes it as \
704             `RUN mkdir -p {dir}` and `WORKDIR {dir}`: a relative path resolves against \
705             whatever WORKDIR the task left, whitespace splits the mkdir into several \
706             directories, and a line break writes an instruction nobody reviewed. Pass an \
707             absolute path such as /workspace."
708        )));
709    }
710    if opts.inherit_workdir && workdir.is_none() && !dockerfile_declares_workdir(task) {
711        return Err(Error::invalid_arg(
712            "inherit_workdir was requested but the task Dockerfile sets no WORKDIR and no \
713             workdir option was given, so there is nothing to inherit: every exec with no cwd \
714             would run in `/`, and every relative path in it would resolve there. Pass a \
715             workdir, or set WORKDIR in the task Dockerfile."
716                .to_string(),
717        ));
718    }
719
720    Ok(scan)
721}
722
723/// Whether a `USER` value names root: `root` or `0`, with no group or a root group.
724///
725/// Anything else is not root, including a value built from a variable — the scan cannot
726/// expand `${TASK_USER}`, and restoring root for a value that turns out to be root costs one
727/// redundant line.
728fn is_root_user(value: &str) -> bool {
729    let is_root = |part: &str| part == "root" || part == "0";
730    match value.split_once(':') {
731        Some((user, group)) => is_root(user) && is_root(group),
732        None => is_root(value),
733    }
734}
735
736/// Whether any line of `dockerfile` is a `WORKDIR` with an argument.
737fn dockerfile_declares_workdir(dockerfile: &str) -> bool {
738    dockerfile.lines().any(|line| {
739        let mut words = line.split_whitespace();
740        words
741            .next()
742            .is_some_and(|first| first.eq_ignore_ascii_case("WORKDIR"))
743            && words.next().is_some()
744    })
745}
746
747/// What [`wrap_dockerfile`] needs to know about how a Dockerfile's instructions end.
748struct Instructions {
749    /// The escape character: `\` unless an `# escape=` directive chose a backtick.
750    escape: char,
751    /// The text ends inside a line continuation.
752    continued: bool,
753    /// The terminator of a heredoc the text never closes.
754    open_heredoc: Option<String>,
755    /// The value of the last `USER` instruction.
756    last_user: Option<String>,
757}
758
759impl Instructions {
760    /// Reads the parser directives, then every logical instruction: continuation lines
761    /// joined, blank and comment lines skipped (inside a continuation too, as the parser
762    /// does), heredoc bodies consumed up to their terminators.
763    fn scan(dockerfile: &str) -> Self {
764        let escape = escape_directive(dockerfile);
765        let mut heredocs: std::collections::VecDeque<(String, bool)> = Default::default();
766        let mut pending = String::new();
767        let mut continued = false;
768        let mut last_user = None;
769        for line in dockerfile.lines() {
770            if let Some((terminator, strip_tabs)) = heredocs.front() {
771                let candidate = if *strip_tabs {
772                    line.trim_start_matches('\t')
773                } else {
774                    line
775                };
776                if candidate.trim_end_matches('\r') == terminator {
777                    heredocs.pop_front();
778                }
779                continue;
780            }
781            let trimmed = line.trim();
782            if trimmed.is_empty() || trimmed.starts_with('#') {
783                continue;
784            }
785            let body = line.trim_end();
786            if let Some(joined) = body.strip_suffix(escape) {
787                pending.push_str(joined);
788                pending.push(' ');
789                continued = true;
790                continue;
791            }
792            continued = false;
793            pending.push_str(body);
794            let instruction = std::mem::take(&mut pending);
795            let mut words = instruction.split_whitespace();
796            let Some(keyword) = words.next() else {
797                continue;
798            };
799            if keyword.eq_ignore_ascii_case("USER") {
800                last_user = words.next().map(str::to_string);
801            } else if ["RUN", "COPY", "ADD"]
802                .iter()
803                .any(|name| keyword.eq_ignore_ascii_case(name))
804            {
805                heredocs.extend(words.filter_map(heredoc_marker));
806            }
807        }
808        Self {
809            escape,
810            continued,
811            open_heredoc: heredocs.pop_front().map(|(terminator, _)| terminator),
812            last_user,
813        }
814    }
815}
816
817/// The escape character a Dockerfile's `# escape=` parser directive selects, or `\`.
818///
819/// Directives are only read at the very top: the first line that is not one — an
820/// instruction, a blank line, or an ordinary comment — ends them.
821fn escape_directive(dockerfile: &str) -> char {
822    for line in dockerfile.lines() {
823        let Some(directive) = line.trim().strip_prefix('#') else {
824            break;
825        };
826        let Some((key, value)) = directive.split_once('=') else {
827            break;
828        };
829        let key = key.trim().to_ascii_lowercase();
830        if key == "escape" {
831            return match value.trim() {
832                "`" => '`',
833                _ => '\\',
834            };
835        }
836        if !["syntax", "check"].contains(&key.as_str()) {
837            break;
838        }
839    }
840    '\\'
841}
842
843/// The terminator a heredoc marker word opens, and whether it strips leading tabs (`<<-`).
844///
845/// `<<EOF`, `<<-EOF`, `<<"EOF"`, `<<'EOF'`; not the here-string `<<<`, and not a bare `<<`.
846fn heredoc_marker(word: &str) -> Option<(String, bool)> {
847    let rest = word.strip_prefix("<<")?;
848    if rest.starts_with('<') {
849        return None;
850    }
851    let (rest, strip_tabs) = match rest.strip_prefix('-') {
852        Some(rest) => (rest, true),
853        None => (rest, false),
854    };
855    let name = rest
856        .strip_prefix('"')
857        .and_then(|name| name.strip_suffix('"'))
858        .or_else(|| {
859            rest.strip_prefix('\'')
860                .and_then(|name| name.strip_suffix('\''))
861        })
862        .unwrap_or(rest);
863    let valid = name
864        .chars()
865        .next()
866        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
867        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
868    valid.then(|| (name.to_string(), strip_tabs))
869}
870
871/// The image ref in a Dockerfile's first `FROM`, or `None` when it has none.
872///
873/// Deliberately loose on whitespace and case, and it ignores `--platform=` and `AS name`
874/// decoration, because the check exists to catch a base that disagrees rather than to
875/// validate Dockerfile syntax.
876///
877/// Split-and-scan rather than a regex: the pattern is "first token after FROM on a line
878/// whose first word is FROM", which `split_whitespace` states more directly than a
879/// pattern string would. (`regex-lite` is available if this ever grows.)
880pub fn dockerfile_from_ref(dockerfile: &str) -> Option<&str> {
881    for line in dockerfile.lines() {
882        let mut words = line.split_whitespace();
883        let Some(first) = words.next() else { continue };
884        if !first.eq_ignore_ascii_case("FROM") {
885            continue;
886        }
887        // Skip flag decoration such as `--platform=linux/arm64`.
888        return words.find(|word| !word.starts_with("--"));
889    }
890    None
891}
892
893/// Rejects working-directory inheritance when nothing declares one.
894///
895/// Measured 2026-08-05: `al2023-minimal`, `python:3.12-slim`, and `node:20-slim` all leave
896/// `WorkingDir` empty, so "inherit the image WORKDIR" inherits `/` and every relative path
897/// in the caller's commands resolves somewhere they did not mean.
898///
899/// Rejected rather than warned because the symptom appears in the **guest, one build cycle
900/// later**, as commands running in the wrong directory rather than as anything about
901/// `WORKDIR`.
902pub fn require_workdir(base: &BaseImage, dockerfile: Option<&str>) -> Result<(), Error> {
903    if !base.working_dir.is_empty() {
904        return Ok(());
905    }
906    let declares_workdir = dockerfile.is_some_and(|text| {
907        text.lines().any(|line| {
908            let mut words = line.split_whitespace();
909            words
910                .next()
911                .is_some_and(|first| first.eq_ignore_ascii_case("WORKDIR"))
912                && words.next().is_some()
913        })
914    });
915    if declares_workdir {
916        return Ok(());
917    }
918    Err(Error::invalid_arg(format!(
919        "inherit_workdir was requested but base image {:?} declares no WorkingDir and the \
920         Dockerfile sets none. Most public ARM64 base images leave it empty \
921         (docs/PLATFORM.md, 'Most public ARM64 base images have no WORKDIR'), so there is \
922         nothing to inherit and every relative path would resolve against `/`. Pass a workdir \
923         to default_dockerfile, or set WORKDIR in your own Dockerfile.",
924        base.name
925    )))
926}
927
928/// The port in a Dockerfile's last `ENV AGENTD_PORT=`, or `None` when it sets none.
929///
930/// Last rather than first: a later `ENV` of the same name wins at build time, so the last
931/// one is what the daemon reads. Accepts `ENV AGENTD_PORT=9000` and the legacy
932/// `ENV AGENTD_PORT 9000` spelling, since both set the variable and a guard that only
933/// understands one form passes the file it cannot parse.
934///
935/// Split-and-scan for the same reason [`dockerfile_from_ref`] is: `split_whitespace`
936/// states the pattern more directly than a regex string would here.
937pub fn dockerfile_agentd_port(dockerfile: &str) -> Option<u16> {
938    let mut found = None;
939    for line in dockerfile.lines() {
940        let mut words = line.split_whitespace();
941        let Some(first) = words.next() else { continue };
942        if !first.eq_ignore_ascii_case("ENV") {
943            continue;
944        }
945        let Some(assignment) = words.next() else {
946            continue;
947        };
948        let value = match assignment.split_once('=') {
949            Some(("AGENTD_PORT", value)) => value,
950            Some(_) => continue,
951            // `ENV AGENTD_PORT 9000`: the value is the next word.
952            None if assignment == "AGENTD_PORT" => match words.next() {
953                Some(value) => value,
954                None => continue,
955            },
956            None => continue,
957        };
958        // An unparseable value is not this guard's business: the daemon keeps its default
959        // for one (`crates/agentd/src/config.rs:118`), so there is no disagreement to report.
960        if let Ok(port) = value.parse() {
961            found = Some(port);
962        }
963    }
964    found
965}
966
967/// Rejects a Dockerfile whose `AGENTD_PORT` disagrees with the port the create call sends
968/// as `hooks.port`.
969///
970/// The two are set independently — `hooks.port` comes from `ControlPlane::port`, the
971/// variable from the caller's own Dockerfile — and the platform calls its build-time
972/// `ready`/`validate` hooks on the port in the create call. A guest listening elsewhere
973/// answers nothing, so the build fails.
974///
975/// Rejected rather than warned because the failure points away from its cause: the docker
976/// build succeeds, the log group holds a clean build *and* the daemon's own "agentd
977/// listening" line, and the image still lands in `CREATE_FAILED`. Neither
978/// `GetMicrovmImage` nor the build log names the port — only
979/// `GetMicrovmImageVersion`'s `hooks.port` does, compared by hand against the Dockerfile.
980///
981/// A Dockerfile that sets no `AGENTD_PORT` is checked against
982/// [`DEFAULT_AGENT_PORT`](crate::control::DEFAULT_AGENT_PORT) rather than passed, because
983/// silence is not neutral: `Config::from_env` keeps its own default for an unset variable
984/// (`crates/agentd/src/config.rs:118`, default `crates/agentd/src/config.rs:84`), so the guest listens on
985/// 9000 whether or not the Dockerfile mentions a port. Against a client that changed its
986/// port, the absent variable produces exactly the measured failure — and produces it for a
987/// caller who never typed a port anywhere, which is the harder version to diagnose.
988pub fn require_matching_agentd_port(port: u16, dockerfile: &str) -> Result<(), Error> {
989    // An unparseable value lands here too, and belongs here: the daemon warns and keeps the
990    // same default (`crates/agentd/src/config.rs:174-179`), so both spellings of "the Dockerfile
991    // named no usable port" have the same consequence in the guest.
992    let Some(found) = dockerfile_agentd_port(dockerfile) else {
993        if port == super::DEFAULT_AGENT_PORT {
994            return Ok(());
995        }
996        return Err(Error::invalid_arg(format!(
997            "this client sends hooks.port={port} but the Dockerfile sets no usable \
998             AGENTD_PORT, so the daemon will listen on its own default of {default}. These \
999             must agree: the platform calls the build-time ready/validate hooks on the port \
1000             in the create call, and a daemon listening on {default} answers none of them — \
1001             the docker build succeeds, the daemon logs that it is listening, and the image \
1002             still fails with CREATE_FAILED naming no port. Add ENV AGENTD_PORT={port} to \
1003             the Dockerfile, or build it with default_dockerfile, which derives the value \
1004             from the same port.",
1005            default = super::DEFAULT_AGENT_PORT,
1006        )));
1007    };
1008    if found == port {
1009        return Ok(());
1010    }
1011    Err(Error::invalid_arg(format!(
1012        "the Dockerfile sets ENV AGENTD_PORT={found} but this client sends hooks.port={port}. \
1013         These must agree: the platform calls the build-time ready/validate hooks on the port \
1014         in the create call, and a daemon listening on {found} answers none of them — the \
1015         docker build succeeds, the daemon logs that it is listening, and the image still \
1016         fails with CREATE_FAILED naming no port. Set ENV AGENTD_PORT={port} in the \
1017         Dockerfile, or build it with default_dockerfile, which derives the value from the \
1018         same port."
1019    )))
1020}
1021
1022/// The seconds in a Dockerfile's last `ENV AGENTD_SSE_KEEPALIVE_SECS=`, or `None` when it
1023/// sets none.
1024///
1025/// Same shape and same reasoning as [`dockerfile_agentd_port`]: last assignment wins, both
1026/// `ENV` spellings, and an unparseable value reads as absent because the daemon warns and
1027/// keeps its default for one (`crates/agentd/src/config.rs:174-179`).
1028pub fn dockerfile_env_u64(dockerfile: &str, key: &str) -> Option<u64> {
1029    let mut found = None;
1030    for line in dockerfile.lines() {
1031        let mut words = line.split_whitespace();
1032        let Some(first) = words.next() else { continue };
1033        if !first.eq_ignore_ascii_case("ENV") {
1034            continue;
1035        }
1036        let Some(assignment) = words.next() else {
1037            continue;
1038        };
1039        let value = match assignment.split_once('=') {
1040            Some((name, value)) if name == key => value,
1041            Some(_) => continue,
1042            None if assignment == key => match words.next() {
1043                Some(value) => value,
1044                None => continue,
1045            },
1046            None => continue,
1047        };
1048        if let Ok(parsed) = value.parse() {
1049            found = Some(parsed);
1050        }
1051    }
1052    found
1053}
1054
1055/// Rejects a Dockerfile whose `AGENTD_SSE_KEEPALIVE_SECS` is not shorter than the client's
1056/// stream idle timeout.
1057///
1058/// The fourth pair of this shape, found by sweeping for the other three. The daemon's SSE
1059/// keepalive interval and the client's tolerance for silence are set in different
1060/// repositories of truth — the interval in the caller's Dockerfile
1061/// (`crates/agentd/src/config.rs:139`, default 15s at `:95`), the tolerance in
1062/// [`DEFAULT_STREAM_IDLE_TIMEOUT`](crate::session::exec::DEFAULT_STREAM_IDLE_TIMEOUT),
1063/// which is 60s *because* it is four times that 15. Raise the interval past the tolerance
1064/// and every attached stream treats a healthy connection as dead, reconnects
1065/// `max_reconnects` times, and fails.
1066///
1067/// The failure names both numbers and misattributes one of them: the client reports that the
1068/// stream "went silent for 60s, longer than the keepalive interval"
1069/// (`crates/microvms-edges/src/session/http.rs:223-227`), where 60 is its own timeout and the
1070/// keepalive interval is the number it does not know. So a reader is told the keepalive was
1071/// exceeded by a message that prints the wrong value for it, one build cycle after the
1072/// Dockerfile that caused it.
1073///
1074/// Equality is refused, not just excess: an interval exactly equal to the timeout races.
1075pub fn require_keepalive_under_idle_timeout(
1076    idle_timeout: Duration,
1077    dockerfile: &str,
1078) -> Result<(), Error> {
1079    let Some(secs) = dockerfile_env_u64(dockerfile, "AGENTD_SSE_KEEPALIVE_SECS") else {
1080        // Absent is safe here, unlike the port: the daemon's default of 15s is already
1081        // under every idle timeout this client will use, and a client that shortens its
1082        // timeout below 15s is not something a Dockerfile can be blamed for.
1083        return Ok(());
1084    };
1085    if secs < idle_timeout.as_secs() {
1086        return Ok(());
1087    }
1088    Err(Error::invalid_arg(format!(
1089        "the Dockerfile sets ENV AGENTD_SSE_KEEPALIVE_SECS={secs} but this client treats a \
1090         stream as dead after {timeout}s of silence. The keepalive must be shorter: the \
1091         daemon sends nothing between events except that keepalive, so an interval of \
1092         {secs}s makes a healthy stream look dead, and every attach reconnects until it \
1093         gives up. The error it raises then reports the client's own {timeout}s as though it \
1094         were the keepalive interval, so it names neither the Dockerfile nor {secs}. Leave \
1095         the variable unset for the daemon's 15s default, or keep it under {timeout}.",
1096        timeout = idle_timeout.as_secs(),
1097    )))
1098}
1099
1100/// The value of a Dockerfile's last `ENTRYPOINT`, or `None` when it sets none.
1101///
1102/// Last rather than first for the reason [`dockerfile_agentd_port`] gives: a later
1103/// instruction of the same name wins at build time, so the last one is what the container
1104/// runs. The value is the raw rest of the line — this scan finds a disagreement, it does
1105/// not parse Dockerfile syntax.
1106pub fn dockerfile_entrypoint(dockerfile: &str) -> Option<&str> {
1107    last_instruction_value(dockerfile, "ENTRYPOINT")
1108}
1109
1110/// The value of a Dockerfile's last `CMD`, or `None` when it sets none.
1111pub fn dockerfile_cmd(dockerfile: &str) -> Option<&str> {
1112    last_instruction_value(dockerfile, "CMD")
1113}
1114
1115/// The rest of the last line whose first word is `keyword`, trimmed, or `None`.
1116fn last_instruction_value<'a>(dockerfile: &'a str, keyword: &str) -> Option<&'a str> {
1117    let mut found = None;
1118    for line in dockerfile.lines() {
1119        let trimmed = line.trim_start();
1120        let Some(first) = trimmed.split_whitespace().next() else {
1121            continue;
1122        };
1123        if first.eq_ignore_ascii_case(keyword) {
1124            found = Some(trimmed[first.len()..].trim());
1125        }
1126    }
1127    found
1128}
1129
1130/// Whether an instruction value is the empty exec form — `[]`, with any spacing.
1131fn is_empty_exec_form(value: &str) -> bool {
1132    let mut meaningful = value.chars().filter(|c| !c.is_whitespace());
1133    meaningful.next() == Some('[') && meaningful.next() == Some(']') && meaningful.next().is_none()
1134}
1135
1136/// Rejects a Dockerfile whose image would never run the daemon: no `CMD`, or an
1137/// `ENTRYPOINT` that swallows it.
1138///
1139/// The artifact unconditionally carries the daemon as entry `agentd` ([`build_artifact`]),
1140/// and the deployment invariant is `ENTRYPOINT []` plus `CMD ["/agentd"]` — see
1141/// [`default_dockerfile`]. A caller Dockerfile with no `CMD` runs the base's own default
1142/// instead, and a non-empty `ENTRYPOINT` turns any `CMD` into that entrypoint's arguments
1143/// rather than the process. Either way the daemon never starts, the build-time
1144/// `ready`/`validate` hooks go unanswered, and the image lands in `CREATE_FAILED` — or the
1145/// launch dies as a run-hook timeout — with nothing naming `CMD`, `ENTRYPOINT`, or the
1146/// artifact entry.
1147///
1148/// Weak-form on purpose: it does **not** check that the `CMD` names a path anything was
1149/// copied to. That would be Dockerfile interpretation rather than agreement checking, and
1150/// the two mistakes people actually make are the two refused here. The unenforceable half —
1151/// a base image that starts its own background process before bootstrap — stays with
1152/// whoever builds the image (`docs/PROTOCOL.md`, "Trust boundary").
1153pub fn require_daemon_cmd(dockerfile: &str) -> Result<(), Error> {
1154    if let Some(entrypoint) = dockerfile_entrypoint(dockerfile)
1155        && !is_empty_exec_form(entrypoint)
1156    {
1157        return Err(Error::invalid_arg(format!(
1158            "the Dockerfile sets ENTRYPOINT {entrypoint}, which makes any CMD its arguments \
1159             rather than the container's process — so the daemon this client uploads never \
1160             starts. The build succeeds anyway: the ready/validate hooks just go unanswered \
1161             and the image fails as CREATE_FAILED, or the launch dies as a run-hook timeout, \
1162             and neither symptom names ENTRYPOINT. Set `ENTRYPOINT []` alongside \
1163             `CMD [\"/agentd\"]`, or build with default_dockerfile, which sets both."
1164        )));
1165    }
1166    match dockerfile_cmd(dockerfile) {
1167        Some(cmd) if !cmd.is_empty() && !is_empty_exec_form(cmd) => Ok(()),
1168        _ => Err(Error::invalid_arg(
1169            "the Dockerfile has no CMD, so the container runs the base image's default \
1170             process and the daemon this client uploads never starts. The build succeeds \
1171             anyway: the ready/validate hooks just go unanswered and the image fails as \
1172             CREATE_FAILED, or the launch dies as a run-hook timeout, and neither symptom \
1173             names CMD. Add `ENTRYPOINT []` and `CMD [\"/agentd\"]`, or build with \
1174             default_dockerfile, which sets both."
1175                .to_string(),
1176        )),
1177    }
1178}
1179
1180/// Rejects a caller Dockerfile that never mentions the lockfile the request carries.
1181///
1182/// The project files enter the artifact unconditionally once the request holds them, so a
1183/// custom Dockerfile that ignores them builds cleanly and produces an image with **no
1184/// environment layer** — and the symptom appears at launch, as every dependency
1185/// installing inside the guest, with nothing anywhere naming the `COPY` that was never
1186/// written. That is the silent-degradation shape: the caller asked for the layer, paid
1187/// the build, and got an image indistinguishable from one that never asked.
1188///
1189/// Weak-form on purpose, like [`require_daemon_cmd`]: a substring test for the lockfile's
1190/// name rather than parsing `COPY` syntax, because the check exists to catch a Dockerfile
1191/// that plainly ignores the files, not to validate how it consumes them.
1192pub fn require_project_install(project: &ProjectFiles, dockerfile: &str) -> Result<(), Error> {
1193    let lockfile = project.ecosystem.lockfile_name();
1194    if dockerfile.contains(lockfile) {
1195        return Ok(());
1196    }
1197    Err(Error::invalid_arg(format!(
1198        "the request carries project files ({lockfile} and {manifest}) but the Dockerfile \
1199         never mentions {lockfile}, so the image would bake no environment layer: the build \
1200         succeeds, and every launch still installs dependencies inside the guest with \
1201         nothing naming the COPY that was never written. Copy the pair and install from \
1202         the lockfile ({install}), or build with default_dockerfile, which derives both \
1203         lines — or drop the project files if the layer is not wanted.",
1204        manifest = project.ecosystem.manifest_name(),
1205        install = match project.ecosystem {
1206            Ecosystem::Uv => "uv sync --locked",
1207            Ecosystem::Npm => "npm ci",
1208            Ecosystem::Cargo => "cargo fetch --locked",
1209        },
1210    )))
1211}
1212
1213/// Rejects a Dockerfile whose `FROM` is not the selected base image.
1214///
1215/// The build runs the Dockerfile *on top of* the base named in `baseImageArn`, so the two
1216/// disagreeing produces an image built from something other than the platform base whose
1217/// behaviour every `docs/PLATFORM.md` measurement describes — and nothing in the result
1218/// says so.
1219pub fn require_matching_from(base: &BaseImage, dockerfile: &str) -> Result<(), Error> {
1220    let Some(found) = dockerfile_from_ref(dockerfile) else {
1221        // No FROM at all is not this check's business: the build will say so, and a
1222        // Dockerfile validator is not what this is.
1223        return Ok(());
1224    };
1225    if found == base.docker_ref {
1226        return Ok(());
1227    }
1228    // The digest-pinned spelling of the same ref: `<docker_ref>@sha256:<64 hex>`. A digest
1229    // names one specific manifest of the ref this check already accepts, so it is a stricter
1230    // statement of agreement rather than a disagreement — a supply-chain-conscious caller
1231    // pins exactly this way, and refusing it would force them to un-pin to pass. The tag
1232    // must still be present and identical: `alpine@sha256:...` against a docker_ref of
1233    // `alpine:3` is a different claim and stays refused.
1234    if let Some(digest) = found
1235        .strip_prefix(base.docker_ref.as_str())
1236        .and_then(|rest| rest.strip_prefix("@sha256:"))
1237        && digest.len() == 64
1238        && digest.bytes().all(|b| b.is_ascii_hexdigit())
1239    {
1240        return Ok(());
1241    }
1242    Err(Error::invalid_arg(format!(
1243        "the Dockerfile's FROM is {found:?} but base image {:?} pairs with {:?}. These must \
1244         agree: baseImageArn and the FROM select the same base, and a mismatch builds against \
1245         a base none of the measured platform behaviour applies to. Use default_dockerfile \
1246         with this base, or pass a BaseImage whose docker_ref matches.",
1247        base.name, base.docker_ref
1248    )))
1249}
1250
1251#[cfg(test)]
1252mod tests {
1253    use super::*;
1254    use crate::testing::aarch64_daemon;
1255
1256    const DEFAULT_AGENT_PORT_FOR_TESTS: u16 = crate::control::DEFAULT_AGENT_PORT;
1257
1258    /// The archive holds exactly the two entries the build expects, named as the build
1259    /// looks for them.
1260    #[test]
1261    fn the_artifact_holds_a_dockerfile_and_the_daemon() {
1262        let bytes =
1263            build_artifact(&aarch64_daemon(b"fake daemon"), "FROM scratch\n", None).expect("zips");
1264        let mut archive =
1265            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1266
1267        let mut names: Vec<String> = (0..archive.len())
1268            .map(|index| {
1269                archive
1270                    .by_index(index)
1271                    .expect("entry")
1272                    .name()
1273                    .expect("a name")
1274                    .into_owned()
1275            })
1276            .collect();
1277        names.sort();
1278        assert_eq!(names, ["Dockerfile", "agentd"]);
1279    }
1280
1281    /// **BIND-20 where the daemon enters an artifact (#257).** An x86_64 ELF, a script and no bytes
1282    /// at all are each refused as a precondition naming what the bytes are, so the bindings'
1283    /// two-step path (`build_artifact`, then the caller's own upload) never uploads one.
1284    ///
1285    /// **Falsification**: drop the `require_aarch64` call from `build_artifact_with_context`
1286    /// and all three zip.
1287    #[test]
1288    fn an_artifact_refuses_a_daemon_that_is_not_an_aarch64_elf() {
1289        for (binary, why) in [
1290            (crate::testing::elf_daemon(0x3E, b"x86"), "ELF machine 0x3e"),
1291            (b"#!/bin/sh\n".to_vec(), "not an ELF binary"),
1292            (Vec::new(), "not an ELF binary"),
1293        ] {
1294            let error = build_artifact(&binary, "FROM scratch\n", None).expect_err(why);
1295            assert_eq!(error.kind(), ErrorKind::Precondition, "{error}");
1296            assert!(error.to_string().contains(why), "{error}");
1297        }
1298    }
1299
1300    /// The daemon entry carries mode 0755, and the Dockerfile entry does not have to.
1301    ///
1302    /// Read back out of the archive rather than asserted on the constant, because the
1303    /// constant being right and the zip entry carrying it are two different facts — and it
1304    /// is the second one that turns into a run-hook timeout.
1305    ///
1306    /// The permission bits are masked out of the returned mode: `zip` reports the whole
1307    /// Unix mode, so the entry reads as `0o100755` — `S_IFREG | 0o755`. Comparing the
1308    /// unmasked value against `0o755` fails while the archive is perfectly correct, which
1309    /// is a test that would have sent someone to debug the writer.
1310    #[test]
1311    fn the_daemon_entry_carries_the_execute_bit() {
1312        let bytes =
1313            build_artifact(&aarch64_daemon(b"binary"), "FROM scratch\n", None).expect("zips");
1314        let mut archive =
1315            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1316        let mode = archive
1317            .by_name("agentd")
1318            .expect("the daemon entry")
1319            .unix_mode()
1320            .expect("a mode was recorded");
1321        assert_eq!(
1322            mode & 0o777,
1323            AGENTD_MODE,
1324            "a non-executable binary surfaces as a run-hook timeout, not a permission error \
1325             (mode was {mode:o})"
1326        );
1327        assert!(
1328            mode & 0o111 != 0,
1329            "the execute bit is the whole point: {mode:o}"
1330        );
1331    }
1332
1333    /// The bytes round-trip. A zip that holds a truncated or re-encoded binary produces an
1334    /// image whose CMD fails for a reason no message names.
1335    #[test]
1336    fn the_daemon_bytes_survive_the_round_trip() {
1337        use std::io::Read as _;
1338
1339        // Deliberately includes a NUL and a high byte, which is what a real ELF has and
1340        // what a text-mode write would mangle.
1341        let binary = aarch64_daemon(&(0u8..=255).cycle().take(4096).collect::<Vec<u8>>());
1342        let bytes = build_artifact(&binary, "FROM scratch\n", None).expect("zips");
1343        let mut archive =
1344            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1345        let mut read = Vec::new();
1346        archive
1347            .by_name("agentd")
1348            .expect("entry")
1349            .read_to_end(&mut read)
1350            .expect("reads");
1351        assert_eq!(read, binary);
1352    }
1353
1354    /// **AC-2-3, the byte-scan guard.** The agent token must not appear anywhere in the
1355    /// artifact's raw bytes — including the project-file entries #74 added.
1356    ///
1357    /// A byte scan rather than an API review, because the leak this guards against is a
1358    /// *value* turning up somewhere — in the Dockerfile as an `ENV`, in a baked config
1359    /// file, in a stray argument — not a parameter being declared. Scanning the compressed
1360    /// bytes and the decompressed entries both, since deflate would hide a literal from a
1361    /// naive scan of the archive. The artifact under scan carries a full project-file
1362    /// pair, and the entry count is asserted so the scan cannot silently sweep fewer
1363    /// members than the artifact holds.
1364    ///
1365    /// **Falsification** — add the token to the Dockerfile (`ENV AGENT_TOKEN=…`, the
1366    /// plausible mistake) and the decompressed scan fails. Re-run for the #74 members
1367    /// (2026-08-31): append the token to the lockfile entry inside `build_artifact` and
1368    /// the per-entry scan fails naming `uv.lock`; it was restored.
1369    #[test]
1370    fn the_artifact_never_carries_the_agent_token() {
1371        use std::io::Read as _;
1372
1373        let token = "s3cr3t-agent-token-do-not-bake-me";
1374        let dockerfile = default_dockerfile(9000, Some("/opt/work"), &BaseImage::al2023(), None);
1375        assert!(
1376            !dockerfile.contains(token),
1377            "the default Dockerfile must not mention a token"
1378        );
1379
1380        let project = ProjectFiles {
1381            ecosystem: Ecosystem::Uv,
1382            manifest: b"[project]\nname = \"demo\"\n".to_vec(),
1383            lockfile: b"version = 1\n".to_vec(),
1384        };
1385        let bytes =
1386            build_artifact(&aarch64_daemon(b"binary"), &dockerfile, Some(&project)).expect("zips");
1387        assert!(
1388            !bytes
1389                .windows(token.len())
1390                .any(|window| window == token.as_bytes()),
1391            "the token appears in the artifact's raw bytes"
1392        );
1393
1394        let mut archive =
1395            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1396        assert_eq!(
1397            archive.len(),
1398            4,
1399            "the scan below must sweep every member this artifact can hold"
1400        );
1401        for index in 0..archive.len() {
1402            let mut entry = archive.by_index(index).expect("entry");
1403            let name = entry.name().expect("a name").into_owned();
1404            let mut content = Vec::new();
1405            entry.read_to_end(&mut content).expect("reads");
1406            assert!(
1407                !content
1408                    .windows(token.len())
1409                    .any(|window| window == token.as_bytes()),
1410                "the token appears inside {name} — the image snapshot is shared by every VM \
1411                 launched from it, so a token here is a token shared with every VM"
1412            );
1413        }
1414    }
1415
1416    /// **#74, the build-context half.** A project's manifest and lockfile enter the
1417    /// archive under their ecosystem's fixed names, at the root beside the Dockerfile —
1418    /// the build context root, where the generated `COPY` finds them — and their bytes
1419    /// survive the round trip.
1420    #[test]
1421    fn project_files_enter_the_artifact_under_their_ecosystem_names() {
1422        use std::io::Read as _;
1423
1424        for (ecosystem, manifest_name, lockfile_name) in [
1425            (Ecosystem::Uv, "pyproject.toml", "uv.lock"),
1426            (Ecosystem::Npm, "package.json", "package-lock.json"),
1427            (Ecosystem::Cargo, "Cargo.toml", "Cargo.lock"),
1428        ] {
1429            let project = ProjectFiles {
1430                ecosystem,
1431                manifest: b"manifest-bytes".to_vec(),
1432                lockfile: b"lockfile-bytes".to_vec(),
1433            };
1434            let bytes =
1435                build_artifact(&aarch64_daemon(b"binary"), "FROM scratch\n", Some(&project))
1436                    .expect("zips");
1437            let mut archive =
1438                zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1439
1440            let mut names: Vec<String> = (0..archive.len())
1441                .map(|index| {
1442                    archive
1443                        .by_index(index)
1444                        .expect("entry")
1445                        .name()
1446                        .expect("a name")
1447                        .into_owned()
1448                })
1449                .collect();
1450            names.sort();
1451            let mut expected = vec![
1452                "Dockerfile".to_string(),
1453                "agentd".to_string(),
1454                manifest_name.to_string(),
1455                lockfile_name.to_string(),
1456            ];
1457            expected.sort();
1458            assert_eq!(names, expected, "{ecosystem:?}");
1459
1460            let mut lockfile = Vec::new();
1461            archive
1462                .by_name(lockfile_name)
1463                .expect("the lockfile entry")
1464                .read_to_end(&mut lockfile)
1465                .expect("reads");
1466            assert_eq!(lockfile, b"lockfile-bytes", "{ecosystem:?}");
1467        }
1468    }
1469
1470    /// **#74's TRAP-5 design guard, the compile surface.** [`ProjectFiles`] has no field
1471    /// that could carry an entry *name* — the names come from the [`Ecosystem`] variant —
1472    /// so a caller cannot put `.env` or a credentials file into the shared snapshot
1473    /// through this type. Asserted by destructuring, the same shape as TRAP-1's
1474    /// `no_request_type_carries_a_caller_supplied_client_token`: a `name`/`path` field
1475    /// added later fails to compile this test.
1476    #[test]
1477    fn project_files_carry_no_caller_named_entry() {
1478        let ProjectFiles {
1479            ecosystem: _,
1480            manifest: _,
1481            lockfile: _,
1482        } = ProjectFiles {
1483            ecosystem: Ecosystem::Npm,
1484            manifest: Vec::new(),
1485            lockfile: Vec::new(),
1486        };
1487    }
1488
1489    /// The content hash is a pure function of the two inputs: equal inputs agree, either
1490    /// input changing changes it, and the boundary between the two inputs is part of the
1491    /// identity.
1492    ///
1493    /// The boundary case is the one worth spelling out: without length prefixes,
1494    /// `("ab", "c")` and `("a", "bc")` hash the same concatenation — and a Dockerfile
1495    /// edit could then collide with a binary edit, serving a stale image for changed
1496    /// inputs, which is the exact hazard the hash exists to close.
1497    #[test]
1498    fn the_content_hash_follows_the_inputs_and_only_the_inputs() {
1499        let hash = artifact_content_hash(b"binary-bytes", "FROM scratch\n", None);
1500        assert_eq!(
1501            hash,
1502            artifact_content_hash(b"binary-bytes", "FROM scratch\n", None)
1503        );
1504        assert_eq!(hash.len(), 64, "sha256 as lowercase hex");
1505        assert!(
1506            hash.chars()
1507                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
1508        );
1509
1510        assert_ne!(
1511            hash,
1512            artifact_content_hash(b"other-bytes", "FROM scratch\n", None)
1513        );
1514        assert_ne!(
1515            hash,
1516            artifact_content_hash(b"binary-bytes", "FROM scratch\nRUN true\n", None)
1517        );
1518        assert_ne!(
1519            artifact_content_hash(b"ab", "c", None),
1520            artifact_content_hash(b"a", "bc", None),
1521            "the input boundary is part of the identity"
1522        );
1523
1524        // The projectless digest is pinned to the exact value this function produced
1525        // before #74. Every image name `build --reuse` ever derived embeds this digest's
1526        // first twelve characters, so changing the no-project stream silently orphans
1527        // every existing reuse — the module docs call that hazard out for the zip's own
1528        // bytes, and it applies to the algorithm the same way. Recomputed independently
1529        // (Python hashlib, 2026-08-31) rather than pasted from this function's output.
1530        assert_eq!(
1531            hash, "90a0ef925a4696b0c0f142241b2c714e63f40071d0d02951e26cb2a1d8bb24fc",
1532            "the no-project digest must stay what it was before #74"
1533        );
1534    }
1535
1536    /// **#74 step 3, the key.** The project files are part of the artifact identity:
1537    /// identical pairs agree, a lockfile edit is a new identity (and so a fresh image
1538    /// name and a fresh build), and the entry names count — the same bytes under a
1539    /// different ecosystem are a different identity, because the Dockerfile that consumes
1540    /// them installs a different environment.
1541    ///
1542    /// **Falsification** — run 2026-08-31 and again 2026-09-02: the lockfile's
1543    /// `hasher.update` lines were dropped from `artifact_content_hash` and the
1544    /// lockfile-edit assertion went red (two different lockfiles, one hash — the
1545    /// stale-reuse hazard verbatim); restored.
1546    #[test]
1547    fn the_content_hash_keys_on_the_lockfile() {
1548        let project = |ecosystem, lockfile: &[u8]| ProjectFiles {
1549            ecosystem,
1550            manifest: b"[project]".to_vec(),
1551            lockfile: lockfile.to_vec(),
1552        };
1553        let hash = artifact_content_hash(
1554            b"binary",
1555            "FROM scratch\n",
1556            Some(&project(Ecosystem::Uv, b"version = 1")),
1557        );
1558        assert_eq!(
1559            hash,
1560            artifact_content_hash(
1561                b"binary",
1562                "FROM scratch\n",
1563                Some(&project(Ecosystem::Uv, b"version = 1")),
1564            ),
1565            "identical dependency files share an image"
1566        );
1567        assert_ne!(
1568            hash,
1569            artifact_content_hash(
1570                b"binary",
1571                "FROM scratch\n",
1572                Some(&project(Ecosystem::Uv, b"version = 2")),
1573            ),
1574            "a lockfile edit is a new image name and a fresh build"
1575        );
1576        assert_ne!(
1577            hash,
1578            artifact_content_hash(b"binary", "FROM scratch\n", None),
1579            "carrying a layer is a different identity from carrying none"
1580        );
1581        assert_ne!(
1582            artifact_content_hash(
1583                b"binary",
1584                "FROM scratch\n",
1585                Some(&project(Ecosystem::Npm, b"version = 1")),
1586            ),
1587            hash,
1588            "the entry names count: the same bytes under another ecosystem install a \
1589             different environment"
1590        );
1591    }
1592
1593    /// The Dockerfile's `FROM` comes from the base image, so the two cannot disagree.
1594    #[test]
1595    fn the_default_dockerfile_derives_its_from_from_the_base_image() {
1596        let base = BaseImage::al2023();
1597        let dockerfile = default_dockerfile(9000, None, &base, None);
1598        assert_eq!(
1599            dockerfile_from_ref(&dockerfile),
1600            Some(base.docker_ref.as_str())
1601        );
1602        assert!(dockerfile.contains(r#"CMD ["/agentd"]"#));
1603        assert!(
1604            dockerfile.contains("ENTRYPOINT []"),
1605            "the trust boundary rests on this line"
1606        );
1607        assert!(dockerfile.contains("ENV AGENTD_PORT=9000"));
1608    }
1609
1610    /// A workdir is written as both a `mkdir` and a `WORKDIR`, and is absent when none was
1611    /// asked for. An empty string counts as none, since that is what an unset value looks
1612    /// like coming from a CLI flag.
1613    #[test]
1614    fn a_workdir_is_created_and_set_or_absent_entirely() {
1615        let base = BaseImage::al2023();
1616        let with = default_dockerfile(9000, Some("/opt/baked-workdir"), &base, None);
1617        assert!(with.contains("RUN mkdir -p /opt/baked-workdir"));
1618        assert!(with.contains("WORKDIR /opt/baked-workdir"));
1619
1620        for none in [None, Some("")] {
1621            let without = default_dockerfile(9000, none, &base, None);
1622            assert!(!without.contains("WORKDIR"), "{without}");
1623        }
1624    }
1625
1626    /// **#74 step 2, the install.** A project Dockerfile copies the ecosystem's pair into
1627    /// the working directory and installs from the lockfile with the lockfile-faithful
1628    /// spelling — `uv sync --locked`, `npm ci`, `cargo fetch --locked` — where the
1629    /// projectless Dockerfile installs nothing (the measured pre-#74 state).
1630    ///
1631    /// **Falsification** — run 2026-08-31: the `COPY` line was dropped from
1632    /// `default_dockerfile` and the copies-its-pair assertion went red for all three
1633    /// ecosystems; restored.
1634    #[test]
1635    fn a_project_dockerfile_installs_from_the_lockfile_it_can_see() {
1636        let base = BaseImage::al2023();
1637        for (ecosystem, install) in [
1638            (Ecosystem::Uv, "uv sync --locked"),
1639            (Ecosystem::Npm, "npm ci"),
1640            (Ecosystem::Cargo, "cargo fetch --locked"),
1641        ] {
1642            let dockerfile = default_dockerfile(9000, None, &base, Some(ecosystem));
1643            assert!(
1644                dockerfile.contains(&format!(
1645                    "COPY {} {} ./",
1646                    ecosystem.manifest_name(),
1647                    ecosystem.lockfile_name(),
1648                )),
1649                "copies its pair: {dockerfile}"
1650            );
1651            assert!(dockerfile.contains(install), "{dockerfile}");
1652            // The layer needs a directory even when the caller named none, because the
1653            // install resolves everything against the current directory.
1654            assert!(
1655                dockerfile.contains(&format!("WORKDIR {DEFAULT_PROJECT_WORKDIR}")),
1656                "{dockerfile}"
1657            );
1658
1659            // A caller-named workdir is where the layer lives instead.
1660            let placed = default_dockerfile(9000, Some("/srv/app"), &base, Some(ecosystem));
1661            assert!(placed.contains("WORKDIR /srv/app"), "{placed}");
1662            assert!(!placed.contains(DEFAULT_PROJECT_WORKDIR), "{placed}");
1663        }
1664
1665        let without = default_dockerfile(9000, None, &base, None);
1666        for install in ["uv sync", "npm ci", "cargo fetch", "COPY pyproject"] {
1667            assert!(!without.contains(install), "{without}");
1668        }
1669    }
1670
1671    /// The project Dockerfile passes every guard the plain one does: the `FROM` matches
1672    /// its base, the port agrees, the daemon stays the `CMD`, and the pair it copies
1673    /// satisfies [`require_project_install`]. A derived Dockerfile that failed its own
1674    /// preflight would refuse every `--project` build at the door.
1675    #[test]
1676    fn the_project_dockerfile_passes_its_own_guards() {
1677        let base = BaseImage::al2023();
1678        for ecosystem in Ecosystem::ALL {
1679            let dockerfile = default_dockerfile(9000, None, &base, Some(ecosystem));
1680            require_matching_from(&base, &dockerfile).expect("its FROM is its base");
1681            require_matching_agentd_port(9000, &dockerfile).expect("its port agrees");
1682            require_daemon_cmd(&dockerfile).expect("the daemon is still the CMD");
1683            let project = ProjectFiles {
1684                ecosystem,
1685                manifest: Vec::new(),
1686                lockfile: Vec::new(),
1687            };
1688            require_project_install(&project, &dockerfile)
1689                .expect("it copies the pair it was derived for");
1690        }
1691    }
1692
1693    /// **#74's silent-degradation guard.** A caller Dockerfile that never mentions the
1694    /// lockfile bakes no environment layer while building cleanly — the symptom is every
1695    /// launch still installing dependencies, with nothing naming the missing `COPY` — so
1696    /// it is refused up front, naming the lockfile, the install command, and both ways
1697    /// out.
1698    ///
1699    /// **Falsification** — run 2026-08-31: the `contains` check was inverted and both
1700    /// halves went red (the ignoring Dockerfile passed, the copying one was refused);
1701    /// restored.
1702    #[test]
1703    fn a_dockerfile_that_ignores_the_project_files_is_refused() {
1704        let project = ProjectFiles {
1705            ecosystem: Ecosystem::Npm,
1706            manifest: b"{}".to_vec(),
1707            lockfile: b"{}".to_vec(),
1708        };
1709        let error = require_project_install(
1710            &project,
1711            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1712             COPY agentd /agentd\n\
1713             ENTRYPOINT []\nCMD [\"/agentd\"]\n",
1714        )
1715        .expect_err("no mention of the lockfile bakes no layer");
1716        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1717        let message = error.to_string();
1718        assert!(message.contains("package-lock.json"), "{message}");
1719        assert!(message.contains("npm ci"), "{message}");
1720        assert!(message.contains("no environment layer"), "{message}");
1721
1722        require_project_install(
1723            &project,
1724            "FROM x\nCOPY package.json package-lock.json ./\nRUN npm ci\nCMD [\"/agentd\"]\n",
1725        )
1726        .expect("a Dockerfile that copies the pair agrees");
1727    }
1728
1729    /// `FROM` parsing tolerates the decoration a real Dockerfile carries: lowercase,
1730    /// leading whitespace, a `--platform` flag, and an `AS` alias.
1731    #[test]
1732    fn the_from_parser_ignores_decoration_rather_than_validating_syntax() {
1733        assert_eq!(dockerfile_from_ref("FROM alpine\n"), Some("alpine"));
1734        assert_eq!(dockerfile_from_ref("  from alpine:3\n"), Some("alpine:3"));
1735        assert_eq!(
1736            dockerfile_from_ref("FROM --platform=linux/arm64 alpine AS build\n"),
1737            Some("alpine")
1738        );
1739        assert_eq!(dockerfile_from_ref("RUN echo from nowhere\n"), None);
1740        assert_eq!(dockerfile_from_ref(""), None);
1741    }
1742
1743    /// A `FROM` that disagrees with the base image is refused, and the message names both
1744    /// refs — the one found and the one expected — because "these must agree" without both
1745    /// values leaves the caller to guess which to change.
1746    #[test]
1747    fn a_dockerfile_from_that_disagrees_with_the_base_is_refused() {
1748        let base = BaseImage::al2023();
1749        let error = require_matching_from(&base, "FROM ubuntu:24.04\nCOPY agentd /agentd\n")
1750            .expect_err("ubuntu is not the managed base");
1751        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1752        let message = error.to_string();
1753        assert!(message.contains("ubuntu:24.04"), "{message}");
1754        assert!(message.contains(&base.docker_ref), "{message}");
1755        assert!(
1756            message.contains("none of the measured platform behaviour applies"),
1757            "{message}"
1758        );
1759
1760        require_matching_from(&base, &default_dockerfile(9000, None, &base, None))
1761            .expect("the derived Dockerfile agrees with its own base");
1762    }
1763
1764    /// A digest-pinned `FROM` of the agreeing ref passes: it names one specific manifest of
1765    /// the base this check already accepts, which is the spelling a supply-chain-conscious
1766    /// caller uses. The boundary cases stay refused — a digest on a *different* ref is still
1767    /// a disagreement, and a malformed digest is not a digest.
1768    #[test]
1769    fn a_digest_pinned_from_of_the_agreeing_ref_passes() {
1770        let base = BaseImage::al2023();
1771        let digest = "c439fb4994ea7ca529233d6256446d3f8b7b4efb58956073e015303a170011de";
1772        let pinned = format!(
1773            "FROM {}@sha256:{digest}\nCOPY agentd /agentd\n",
1774            base.docker_ref
1775        );
1776        require_matching_from(&base, &pinned).expect("a digest pin of the same ref agrees");
1777
1778        require_matching_from(&base, &format!("FROM ubuntu:24.04@sha256:{digest}\n"))
1779            .expect_err("a digest does not launder a different ref");
1780        require_matching_from(&base, &format!("FROM {}@sha256:abc123\n", base.docker_ref))
1781            .expect_err("a 6-character digest is not a digest");
1782        require_matching_from(
1783            &base,
1784            &format!("FROM {}@sha256:{}\n", base.docker_ref, "g".repeat(64)),
1785        )
1786        .expect_err("64 non-hex characters are not a digest");
1787    }
1788
1789    /// A Dockerfile with no `FROM` is not this check's business: the build will say so, and
1790    /// refusing here would be a Dockerfile validator rather than an agreement check.
1791    #[test]
1792    fn a_dockerfile_with_no_from_is_left_to_the_build() {
1793        require_matching_from(&BaseImage::al2023(), "COPY agentd /agentd\n")
1794            .expect("no FROM is not a disagreement");
1795    }
1796
1797    /// The measured case, reproduced from the Dockerfile that spent it: a hand-written
1798    /// guest Dockerfile carrying `ENV AGENTD_PORT=8080` — the plausible port, and the wrong
1799    /// one — against a client sending `hooks.port=9000`. The build succeeds, the daemon logs
1800    /// `agentd listening`, and the image lands in `CREATE_FAILED` naming no port.
1801    #[test]
1802    fn a_dockerfile_port_that_disagrees_with_the_hook_port_is_refused() {
1803        let error = require_matching_agentd_port(
1804            crate::control::DEFAULT_AGENT_PORT,
1805            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1806             COPY agentd /agentd\n\
1807             ENV AGENTD_PORT=8080\n\
1808             EXPOSE 8080\n\
1809             CMD [\"/agentd\"]\n",
1810        )
1811        .expect_err("8080 is not the port the create call sends");
1812        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1813        let message = error.to_string();
1814        assert!(message.contains("8080"), "{message}");
1815        assert!(message.contains("9000"), "{message}");
1816        // The remedy is what a reader acts on, and the diagnostic's value is naming the
1817        // symptom that points away from the cause.
1818        assert!(message.contains("CREATE_FAILED"), "{message}");
1819        assert!(message.contains("ready/validate"), "{message}");
1820
1821        require_matching_agentd_port(
1822            crate::control::DEFAULT_AGENT_PORT,
1823            &default_dockerfile(
1824                crate::control::DEFAULT_AGENT_PORT,
1825                Some("/work"),
1826                &BaseImage::al2023(),
1827                None,
1828            ),
1829        )
1830        .expect("the derived Dockerfile agrees with the port it was derived from");
1831    }
1832
1833    /// Both `ENV` spellings set the variable, so a guard reading only `KEY=VALUE` would pass
1834    /// the legacy form it could not parse. The last assignment wins, as it does at build
1835    /// time.
1836    #[test]
1837    fn the_port_scan_reads_both_env_spellings_and_takes_the_last() {
1838        assert_eq!(dockerfile_agentd_port("ENV AGENTD_PORT=9000\n"), Some(9000));
1839        assert_eq!(dockerfile_agentd_port("ENV AGENTD_PORT 8080\n"), Some(8080));
1840        assert_eq!(dockerfile_agentd_port("env agentd_port=7000\n"), None);
1841        assert_eq!(
1842            dockerfile_agentd_port("ENV AGENTD_PORT=8080\nENV AGENTD_PORT=9000\n"),
1843            Some(9000),
1844        );
1845        assert_eq!(dockerfile_agentd_port("ENV AGENTD_LOG=info\n"), None);
1846        // Neither a missing variable nor an unparseable one is a disagreement: the daemon
1847        // keeps its own default for both (`crates/agentd/src/config.rs:118`).
1848        assert_eq!(
1849            dockerfile_agentd_port("FROM x\nCOPY agentd /agentd\n"),
1850            None
1851        );
1852        assert_eq!(dockerfile_agentd_port("ENV AGENTD_PORT=nine\n"), None);
1853        require_matching_agentd_port(
1854            crate::control::DEFAULT_AGENT_PORT,
1855            "FROM x\nCOPY agentd /agentd\n",
1856        )
1857        .expect("no variable agrees with the default, which is what the daemon will use");
1858    }
1859
1860    /// The other half of the pair, and the harder one to diagnose: a Dockerfile that names
1861    /// no port at all against a client that moved off the default. Silence is not neutral —
1862    /// `Config::from_env` keeps `9000` for an unset variable — so the guest listens on 9000
1863    /// while the hooks are dialled on the client's port, which is the measured failure with
1864    /// nothing in the Dockerfile to point at.
1865    #[test]
1866    fn a_dockerfile_naming_no_port_is_refused_when_the_client_moved_off_the_default() {
1867        let error = require_matching_agentd_port(
1868            8080,
1869            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1870             COPY agentd /agentd\n\
1871             CMD [\"/agentd\"]\n",
1872        )
1873        .expect_err("a silent Dockerfile leaves the daemon on 9000, not on 8080");
1874        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1875        let message = error.to_string();
1876        assert!(message.contains("8080"), "{message}");
1877        assert!(
1878            message.contains(&crate::control::DEFAULT_AGENT_PORT.to_string()),
1879            "the daemon's default is the value the reader has to learn: {message}"
1880        );
1881        assert!(message.contains("CREATE_FAILED"), "{message}");
1882        assert!(message.contains("ready/validate"), "{message}");
1883
1884        // An unparseable value has the same consequence in the guest as no value, so it is
1885        // refused for the same reason rather than passed as "not this guard's business".
1886        require_matching_agentd_port(8080, "FROM x\nENV AGENTD_PORT=nine\n")
1887            .expect_err("a value the daemon cannot parse leaves it on its own default");
1888
1889        // The default-port client is the common case and stays silent: the Dockerfile that
1890        // says nothing and the client that changed nothing already agree.
1891        require_matching_agentd_port(
1892            crate::control::DEFAULT_AGENT_PORT,
1893            "FROM x\nCOPY agentd /agentd\n",
1894        )
1895        .expect("silence agrees with the default");
1896    }
1897
1898    /// The fourth pair of the `FROM`/`WORKDIR`/`AGENTD_PORT` shape, found by sweeping for
1899    /// the others: a keepalive interval the client's silence tolerance is shorter than. The
1900    /// resulting error prints the client's own timeout as though it were the keepalive, so
1901    /// the number a reader would search for never appears.
1902    #[test]
1903    fn a_keepalive_at_or_over_the_client_idle_timeout_is_refused() {
1904        let timeout = crate::session::exec::DEFAULT_STREAM_IDLE_TIMEOUT;
1905        assert_eq!(timeout.as_secs(), 60, "the guard's arithmetic assumes this");
1906
1907        let error =
1908            require_keepalive_under_idle_timeout(timeout, "ENV AGENTD_SSE_KEEPALIVE_SECS=90\n")
1909                .expect_err("90s of scheduled silence exceeds a 60s tolerance");
1910        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1911        let message = error.to_string();
1912        assert!(message.contains("90"), "{message}");
1913        assert!(message.contains("60"), "{message}");
1914
1915        // Equality races rather than passing: the timeout fires on the same tick the
1916        // keepalive is due.
1917        require_keepalive_under_idle_timeout(timeout, "ENV AGENTD_SSE_KEEPALIVE_SECS=60\n")
1918            .expect_err("an interval equal to the tolerance is a race, not a margin");
1919
1920        require_keepalive_under_idle_timeout(timeout, "ENV AGENTD_SSE_KEEPALIVE_SECS 30\n")
1921            .expect("30s leaves a margin, in the legacy spelling");
1922        // The daemon's own default is 15s, so silence is safe for this pair.
1923        require_keepalive_under_idle_timeout(timeout, "FROM x\nCOPY agentd /agentd\n")
1924            .expect("an unset keepalive leaves the daemon at 15s");
1925        require_keepalive_under_idle_timeout(
1926            timeout,
1927            &default_dockerfile(
1928                crate::control::DEFAULT_AGENT_PORT,
1929                Some("/work"),
1930                &BaseImage::al2023(),
1931                None,
1932            ),
1933        )
1934        .expect("the derived Dockerfile sets no keepalive");
1935    }
1936
1937    /// **Issue #46, both refusable halves.** A Dockerfile with no `CMD` builds an image
1938    /// that runs the base's default process; a non-empty `ENTRYPOINT` turns the `CMD` into
1939    /// its arguments. Either way the daemon the artifact carries never starts, and the
1940    /// failure surfaces as `CREATE_FAILED` or a run-hook timeout naming neither
1941    /// instruction — so the message must name both the instruction and that symptom.
1942    #[test]
1943    fn a_dockerfile_that_never_runs_the_daemon_is_refused_naming_the_symptom() {
1944        // No CMD at all: the base's default applies, which is not /agentd.
1945        let error = require_daemon_cmd(
1946            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1947             COPY agentd /agentd\n\
1948             ENV AGENTD_PORT=9000\n",
1949        )
1950        .expect_err("no CMD means the daemon never starts");
1951        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1952        let message = error.to_string();
1953        assert!(message.contains("no CMD"), "{message}");
1954        assert!(message.contains("run-hook timeout"), "{message}");
1955        assert!(message.contains("CREATE_FAILED"), "{message}");
1956
1957        // A non-empty ENTRYPOINT swallows the CMD as its arguments.
1958        let error = require_daemon_cmd(
1959            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1960             COPY agentd /agentd\n\
1961             ENTRYPOINT [\"/bin/sh\", \"-c\"]\n\
1962             CMD [\"/agentd\"]\n",
1963        )
1964        .expect_err("a non-empty ENTRYPOINT makes CMD its arguments");
1965        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1966        let message = error.to_string();
1967        assert!(message.contains("ENTRYPOINT"), "{message}");
1968        assert!(message.contains("run-hook timeout"), "{message}");
1969
1970        // An empty CMD is the same absence in different spelling.
1971        require_daemon_cmd("FROM x\nCMD []\n").expect_err("CMD [] runs nothing");
1972    }
1973
1974    /// The shapes that must pass: the deployment invariant itself, in exec and spaced
1975    /// spellings, and the invariant's `ENTRYPOINT []` with any interior whitespace. The
1976    /// derived Dockerfile passes its own guard, which is what keeps the default path
1977    /// unaffected.
1978    #[test]
1979    fn the_deployment_invariant_passes_the_daemon_cmd_guard() {
1980        require_daemon_cmd(&default_dockerfile(
1981            9000,
1982            Some("/work"),
1983            &BaseImage::al2023(),
1984            None,
1985        ))
1986        .expect("the derived Dockerfile is the invariant");
1987        require_daemon_cmd("FROM x\nENTRYPOINT []\nCMD [\"/agentd\"]\n").expect("the invariant");
1988        require_daemon_cmd("FROM x\nENTRYPOINT [ ]\nCMD [\"/agentd\"]\n")
1989            .expect("interior whitespace is still the empty exec form");
1990        require_daemon_cmd("FROM x\ncmd [\"/agentd\"]\n").expect("case-insensitive, no ENTRYPOINT");
1991        // Last instruction wins, as at build time: a later empty ENTRYPOINT un-swallows.
1992        require_daemon_cmd("FROM x\nENTRYPOINT [\"/bin/sh\"]\nENTRYPOINT []\nCMD [\"/agentd\"]\n")
1993            .expect("the last ENTRYPOINT is the one the build uses");
1994        // And the reverse ordering is refused for the same reason.
1995        require_daemon_cmd("FROM x\nENTRYPOINT []\nENTRYPOINT [\"/bin/sh\"]\nCMD [\"/agentd\"]\n")
1996            .expect_err("the last ENTRYPOINT is non-empty");
1997    }
1998
1999    /// Workdir inheritance is refused when neither the base nor the Dockerfile declares
2000    /// one, and the message says where the symptom would have appeared — in the guest, a
2001    /// build cycle later.
2002    #[test]
2003    fn inheriting_a_workdir_nothing_declares_is_refused() {
2004        let base = BaseImage::al2023();
2005        assert!(base.working_dir.is_empty(), "the measured case");
2006
2007        let error = require_workdir(&base, None).expect_err("nothing declares a workdir");
2008        assert_eq!(error.kind(), ErrorKind::InvalidArg);
2009        let message = error.to_string();
2010        assert!(message.contains("no WorkingDir"), "{message}");
2011        assert!(message.contains("nothing to inherit"), "{message}");
2012        assert!(message.contains("docs/PLATFORM.md"), "{message}");
2013    }
2014
2015    /// It is accepted when *either* side declares one — the Dockerfile's `WORKDIR` or the
2016    /// base image's own `working_dir`. Both directions, because a check that only read the
2017    /// Dockerfile would refuse a caller on a purpose-built image that declares one.
2018    #[test]
2019    fn either_the_dockerfile_or_the_base_may_supply_the_workdir() {
2020        let base = BaseImage::al2023();
2021        require_workdir(&base, Some("FROM x\nWORKDIR /srv\n"))
2022            .expect("the Dockerfile declares one");
2023
2024        let purpose_built = BaseImage {
2025            working_dir: "/app".to_string(),
2026            ..BaseImage::al2023()
2027        };
2028        require_workdir(&purpose_built, None).expect("the base image declares one");
2029    }
2030
2031    /// A bare `WORKDIR` with no argument does not count as declaring one. It is the shape a
2032    /// truncated edit leaves behind, and treating it as a declaration would pass the guard
2033    /// on a Dockerfile that sets nothing.
2034    #[test]
2035    fn a_workdir_with_no_argument_does_not_count_as_a_declaration() {
2036        let error = require_workdir(&BaseImage::al2023(), Some("FROM x\nWORKDIR\n"))
2037            .expect_err("WORKDIR with no path declares nothing");
2038        assert_eq!(error.kind(), ErrorKind::InvalidArg);
2039    }
2040
2041    /// **IMAGE-1, the acceptance test #220 names.** Wrapping a bare `FROM` produces exactly the
2042    /// default Dockerfile for that base, so the stanza has one source: the default generator's
2043    /// output minus its `FROM` line is what a wrap appends. Checked with and without a workdir,
2044    /// and on a non-default port, because each of those is a branch of the one stanza.
2045    #[test]
2046    fn wrapping_a_bare_from_is_the_default_dockerfile_minus_nothing() {
2047        for (port, workdir) in [
2048            (DEFAULT_AGENT_PORT_FOR_TESTS, None),
2049            (DEFAULT_AGENT_PORT_FOR_TESTS, Some("/srv/task")),
2050            (8080, None),
2051        ] {
2052            let base = BaseImage {
2053                docker_ref: "x".to_string(),
2054                ..BaseImage::al2023()
2055            };
2056            let default = default_dockerfile(port, workdir, &base, None);
2057            let opts = WrapOptions {
2058                port,
2059                workdir: workdir.map(str::to_string),
2060                ..WrapOptions::default()
2061            };
2062            assert_eq!(
2063                wrap_dockerfile("FROM x\n", &opts).expect("a bare FROM wraps"),
2064                default,
2065                "IMAGE-1: port {port} workdir {workdir:?}"
2066            );
2067            let (from, stanza) = default.split_once('\n').expect("lines");
2068            assert_eq!(from, "FROM x");
2069            assert!(stanza.ends_with("CMD [\"/agentd\"]\n"), "{stanza}");
2070        }
2071    }
2072
2073    /// **IMAGE-2.** Whatever the task set — its own entrypoint, command, port, user — the
2074    /// wrapped result ends on the bootstrap invariant with the client's port, and a task that
2075    /// ends on another user has `USER root` restored ahead of the stanza. A task that ends on
2076    /// root, or never changes user, gets no extra line, which is what keeps IMAGE-1's equality.
2077    #[test]
2078    fn a_wrapped_task_ends_on_the_invariant_with_root_restored_when_needed() {
2079        let task = "FROM python:3.12-slim\nWORKDIR /app\nENV AGENTD_PORT=8080\n\
2080                    ENTRYPOINT [\"/bin/sh\", \"-c\"]\nCMD [\"python\", \"serve.py\"]\nUSER app\n";
2081        let wrapped = wrap_dockerfile(task, &WrapOptions::default()).expect("wraps");
2082        let added = wrapped
2083            .strip_prefix(task)
2084            .expect("the task text is kept verbatim");
2085        assert!(
2086            added.starts_with("USER root\nCOPY agentd /agentd\n"),
2087            "{added}"
2088        );
2089        assert_eq!(dockerfile_entrypoint(&wrapped), Some("[]"));
2090        assert_eq!(dockerfile_cmd(&wrapped), Some(r#"["/agentd"]"#));
2091        assert_eq!(dockerfile_agentd_port(&wrapped), Some(9000));
2092        require_daemon_cmd(&wrapped).expect("the daemon is the CMD");
2093        require_matching_agentd_port(9000, &wrapped).expect("the stanza's port wins");
2094
2095        for (last_user, restored) in [
2096            ("USER root", false),
2097            ("USER 0", false),
2098            ("USER root:root", false),
2099            ("USER 0:0", false),
2100            ("user app", true),
2101            ("USER 1000:1000", true),
2102            ("USER root:staff", true),
2103            ("USER ${TASK_USER}", true),
2104        ] {
2105            let task = format!("FROM x\n{last_user}\n");
2106            let added = wrap_dockerfile(&task, &WrapOptions::default())
2107                .expect("wraps")
2108                .strip_prefix(task.as_str())
2109                .expect("verbatim")
2110                .to_string();
2111            assert_eq!(
2112                added.starts_with("USER root\n"),
2113                restored,
2114                "IMAGE-2: {last_user:?}: {added}"
2115            );
2116        }
2117
2118        // Only the last USER counts, as at build time.
2119        let task = "FROM x\nUSER app\nUSER root\n";
2120        let wrapped = wrap_dockerfile(task, &WrapOptions::default()).expect("wraps");
2121        let added = wrapped.strip_prefix(task).expect("verbatim");
2122        assert!(added.starts_with("COPY agentd /agentd\n"), "{added}");
2123    }
2124
2125    /// **IMAGE-2, the newline.** A task file without a trailing newline gets one before the
2126    /// stanza, in either line ending, so the stanza's first line is its own instruction.
2127    #[test]
2128    fn a_task_without_a_trailing_newline_is_normalized() {
2129        let wrapped = wrap_dockerfile("FROM x", &WrapOptions::default()).expect("wraps");
2130        assert!(
2131            wrapped.starts_with("FROM x\nCOPY agentd /agentd\n"),
2132            "{wrapped}"
2133        );
2134        let wrapped =
2135            wrap_dockerfile("FROM x\r\nRUN true", &WrapOptions::default()).expect("wraps");
2136        assert!(
2137            wrapped.starts_with("FROM x\r\nRUN true\nCOPY agentd /agentd\n"),
2138            "{wrapped}"
2139        );
2140        let wrapped = wrap_dockerfile("FROM x\r\n", &WrapOptions::default()).expect("wraps");
2141        assert!(wrapped.starts_with("FROM x\r\nCOPY agentd"), "{wrapped}");
2142    }
2143
2144    /// IMAGE-2: the builder executes capture with the final USER before restoring
2145    /// root for sealing and daemon startup, regardless of how the task chose it.
2146    #[test]
2147    fn preserving_user_captures_before_root_and_keeps_the_daemon_as_cmd() {
2148        for task in [
2149            "FROM x\nUSER app\n",
2150            "FROM x\nUSER 4242:4343\n",
2151            "FROM x AS builder\nUSER ignored\nFROM y\n",
2152            "FROM x AS base\nUSER app\nFROM base\n",
2153            "FROM x\nARG who=app\nUSER ${who}\n",
2154            "FROM x\nENV AGENTD_DEFAULT_USER=root\nUSER app\n",
2155        ] {
2156            let wrapped = wrap_dockerfile_preserving_user(task, &WrapOptions::default()).unwrap();
2157            assert!(wrapped.starts_with(task));
2158            let tail = &wrapped[task.len()..];
2159            assert!(tail.find("--capture-image-user").unwrap() < tail.find("USER 0:0").unwrap());
2160            assert!(tail.find("USER 0:0").unwrap() < tail.find("--seal-image-user").unwrap());
2161            assert!(tail.contains("ENV AGENTD_PRESERVE_IMAGE_USER=1"));
2162            assert!(tail.ends_with("ENTRYPOINT []\nCMD [\"/agentd\"]\n"));
2163            assert!(!tail.contains("AGENTD_DEFAULT_USER="));
2164        }
2165        for invalid in ["USER app\n", "FROM x\nRUN echo \\"] {
2166            assert!(wrap_dockerfile_preserving_user(invalid, &WrapOptions::default()).is_err());
2167        }
2168    }
2169
2170    /// **IMAGE-2.** The capture stanza starts on its own line, whether the task already
2171    /// ends with a newline or needs one, and preserves either existing line ending.
2172    #[test]
2173    fn preserving_user_normalizes_the_task_boundary() {
2174        for (task, prefix) in [
2175            (
2176                "FROM x\nUSER app",
2177                "FROM x\nUSER app\nCOPY --chmod=0755 agentd /agentd\n",
2178            ),
2179            (
2180                "FROM x\nUSER app\n",
2181                "FROM x\nUSER app\nCOPY --chmod=0755 agentd /agentd\n",
2182            ),
2183            (
2184                "FROM x\r\nUSER app\r\n",
2185                "FROM x\r\nUSER app\r\nCOPY --chmod=0755 agentd /agentd\n",
2186            ),
2187        ] {
2188            let wrapped = wrap_dockerfile_preserving_user(task, &WrapOptions::default())
2189                .expect("the task wraps");
2190            assert!(wrapped.starts_with(prefix), "{wrapped:?}");
2191        }
2192    }
2193
2194    /// **IMAGE-1.** Preserving the image user still honors the wrapper's workdir option;
2195    /// an empty option leaves the image's workdir alone, like an omitted option.
2196    #[test]
2197    fn preserving_user_keeps_the_requested_workdir() {
2198        for (workdir, expected) in [
2199            (None, vec![]),
2200            (Some(""), vec![]),
2201            (Some("/srv/task"), vec!["/srv/task"]),
2202        ] {
2203            let opts = WrapOptions {
2204                workdir: workdir.map(str::to_string),
2205                ..WrapOptions::default()
2206            };
2207            let wrapped = wrap_dockerfile_preserving_user("FROM x\nUSER app\n", &opts)
2208                .expect("the task wraps");
2209            let declared: Vec<_> = wrapped
2210                .lines()
2211                .filter_map(|line| line.strip_prefix("WORKDIR "))
2212                .collect();
2213            assert_eq!(declared, expected, "{wrapped}");
2214            if workdir == Some("/srv/task") {
2215                assert!(wrapped.contains("RUN mkdir -p /srv/task\n"), "{wrapped}");
2216            }
2217        }
2218    }
2219
2220    /// **IMAGE-3.** Each refusal on its own, against an otherwise wrappable task, names its
2221    /// cause: no `FROM`, a trailing continuation (in the default and a custom escape
2222    /// character, across blank and comment lines, in either line ending), an open heredoc, a
2223    /// keepalive the client cannot tolerate, a bad workdir or port, and inheriting a workdir
2224    /// nothing declares.
2225    #[test]
2226    fn a_task_the_stanza_cannot_follow_is_refused_naming_the_cause() {
2227        let refused = |task: &str, opts: WrapOptions, cause: &str| {
2228            let error = wrap_dockerfile(task, &opts).expect_err(cause);
2229            assert_eq!(error.kind(), ErrorKind::InvalidArg, "{error}");
2230            let message = error.to_string();
2231            assert!(message.contains(cause), "IMAGE-3 {cause:?}: {message}");
2232        };
2233        let none = WrapOptions::default;
2234        refused("RUN echo hello\n", none(), "no FROM");
2235        refused("", none(), "no FROM");
2236        refused("FROM\n", none(), "no FROM");
2237        refused(
2238            "FROM x\nRUN apt-get update && \\\n",
2239            none(),
2240            "line continuation",
2241        );
2242        refused("FROM x\nRUN a \\   \n", none(), "line continuation");
2243        refused("FROM x\nRUN a \\\r\n", none(), "line continuation");
2244        refused(
2245            "FROM x\nRUN a \\\n\n# comment\n",
2246            none(),
2247            "line continuation",
2248        );
2249        refused("# escape=`\nFROM x\nRUN a `\n", none(), "line continuation");
2250        refused("FROM x\nRUN <<EOF\necho never closed\n", none(), "heredoc");
2251        refused("FROM x\nRUN <<-\"END\"\necho x\n", none(), "heredoc");
2252        refused("FROM x\nCOPY <<A <<B /dst/\na\nA\nb\n", none(), "heredoc");
2253        refused(
2254            "FROM x\nENV AGENTD_SSE_KEEPALIVE_SECS=90\n",
2255            none(),
2256            "AGENTD_SSE_KEEPALIVE_SECS=90",
2257        );
2258        for workdir in ["relative/dir", "/srv\nRUN evil", "/my dir", "/tab\there"] {
2259            refused(
2260                "FROM x\n",
2261                WrapOptions {
2262                    workdir: Some(workdir.to_string()),
2263                    ..none()
2264                },
2265                "absolute path",
2266            );
2267        }
2268        refused("FROM x\n", WrapOptions { port: 0, ..none() }, "port");
2269        refused(
2270            "FROM x\n",
2271            WrapOptions {
2272                inherit_workdir: true,
2273                ..none()
2274            },
2275            "nothing to inherit",
2276        );
2277    }
2278
2279    /// **IMAGE-3, the other side.** What looks like a refusal but is not: a backslash under a
2280    /// backtick escape, a continuation that was finished, a closed heredoc (including a `<<-`
2281    /// terminator indented with tabs), a here-string, an escaped keepalive under the timeout,
2282    /// and inheriting a workdir the task or the options declare.
2283    #[test]
2284    fn a_finished_task_is_wrapped_even_when_it_looks_unfinished() {
2285        let none = WrapOptions::default;
2286        for task in [
2287            "# escape=`\nFROM x\nRUN a \\\n",
2288            "FROM x\nRUN a \\\n  && b\n",
2289            "FROM x\nRUN <<EOF\necho closed\nEOF\n",
2290            "FROM x\nRUN <<-EOF\n\techo closed\n\tEOF\n",
2291            "FROM x\nCOPY <<A <<B /dst/\na\nA\nb\nB\n",
2292            "FROM x\nRUN cat <<< word\n",
2293            "FROM x\n# a trailing comment \\\n",
2294            "FROM x\nENV AGENTD_SSE_KEEPALIVE_SECS=30\n",
2295        ] {
2296            wrap_dockerfile(task, &none())
2297                .unwrap_or_else(|error| panic!("{task:?} was refused: {error}"));
2298        }
2299        wrap_dockerfile(
2300            "FROM x\nWORKDIR /app\n",
2301            &WrapOptions {
2302                inherit_workdir: true,
2303                ..none()
2304            },
2305        )
2306        .expect("the task declares one");
2307        wrap_dockerfile(
2308            "FROM x\n",
2309            &WrapOptions {
2310                inherit_workdir: true,
2311                workdir: Some("/srv".to_string()),
2312                ..none()
2313            },
2314        )
2315        .expect("the options declare one");
2316        wrap_dockerfile(
2317            "FROM x\n",
2318            &WrapOptions {
2319                workdir: Some(String::new()),
2320                ..none()
2321            },
2322        )
2323        .expect("an empty workdir is none, as default_dockerfile reads it");
2324    }
2325
2326    /// **IMAGE-4.** A derived base takes its ref from the first `FROM`, keeps the managed
2327    /// base's name (so `baseImageArn` is unchanged) and an empty working dir, and pairs with
2328    /// the Dockerfile it came from under the `FROM` guard — digest pins included, since the
2329    /// ref is taken whole. A Dockerfile with no `FROM` has nothing to derive.
2330    #[test]
2331    fn a_base_derived_from_a_dockerfile_pairs_with_it_by_construction() {
2332        let digest = "c439fb4994ea7ca529233d6256446d3f8b7b4efb58956073e015303a170011de";
2333        for (task, docker_ref) in [
2334            ("FROM python:3.12-slim\n", "python:3.12-slim".to_string()),
2335            (
2336                "FROM --platform=linux/arm64 golang:1.23 AS build\nFROM python:3.12-slim\n",
2337                "golang:1.23".to_string(),
2338            ),
2339            (
2340                &*format!("FROM ubuntu:24.04@sha256:{digest}\n"),
2341                format!("ubuntu:24.04@sha256:{digest}"),
2342            ),
2343        ] {
2344            let base = BaseImage::from_dockerfile(task).expect("a FROM");
2345            assert_eq!(base.docker_ref, docker_ref);
2346            assert_eq!(
2347                base.name,
2348                BaseImage::al2023().name,
2349                "IMAGE-4 keeps the managed base"
2350            );
2351            assert_eq!(base.working_dir, "");
2352            let wrapped = wrap_dockerfile(task, &WrapOptions::default()).expect("wraps");
2353            require_matching_from(&base, &wrapped).expect("IMAGE-4: the pair agrees");
2354            assert_eq!(BaseImage::from_dockerfile(&wrapped).expect("a FROM"), base);
2355        }
2356        // The inversion #220 removes: under the managed base, a task on another base is
2357        // refused.
2358        require_matching_from(
2359            &BaseImage::al2023(),
2360            &wrap_dockerfile("FROM python:3.12-slim\n", &WrapOptions::default()).expect("wraps"),
2361        )
2362        .expect_err("the managed base does not pair with python:3.12-slim");
2363
2364        let error = BaseImage::from_dockerfile("RUN echo hello\n").expect_err("no FROM");
2365        assert_eq!(error.kind(), ErrorKind::InvalidArg);
2366        assert!(error.to_string().contains("no FROM"), "{error}");
2367    }
2368
2369    /// **The table `crates/model/src/wrap.rs` specifies**, rendered as real Dockerfile text: every
2370    /// task and option combination the model enumerates, and the refusal (or the `USER root`
2371    /// verdict) the model's `specified` gives it. The model crate cannot be a dependency here
2372    /// (this crate is published and the model isn't), so the table is restated as `expected`
2373    /// below, and `crates/model-conformance/tests/tables.rs` drives this function over the model's rows.
2374    #[test]
2375    fn wrap_agrees_with_the_model_table() {
2376        #[derive(Debug)]
2377        enum Expect {
2378            Refused(&'static str),
2379            Wrapped { user_root: bool },
2380        }
2381        let digest = "c439fb4994ea7ca529233d6256446d3f8b7b4efb58956073e015303a170011de";
2382        let managed = BaseImage::al2023().docker_ref;
2383        let froms = [
2384            None,
2385            Some(managed.clone()),
2386            Some(format!("{managed}@sha256:{digest}")),
2387            Some("python:3.12-slim".to_string()),
2388        ];
2389        let mut checked = 0;
2390        for from in &froms {
2391            for tail in 0..3 {
2392                for user in 0..3 {
2393                    for declares_workdir in [false, true] {
2394                        for keepalive_too_long in [false, true] {
2395                            for workdir in 0..3 {
2396                                for inherit_workdir in [false, true] {
2397                                    let mut text = String::new();
2398                                    match from {
2399                                        Some(from) => text.push_str(&format!("FROM {from}\n")),
2400                                        None => text.push_str("RUN echo no base\n"),
2401                                    }
2402                                    if declares_workdir {
2403                                        text.push_str("WORKDIR /app\n");
2404                                    }
2405                                    if keepalive_too_long {
2406                                        text.push_str("ENV AGENTD_SSE_KEEPALIVE_SECS=60\n");
2407                                    }
2408                                    match user {
2409                                        1 => text.push_str("USER root\n"),
2410                                        2 => text.push_str("USER app\n"),
2411                                        _ => {}
2412                                    }
2413                                    match tail {
2414                                        1 => text.push_str("RUN make \\\n"),
2415                                        2 => text.push_str("RUN <<EOF\necho open\n"),
2416                                        _ => {}
2417                                    }
2418                                    let opts = WrapOptions {
2419                                        workdir: match workdir {
2420                                            1 => Some("/srv".to_string()),
2421                                            2 => Some("srv".to_string()),
2422                                            _ => None,
2423                                        },
2424                                        inherit_workdir,
2425                                        ..WrapOptions::default()
2426                                    };
2427                                    let expected = if from.is_none() {
2428                                        Expect::Refused("no FROM")
2429                                    } else if tail != 0 {
2430                                        Expect::Refused(if tail == 1 {
2431                                            "line continuation"
2432                                        } else {
2433                                            "heredoc"
2434                                        })
2435                                    } else if keepalive_too_long {
2436                                        Expect::Refused("AGENTD_SSE_KEEPALIVE_SECS")
2437                                    } else if workdir == 2 {
2438                                        Expect::Refused("absolute path")
2439                                    } else if inherit_workdir && !declares_workdir && workdir == 0 {
2440                                        Expect::Refused("nothing to inherit")
2441                                    } else {
2442                                        Expect::Wrapped {
2443                                            user_root: user == 2,
2444                                        }
2445                                    };
2446                                    let got = wrap_dockerfile(&text, &opts);
2447                                    match (&expected, &got) {
2448                                        (Expect::Refused(cause), Err(error)) => assert!(
2449                                            error.to_string().contains(cause),
2450                                            "{expected:?} for {text:?} {opts:?}: {error}"
2451                                        ),
2452                                        (Expect::Wrapped { user_root }, Ok(out)) => assert_eq!(
2453                                            out.strip_prefix(text.as_str())
2454                                                .expect("verbatim")
2455                                                .starts_with("USER root\n"),
2456                                            *user_root,
2457                                            "{text:?} {opts:?}"
2458                                        ),
2459                                        _ => panic!(
2460                                            "{expected:?} for {text:?} {opts:?}, got {got:?}"
2461                                        ),
2462                                    }
2463                                    checked += 1;
2464                                }
2465                            }
2466                        }
2467                    }
2468                }
2469            }
2470        }
2471        assert_eq!(
2472            checked,
2473            4 * 3 * 3 * 2 * 2 * 3 * 2,
2474            "every combination the model has"
2475        );
2476    }
2477
2478    fn context_of(entries: &[(&str, u32, &[u8])]) -> crate::control::context::BuildContext {
2479        crate::control::context::BuildContext::from_entries(
2480            entries
2481                .iter()
2482                .map(
2483                    |(name, mode, bytes)| crate::control::context::ContextEntry {
2484                        name: (*name).to_string(),
2485                        mode: *mode,
2486                        bytes: bytes.to_vec(),
2487                    },
2488                )
2489                .collect(),
2490        )
2491        .expect("valid entries")
2492    }
2493
2494    /// **IMAGE-6, the pin.** A request with no build context — `None`, or an empty one — hashes
2495    /// to exactly what `artifact_content_hash` produced before #221, so no `build --reuse` or
2496    /// `AgentVm` image name moves. The vector is the one pinned for #74, recomputed
2497    /// independently with Python's hashlib then.
2498    #[test]
2499    fn a_request_without_a_context_keeps_its_digest() {
2500        let pinned = "90a0ef925a4696b0c0f142241b2c714e63f40071d0d02951e26cb2a1d8bb24fc";
2501        assert_eq!(
2502            artifact_content_hash_with_context(b"binary-bytes", "FROM scratch\n", None, None),
2503            pinned,
2504            "IMAGE-6: the no-context digest is the pre-#221 digest"
2505        );
2506        let empty = crate::control::context::BuildContext::default();
2507        assert_eq!(
2508            artifact_content_hash_with_context(
2509                b"binary-bytes",
2510                "FROM scratch\n",
2511                None,
2512                Some(&empty)
2513            ),
2514            pinned,
2515            "an empty context carries no extra entries, so it is the same artifact"
2516        );
2517        assert_eq!(
2518            artifact_content_hash(b"binary-bytes", "FROM scratch\n", None),
2519            pinned
2520        );
2521    }
2522
2523    /// **IMAGE-6, the extension.** Each entry's name, mode, and bytes are part of the
2524    /// identity; the order entries were read in is not, because a context is sorted by name.
2525    #[test]
2526    fn the_context_hash_follows_every_entry_and_not_their_order() {
2527        let hash = |context: &crate::control::context::BuildContext| {
2528            artifact_content_hash_with_context(b"bin", "FROM x\n", None, Some(context))
2529        };
2530        let base = hash(&context_of(&[
2531            ("a.txt", 0o644, b"a"),
2532            ("b.txt", 0o644, b"b"),
2533        ]));
2534        assert_ne!(
2535            base,
2536            artifact_content_hash_with_context(b"bin", "FROM x\n", None, None),
2537            "IMAGE-6: a context is part of the identity"
2538        );
2539        assert_eq!(
2540            base,
2541            hash(&context_of(&[
2542                ("b.txt", 0o644, b"b"),
2543                ("a.txt", 0o644, b"a")
2544            ])),
2545            "the read order is not"
2546        );
2547        for (changed, what) in [
2548            (
2549                context_of(&[("a.txt", 0o644, b"A"), ("b.txt", 0o644, b"b")]),
2550                "bytes",
2551            ),
2552            (
2553                context_of(&[("a.txt", 0o755, b"a"), ("b.txt", 0o644, b"b")]),
2554                "mode",
2555            ),
2556            (
2557                context_of(&[("c.txt", 0o644, b"a"), ("b.txt", 0o644, b"b")]),
2558                "name",
2559            ),
2560            (context_of(&[("a.txt", 0o644, b"ab")]), "boundary"),
2561        ] {
2562            assert_ne!(base, hash(&changed), "IMAGE-6: the entry {what} counts");
2563        }
2564    }
2565
2566    /// **IMAGE-7, the zip.** Equal inputs make byte-identical artifacts, so equal inputs are
2567    /// one S3 object: every entry carries the DOS epoch as its date and a fixed mode, the
2568    /// context entries sit beside the Dockerfile at the root, and the Dockerfile entry is the
2569    /// one passed in. The same build a second apart, which needs a real sleep this crate
2570    /// can't make, is `crates/microvms-core/tests/artifact_across_seconds.rs`.
2571    #[test]
2572    fn the_artifact_is_deterministic_with_fixed_dates_and_modes() {
2573        use std::io::Read as _;
2574
2575        let context = context_of(&[("app/run.sh", 0o755, b"#!/bin/sh\n"), ("data", 0o644, b"d")]);
2576        let build = || {
2577            build_artifact_with_context(
2578                &aarch64_daemon(b"daemon"),
2579                "FROM x\n",
2580                None,
2581                Some(&context),
2582            )
2583            .expect("zips")
2584        };
2585        let first = build();
2586        assert_eq!(first, build(), "IMAGE-7: equal inputs, identical bytes");
2587
2588        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(first)).expect("a zip");
2589        let mut names = Vec::new();
2590        for index in 0..archive.len() {
2591            let entry = archive.by_index(index).expect("entry");
2592            let name = entry.name().expect("a name").into_owned();
2593            let modified = entry.last_modified().expect("a date");
2594            assert_eq!(
2595                (modified.year(), modified.month(), modified.day()),
2596                (1980, 1, 1),
2597                "IMAGE-7: {name} carries a fixed date"
2598            );
2599            let mode = entry.unix_mode().expect("a mode") & 0o777;
2600            let expected = match name.as_str() {
2601                "agentd" | "app/run.sh" => 0o755,
2602                _ => 0o644,
2603            };
2604            assert_eq!(mode, expected, "IMAGE-7: {name} mode {mode:o}");
2605            names.push(name);
2606        }
2607        assert_eq!(names, ["Dockerfile", "agentd", "app/run.sh", "data"]);
2608        let mut dockerfile = String::new();
2609        archive
2610            .by_name("Dockerfile")
2611            .expect("entry")
2612            .read_to_string(&mut dockerfile)
2613            .expect("reads");
2614        assert_eq!(dockerfile, "FROM x\n");
2615    }
2616
2617    /// **IMAGE-7, the host system.** Every entry's central-directory header records Unix (3)
2618    /// as the system that made it, whatever host builds the artifact. zip records the running
2619    /// host otherwise, MS-DOS (0) on Windows, and that one byte made a Windows build differ
2620    /// from a Linux build of the same inputs and let a reader that follows it take the
2621    /// entries' modes for DOS attributes.
2622    ///
2623    /// **Falsification**: set `.system(zip::System::Dos)`, the Windows default, in
2624    /// `build_artifact_with_context`'s options, and every host byte reads 0.
2625    #[test]
2626    fn every_artifact_entry_records_unix_as_its_host_system() {
2627        let context = context_of(&[("app/run.sh", 0o755, b"#!/bin/sh\n")]);
2628        let bytes = build_artifact_with_context(
2629            &aarch64_daemon(b"daemon"),
2630            "FROM x\n",
2631            None,
2632            Some(&context),
2633        )
2634        .expect("zips");
2635        assert_eq!(
2636            central_directory_hosts(&bytes),
2637            [3, 3, 3],
2638            "IMAGE-7: every entry's host system is Unix"
2639        );
2640    }
2641
2642    /// The host-system byte of each central-directory header, in order (APPNOTE 4.3.12 and
2643    /// 4.4.2: the high byte of "version made by"). The artifact carries no archive comment, so
2644    /// its end record is the last 22 bytes: the entry count at +10, the directory's offset at
2645    /// +16.
2646    fn central_directory_hosts(bytes: &[u8]) -> Vec<u8> {
2647        let u16_at = |at: usize| usize::from(u16::from_le_bytes([bytes[at], bytes[at + 1]]));
2648        let end = bytes.len() - 22;
2649        assert_eq!(&bytes[end..end + 4], b"PK\x05\x06", "the end record");
2650        let offset = bytes[end + 16..end + 20].try_into().expect("four bytes");
2651        let mut at = usize::try_from(u32::from_le_bytes(offset)).expect("fits");
2652        (0..u16_at(end + 10))
2653            .map(|_| {
2654                assert_eq!(
2655                    &bytes[at..at + 4],
2656                    b"PK\x01\x02",
2657                    "a central-directory header"
2658                );
2659                let host = bytes[at + 5];
2660                at += 46 + u16_at(at + 28) + u16_at(at + 30) + u16_at(at + 32);
2661                host
2662            })
2663            .collect()
2664    }
2665
2666    /// **IMAGE-7, the byte scan extended.** The agent token has no path into a context either:
2667    /// the artifact built from a context is scanned the way AC-2-3 scans the plain one.
2668    #[test]
2669    fn a_context_artifact_never_carries_the_agent_token() {
2670        let token = "s3cr3t-agent-token-do-not-bake-me";
2671        let context = context_of(&[("app/main.py", 0o644, b"print('hi')\n")]);
2672        let bytes = build_artifact_with_context(
2673            &aarch64_daemon(b"binary"),
2674            &wrap_dockerfile("FROM x\n", &WrapOptions::default()).expect("wraps"),
2675            None,
2676            Some(&context),
2677        )
2678        .expect("zips");
2679        assert!(
2680            !bytes
2681                .windows(token.len())
2682                .any(|window| window == token.as_bytes())
2683        );
2684    }
2685
2686    /// The base image ARN, for the region it is requested in.
2687    ///
2688    /// `microvm-image:` with a **colon**, which is the spelling for a managed base *and* for
2689    /// a customer image alike — measured 2026-08-15 against real ARNs in us-east-1, and the
2690    /// only form the model's `TaggableResource` pattern admits. The docs above this function
2691    /// carry the measurement.
2692    ///
2693    /// **Falsification** — change the separator to `/` and both assertions go red. That was
2694    /// the state twelve fakes and the transport encoding test were in, which is why this
2695    /// test now asserts the separator explicitly rather than only the region.
2696    #[test]
2697    fn the_base_image_arn_names_the_request_region_with_a_colon_separator() {
2698        assert_eq!(
2699            BaseImage::al2023().arn(&crate::region::Region::UsEast1),
2700            "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"
2701        );
2702        assert_eq!(
2703            BaseImage::al2023().arn(&crate::region::Region::ApNortheast1),
2704            "arn:aws:lambda:ap-northeast-1:aws:microvm-image:al2023-1"
2705        );
2706        assert!(
2707            !BaseImage::al2023()
2708                .arn(&crate::region::Region::UsEast1)
2709                .contains("microvm-image/"),
2710            "the slash form answers AccessDeniedException, not a validation error"
2711        );
2712    }
2713}