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    if dockerfile_from_ref(task).is_none() {
613        return Err(Error::invalid_arg(
614            "the task Dockerfile has no FROM, so there is no image to append the agentd \
615             stanza to and no base image to pair with it. Wrap the Dockerfile the task \
616             builds from, or pass `FROM <image>` for a task that names only an image."
617                .to_string(),
618        ));
619    }
620    let scan = Instructions::scan(task);
621    if let Some(terminator) = scan.open_heredoc {
622        return Err(Error::invalid_arg(format!(
623            "the task Dockerfile ends inside a heredoc that is never terminated (no line \
624             {terminator:?} closes it), so every line appended after it — the whole agentd \
625             stanza — would become the heredoc's body. The image would build with no daemon \
626             in it and fail as a run-hook timeout. Terminate the heredoc."
627        )));
628    }
629    if scan.continued {
630        return Err(Error::invalid_arg(format!(
631            "the task Dockerfile's last instruction ends with a line continuation ({:?}), so \
632             the first line appended after it — the agentd stanza's `COPY agentd /agentd` — \
633             would be joined into that instruction instead of running. The image would build \
634             with no daemon in it and fail as a run-hook timeout. Finish the instruction, or \
635             drop the trailing {:?}.",
636            scan.escape, scan.escape,
637        )));
638    }
639    require_keepalive_under_idle_timeout(crate::session::exec::DEFAULT_STREAM_IDLE_TIMEOUT, task)?;
640    super::require_valid_port("port", opts.port)?;
641    let workdir = opts.workdir.as_deref().filter(|dir| !dir.is_empty());
642    if let Some(dir) = workdir
643        && (!dir.starts_with('/') || dir.chars().any(|c| c.is_whitespace() || c.is_control()))
644    {
645        return Err(Error::invalid_arg(format!(
646            "the workdir {dir:?} is not one absolute path. The stanza writes it as \
647             `RUN mkdir -p {dir}` and `WORKDIR {dir}`: a relative path resolves against \
648             whatever WORKDIR the task left, whitespace splits the mkdir into several \
649             directories, and a line break writes an instruction nobody reviewed. Pass an \
650             absolute path such as /workspace."
651        )));
652    }
653    if opts.inherit_workdir && workdir.is_none() && !dockerfile_declares_workdir(task) {
654        return Err(Error::invalid_arg(
655            "inherit_workdir was requested but the task Dockerfile sets no WORKDIR and no \
656             workdir option was given, so there is nothing to inherit: every exec with no cwd \
657             would run in `/`, and every relative path in it would resolve there. Pass a \
658             workdir, or set WORKDIR in the task Dockerfile."
659                .to_string(),
660        ));
661    }
662
663    let stanza = agentd_stanza(opts.port, workdir, None);
664    let mut wrapped = String::with_capacity(task.len() + stanza.len() + 16);
665    wrapped.push_str(task);
666    if !task.ends_with('\n') {
667        wrapped.push('\n');
668    }
669    if scan
670        .last_user
671        .as_deref()
672        .is_some_and(|user| !is_root_user(user))
673    {
674        wrapped.push_str("USER root\n");
675    }
676    wrapped.push_str(&stanza);
677    Ok(wrapped)
678}
679
680/// Whether a `USER` value names root: `root` or `0`, with no group or a root group.
681///
682/// Anything else is not root, including a value built from a variable — the scan cannot
683/// expand `${TASK_USER}`, and restoring root for a value that turns out to be root costs one
684/// redundant line.
685fn is_root_user(value: &str) -> bool {
686    let is_root = |part: &str| part == "root" || part == "0";
687    match value.split_once(':') {
688        Some((user, group)) => is_root(user) && is_root(group),
689        None => is_root(value),
690    }
691}
692
693/// Whether any line of `dockerfile` is a `WORKDIR` with an argument.
694fn dockerfile_declares_workdir(dockerfile: &str) -> bool {
695    dockerfile.lines().any(|line| {
696        let mut words = line.split_whitespace();
697        words
698            .next()
699            .is_some_and(|first| first.eq_ignore_ascii_case("WORKDIR"))
700            && words.next().is_some()
701    })
702}
703
704/// What [`wrap_dockerfile`] needs to know about how a Dockerfile's instructions end.
705struct Instructions {
706    /// The escape character: `\` unless an `# escape=` directive chose a backtick.
707    escape: char,
708    /// The text ends inside a line continuation.
709    continued: bool,
710    /// The terminator of a heredoc the text never closes.
711    open_heredoc: Option<String>,
712    /// The value of the last `USER` instruction.
713    last_user: Option<String>,
714}
715
716impl Instructions {
717    /// Reads the parser directives, then every logical instruction: continuation lines
718    /// joined, blank and comment lines skipped (inside a continuation too, as the parser
719    /// does), heredoc bodies consumed up to their terminators.
720    fn scan(dockerfile: &str) -> Self {
721        let escape = escape_directive(dockerfile);
722        let mut heredocs: std::collections::VecDeque<(String, bool)> = Default::default();
723        let mut pending = String::new();
724        let mut continued = false;
725        let mut last_user = None;
726        for line in dockerfile.lines() {
727            if let Some((terminator, strip_tabs)) = heredocs.front() {
728                let candidate = if *strip_tabs {
729                    line.trim_start_matches('\t')
730                } else {
731                    line
732                };
733                if candidate.trim_end_matches('\r') == terminator {
734                    heredocs.pop_front();
735                }
736                continue;
737            }
738            let trimmed = line.trim();
739            if trimmed.is_empty() || trimmed.starts_with('#') {
740                continue;
741            }
742            let body = line.trim_end();
743            if let Some(joined) = body.strip_suffix(escape) {
744                pending.push_str(joined);
745                pending.push(' ');
746                continued = true;
747                continue;
748            }
749            continued = false;
750            pending.push_str(body);
751            let instruction = std::mem::take(&mut pending);
752            let mut words = instruction.split_whitespace();
753            let Some(keyword) = words.next() else {
754                continue;
755            };
756            if keyword.eq_ignore_ascii_case("USER") {
757                last_user = words.next().map(str::to_string);
758            } else if ["RUN", "COPY", "ADD"]
759                .iter()
760                .any(|name| keyword.eq_ignore_ascii_case(name))
761            {
762                heredocs.extend(words.filter_map(heredoc_marker));
763            }
764        }
765        Self {
766            escape,
767            continued,
768            open_heredoc: heredocs.pop_front().map(|(terminator, _)| terminator),
769            last_user,
770        }
771    }
772}
773
774/// The escape character a Dockerfile's `# escape=` parser directive selects, or `\`.
775///
776/// Directives are only read at the very top: the first line that is not one — an
777/// instruction, a blank line, or an ordinary comment — ends them.
778fn escape_directive(dockerfile: &str) -> char {
779    for line in dockerfile.lines() {
780        let Some(directive) = line.trim().strip_prefix('#') else {
781            break;
782        };
783        let Some((key, value)) = directive.split_once('=') else {
784            break;
785        };
786        let key = key.trim().to_ascii_lowercase();
787        if key == "escape" {
788            return match value.trim() {
789                "`" => '`',
790                _ => '\\',
791            };
792        }
793        if !["syntax", "check"].contains(&key.as_str()) {
794            break;
795        }
796    }
797    '\\'
798}
799
800/// The terminator a heredoc marker word opens, and whether it strips leading tabs (`<<-`).
801///
802/// `<<EOF`, `<<-EOF`, `<<"EOF"`, `<<'EOF'`; not the here-string `<<<`, and not a bare `<<`.
803fn heredoc_marker(word: &str) -> Option<(String, bool)> {
804    let rest = word.strip_prefix("<<")?;
805    if rest.starts_with('<') {
806        return None;
807    }
808    let (rest, strip_tabs) = match rest.strip_prefix('-') {
809        Some(rest) => (rest, true),
810        None => (rest, false),
811    };
812    let name = rest
813        .strip_prefix('"')
814        .and_then(|name| name.strip_suffix('"'))
815        .or_else(|| {
816            rest.strip_prefix('\'')
817                .and_then(|name| name.strip_suffix('\''))
818        })
819        .unwrap_or(rest);
820    let valid = name
821        .chars()
822        .next()
823        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
824        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
825    valid.then(|| (name.to_string(), strip_tabs))
826}
827
828/// The image ref in a Dockerfile's first `FROM`, or `None` when it has none.
829///
830/// Deliberately loose on whitespace and case, and it ignores `--platform=` and `AS name`
831/// decoration, because the check exists to catch a base that disagrees rather than to
832/// validate Dockerfile syntax.
833///
834/// Split-and-scan rather than a regex: the pattern is "first token after FROM on a line
835/// whose first word is FROM", which `split_whitespace` states more directly than a
836/// pattern string would. (`regex-lite` is available if this ever grows.)
837pub fn dockerfile_from_ref(dockerfile: &str) -> Option<&str> {
838    for line in dockerfile.lines() {
839        let mut words = line.split_whitespace();
840        let Some(first) = words.next() else { continue };
841        if !first.eq_ignore_ascii_case("FROM") {
842            continue;
843        }
844        // Skip flag decoration such as `--platform=linux/arm64`.
845        return words.find(|word| !word.starts_with("--"));
846    }
847    None
848}
849
850/// Rejects working-directory inheritance when nothing declares one.
851///
852/// Measured 2026-08-05: `al2023-minimal`, `python:3.12-slim`, and `node:20-slim` all leave
853/// `WorkingDir` empty, so "inherit the image WORKDIR" inherits `/` and every relative path
854/// in the caller's commands resolves somewhere they did not mean.
855///
856/// Rejected rather than warned because the symptom appears in the **guest, one build cycle
857/// later**, as commands running in the wrong directory rather than as anything about
858/// `WORKDIR`.
859pub fn require_workdir(base: &BaseImage, dockerfile: Option<&str>) -> Result<(), Error> {
860    if !base.working_dir.is_empty() {
861        return Ok(());
862    }
863    let declares_workdir = dockerfile.is_some_and(|text| {
864        text.lines().any(|line| {
865            let mut words = line.split_whitespace();
866            words
867                .next()
868                .is_some_and(|first| first.eq_ignore_ascii_case("WORKDIR"))
869                && words.next().is_some()
870        })
871    });
872    if declares_workdir {
873        return Ok(());
874    }
875    Err(Error::invalid_arg(format!(
876        "inherit_workdir was requested but base image {:?} declares no WorkingDir and the \
877         Dockerfile sets none. Most public ARM64 base images leave it empty \
878         (docs/PLATFORM.md, 'Most public ARM64 base images have no WORKDIR'), so there is \
879         nothing to inherit and every relative path would resolve against `/`. Pass a workdir \
880         to default_dockerfile, or set WORKDIR in your own Dockerfile.",
881        base.name
882    )))
883}
884
885/// The port in a Dockerfile's last `ENV AGENTD_PORT=`, or `None` when it sets none.
886///
887/// Last rather than first: a later `ENV` of the same name wins at build time, so the last
888/// one is what the daemon reads. Accepts `ENV AGENTD_PORT=9000` and the legacy
889/// `ENV AGENTD_PORT 9000` spelling, since both set the variable and a guard that only
890/// understands one form passes the file it cannot parse.
891///
892/// Split-and-scan for the same reason [`dockerfile_from_ref`] is: `split_whitespace`
893/// states the pattern more directly than a regex string would here.
894pub fn dockerfile_agentd_port(dockerfile: &str) -> Option<u16> {
895    let mut found = None;
896    for line in dockerfile.lines() {
897        let mut words = line.split_whitespace();
898        let Some(first) = words.next() else { continue };
899        if !first.eq_ignore_ascii_case("ENV") {
900            continue;
901        }
902        let Some(assignment) = words.next() else {
903            continue;
904        };
905        let value = match assignment.split_once('=') {
906            Some(("AGENTD_PORT", value)) => value,
907            Some(_) => continue,
908            // `ENV AGENTD_PORT 9000`: the value is the next word.
909            None if assignment == "AGENTD_PORT" => match words.next() {
910                Some(value) => value,
911                None => continue,
912            },
913            None => continue,
914        };
915        // An unparseable value is not this guard's business: the daemon keeps its default
916        // for one (`crates/agentd/src/config.rs:118`), so there is no disagreement to report.
917        if let Ok(port) = value.parse() {
918            found = Some(port);
919        }
920    }
921    found
922}
923
924/// Rejects a Dockerfile whose `AGENTD_PORT` disagrees with the port the create call sends
925/// as `hooks.port`.
926///
927/// The two are set independently — `hooks.port` comes from `ControlPlane::port`, the
928/// variable from the caller's own Dockerfile — and the platform calls its build-time
929/// `ready`/`validate` hooks on the port in the create call. A guest listening elsewhere
930/// answers nothing, so the build fails.
931///
932/// Rejected rather than warned because the failure points away from its cause: the docker
933/// build succeeds, the log group holds a clean build *and* the daemon's own "agentd
934/// listening" line, and the image still lands in `CREATE_FAILED`. Neither
935/// `GetMicrovmImage` nor the build log names the port — only
936/// `GetMicrovmImageVersion`'s `hooks.port` does, compared by hand against the Dockerfile.
937///
938/// A Dockerfile that sets no `AGENTD_PORT` is checked against
939/// [`DEFAULT_AGENT_PORT`](crate::control::DEFAULT_AGENT_PORT) rather than passed, because
940/// silence is not neutral: `Config::from_env` keeps its own default for an unset variable
941/// (`crates/agentd/src/config.rs:118`, default `crates/agentd/src/config.rs:84`), so the guest listens on
942/// 9000 whether or not the Dockerfile mentions a port. Against a client that changed its
943/// port, the absent variable produces exactly the measured failure — and produces it for a
944/// caller who never typed a port anywhere, which is the harder version to diagnose.
945pub fn require_matching_agentd_port(port: u16, dockerfile: &str) -> Result<(), Error> {
946    // An unparseable value lands here too, and belongs here: the daemon warns and keeps the
947    // same default (`crates/agentd/src/config.rs:174-179`), so both spellings of "the Dockerfile
948    // named no usable port" have the same consequence in the guest.
949    let Some(found) = dockerfile_agentd_port(dockerfile) else {
950        if port == super::DEFAULT_AGENT_PORT {
951            return Ok(());
952        }
953        return Err(Error::invalid_arg(format!(
954            "this client sends hooks.port={port} but the Dockerfile sets no usable \
955             AGENTD_PORT, so the daemon will listen on its own default of {default}. These \
956             must agree: the platform calls the build-time ready/validate hooks on the port \
957             in the create call, and a daemon listening on {default} answers none of them — \
958             the docker build succeeds, the daemon logs that it is listening, and the image \
959             still fails with CREATE_FAILED naming no port. Add ENV AGENTD_PORT={port} to \
960             the Dockerfile, or build it with default_dockerfile, which derives the value \
961             from the same port.",
962            default = super::DEFAULT_AGENT_PORT,
963        )));
964    };
965    if found == port {
966        return Ok(());
967    }
968    Err(Error::invalid_arg(format!(
969        "the Dockerfile sets ENV AGENTD_PORT={found} but this client sends hooks.port={port}. \
970         These must agree: the platform calls the build-time ready/validate hooks on the port \
971         in the create call, and a daemon listening on {found} answers none of them — the \
972         docker build succeeds, the daemon logs that it is listening, and the image still \
973         fails with CREATE_FAILED naming no port. Set ENV AGENTD_PORT={port} in the \
974         Dockerfile, or build it with default_dockerfile, which derives the value from the \
975         same port."
976    )))
977}
978
979/// The seconds in a Dockerfile's last `ENV AGENTD_SSE_KEEPALIVE_SECS=`, or `None` when it
980/// sets none.
981///
982/// Same shape and same reasoning as [`dockerfile_agentd_port`]: last assignment wins, both
983/// `ENV` spellings, and an unparseable value reads as absent because the daemon warns and
984/// keeps its default for one (`crates/agentd/src/config.rs:174-179`).
985pub fn dockerfile_env_u64(dockerfile: &str, key: &str) -> Option<u64> {
986    let mut found = None;
987    for line in dockerfile.lines() {
988        let mut words = line.split_whitespace();
989        let Some(first) = words.next() else { continue };
990        if !first.eq_ignore_ascii_case("ENV") {
991            continue;
992        }
993        let Some(assignment) = words.next() else {
994            continue;
995        };
996        let value = match assignment.split_once('=') {
997            Some((name, value)) if name == key => value,
998            Some(_) => continue,
999            None if assignment == key => match words.next() {
1000                Some(value) => value,
1001                None => continue,
1002            },
1003            None => continue,
1004        };
1005        if let Ok(parsed) = value.parse() {
1006            found = Some(parsed);
1007        }
1008    }
1009    found
1010}
1011
1012/// Rejects a Dockerfile whose `AGENTD_SSE_KEEPALIVE_SECS` is not shorter than the client's
1013/// stream idle timeout.
1014///
1015/// The fourth pair of this shape, found by sweeping for the other three. The daemon's SSE
1016/// keepalive interval and the client's tolerance for silence are set in different
1017/// repositories of truth — the interval in the caller's Dockerfile
1018/// (`crates/agentd/src/config.rs:139`, default 15s at `:95`), the tolerance in
1019/// [`DEFAULT_STREAM_IDLE_TIMEOUT`](crate::session::exec::DEFAULT_STREAM_IDLE_TIMEOUT),
1020/// which is 60s *because* it is four times that 15. Raise the interval past the tolerance
1021/// and every attached stream treats a healthy connection as dead, reconnects
1022/// `max_reconnects` times, and fails.
1023///
1024/// The failure names both numbers and misattributes one of them: the client reports that the
1025/// stream "went silent for 60s, longer than the keepalive interval"
1026/// (`crates/microvms-edges/src/session/http.rs:223-227`), where 60 is its own timeout and the
1027/// keepalive interval is the number it does not know. So a reader is told the keepalive was
1028/// exceeded by a message that prints the wrong value for it, one build cycle after the
1029/// Dockerfile that caused it.
1030///
1031/// Equality is refused, not just excess: an interval exactly equal to the timeout races.
1032pub fn require_keepalive_under_idle_timeout(
1033    idle_timeout: Duration,
1034    dockerfile: &str,
1035) -> Result<(), Error> {
1036    let Some(secs) = dockerfile_env_u64(dockerfile, "AGENTD_SSE_KEEPALIVE_SECS") else {
1037        // Absent is safe here, unlike the port: the daemon's default of 15s is already
1038        // under every idle timeout this client will use, and a client that shortens its
1039        // timeout below 15s is not something a Dockerfile can be blamed for.
1040        return Ok(());
1041    };
1042    if secs < idle_timeout.as_secs() {
1043        return Ok(());
1044    }
1045    Err(Error::invalid_arg(format!(
1046        "the Dockerfile sets ENV AGENTD_SSE_KEEPALIVE_SECS={secs} but this client treats a \
1047         stream as dead after {timeout}s of silence. The keepalive must be shorter: the \
1048         daemon sends nothing between events except that keepalive, so an interval of \
1049         {secs}s makes a healthy stream look dead, and every attach reconnects until it \
1050         gives up. The error it raises then reports the client's own {timeout}s as though it \
1051         were the keepalive interval, so it names neither the Dockerfile nor {secs}. Leave \
1052         the variable unset for the daemon's 15s default, or keep it under {timeout}.",
1053        timeout = idle_timeout.as_secs(),
1054    )))
1055}
1056
1057/// The value of a Dockerfile's last `ENTRYPOINT`, or `None` when it sets none.
1058///
1059/// Last rather than first for the reason [`dockerfile_agentd_port`] gives: a later
1060/// instruction of the same name wins at build time, so the last one is what the container
1061/// runs. The value is the raw rest of the line — this scan finds a disagreement, it does
1062/// not parse Dockerfile syntax.
1063pub fn dockerfile_entrypoint(dockerfile: &str) -> Option<&str> {
1064    last_instruction_value(dockerfile, "ENTRYPOINT")
1065}
1066
1067/// The value of a Dockerfile's last `CMD`, or `None` when it sets none.
1068pub fn dockerfile_cmd(dockerfile: &str) -> Option<&str> {
1069    last_instruction_value(dockerfile, "CMD")
1070}
1071
1072/// The rest of the last line whose first word is `keyword`, trimmed, or `None`.
1073fn last_instruction_value<'a>(dockerfile: &'a str, keyword: &str) -> Option<&'a str> {
1074    let mut found = None;
1075    for line in dockerfile.lines() {
1076        let trimmed = line.trim_start();
1077        let Some(first) = trimmed.split_whitespace().next() else {
1078            continue;
1079        };
1080        if first.eq_ignore_ascii_case(keyword) {
1081            found = Some(trimmed[first.len()..].trim());
1082        }
1083    }
1084    found
1085}
1086
1087/// Whether an instruction value is the empty exec form — `[]`, with any spacing.
1088fn is_empty_exec_form(value: &str) -> bool {
1089    let mut meaningful = value.chars().filter(|c| !c.is_whitespace());
1090    meaningful.next() == Some('[') && meaningful.next() == Some(']') && meaningful.next().is_none()
1091}
1092
1093/// Rejects a Dockerfile whose image would never run the daemon: no `CMD`, or an
1094/// `ENTRYPOINT` that swallows it.
1095///
1096/// The artifact unconditionally carries the daemon as entry `agentd` ([`build_artifact`]),
1097/// and the deployment invariant is `ENTRYPOINT []` plus `CMD ["/agentd"]` — see
1098/// [`default_dockerfile`]. A caller Dockerfile with no `CMD` runs the base's own default
1099/// instead, and a non-empty `ENTRYPOINT` turns any `CMD` into that entrypoint's arguments
1100/// rather than the process. Either way the daemon never starts, the build-time
1101/// `ready`/`validate` hooks go unanswered, and the image lands in `CREATE_FAILED` — or the
1102/// launch dies as a run-hook timeout — with nothing naming `CMD`, `ENTRYPOINT`, or the
1103/// artifact entry.
1104///
1105/// Weak-form on purpose: it does **not** check that the `CMD` names a path anything was
1106/// copied to. That would be Dockerfile interpretation rather than agreement checking, and
1107/// the two mistakes people actually make are the two refused here. The unenforceable half —
1108/// a base image that starts its own background process before bootstrap — stays with
1109/// whoever builds the image (`docs/PROTOCOL.md`, "Trust boundary").
1110pub fn require_daemon_cmd(dockerfile: &str) -> Result<(), Error> {
1111    if let Some(entrypoint) = dockerfile_entrypoint(dockerfile)
1112        && !is_empty_exec_form(entrypoint)
1113    {
1114        return Err(Error::invalid_arg(format!(
1115            "the Dockerfile sets ENTRYPOINT {entrypoint}, which makes any CMD its arguments \
1116             rather than the container's process — so the daemon this client uploads never \
1117             starts. The build succeeds anyway: the ready/validate hooks just go unanswered \
1118             and the image fails as CREATE_FAILED, or the launch dies as a run-hook timeout, \
1119             and neither symptom names ENTRYPOINT. Set `ENTRYPOINT []` alongside \
1120             `CMD [\"/agentd\"]`, or build with default_dockerfile, which sets both."
1121        )));
1122    }
1123    match dockerfile_cmd(dockerfile) {
1124        Some(cmd) if !cmd.is_empty() && !is_empty_exec_form(cmd) => Ok(()),
1125        _ => Err(Error::invalid_arg(
1126            "the Dockerfile has no CMD, so the container runs the base image's default \
1127             process and the daemon this client uploads never starts. The build succeeds \
1128             anyway: the ready/validate hooks just go unanswered and the image fails as \
1129             CREATE_FAILED, or the launch dies as a run-hook timeout, and neither symptom \
1130             names CMD. Add `ENTRYPOINT []` and `CMD [\"/agentd\"]`, or build with \
1131             default_dockerfile, which sets both."
1132                .to_string(),
1133        )),
1134    }
1135}
1136
1137/// Rejects a caller Dockerfile that never mentions the lockfile the request carries.
1138///
1139/// The project files enter the artifact unconditionally once the request holds them, so a
1140/// custom Dockerfile that ignores them builds cleanly and produces an image with **no
1141/// environment layer** — and the symptom appears at launch, as every dependency
1142/// installing inside the guest, with nothing anywhere naming the `COPY` that was never
1143/// written. That is the silent-degradation shape: the caller asked for the layer, paid
1144/// the build, and got an image indistinguishable from one that never asked.
1145///
1146/// Weak-form on purpose, like [`require_daemon_cmd`]: a substring test for the lockfile's
1147/// name rather than parsing `COPY` syntax, because the check exists to catch a Dockerfile
1148/// that plainly ignores the files, not to validate how it consumes them.
1149pub fn require_project_install(project: &ProjectFiles, dockerfile: &str) -> Result<(), Error> {
1150    let lockfile = project.ecosystem.lockfile_name();
1151    if dockerfile.contains(lockfile) {
1152        return Ok(());
1153    }
1154    Err(Error::invalid_arg(format!(
1155        "the request carries project files ({lockfile} and {manifest}) but the Dockerfile \
1156         never mentions {lockfile}, so the image would bake no environment layer: the build \
1157         succeeds, and every launch still installs dependencies inside the guest with \
1158         nothing naming the COPY that was never written. Copy the pair and install from \
1159         the lockfile ({install}), or build with default_dockerfile, which derives both \
1160         lines — or drop the project files if the layer is not wanted.",
1161        manifest = project.ecosystem.manifest_name(),
1162        install = match project.ecosystem {
1163            Ecosystem::Uv => "uv sync --locked",
1164            Ecosystem::Npm => "npm ci",
1165            Ecosystem::Cargo => "cargo fetch --locked",
1166        },
1167    )))
1168}
1169
1170/// Rejects a Dockerfile whose `FROM` is not the selected base image.
1171///
1172/// The build runs the Dockerfile *on top of* the base named in `baseImageArn`, so the two
1173/// disagreeing produces an image built from something other than the platform base whose
1174/// behaviour every `docs/PLATFORM.md` measurement describes — and nothing in the result
1175/// says so.
1176pub fn require_matching_from(base: &BaseImage, dockerfile: &str) -> Result<(), Error> {
1177    let Some(found) = dockerfile_from_ref(dockerfile) else {
1178        // No FROM at all is not this check's business: the build will say so, and a
1179        // Dockerfile validator is not what this is.
1180        return Ok(());
1181    };
1182    if found == base.docker_ref {
1183        return Ok(());
1184    }
1185    // The digest-pinned spelling of the same ref: `<docker_ref>@sha256:<64 hex>`. A digest
1186    // names one specific manifest of the ref this check already accepts, so it is a stricter
1187    // statement of agreement rather than a disagreement — a supply-chain-conscious caller
1188    // pins exactly this way, and refusing it would force them to un-pin to pass. The tag
1189    // must still be present and identical: `alpine@sha256:...` against a docker_ref of
1190    // `alpine:3` is a different claim and stays refused.
1191    if let Some(digest) = found
1192        .strip_prefix(base.docker_ref.as_str())
1193        .and_then(|rest| rest.strip_prefix("@sha256:"))
1194        && digest.len() == 64
1195        && digest.bytes().all(|b| b.is_ascii_hexdigit())
1196    {
1197        return Ok(());
1198    }
1199    Err(Error::invalid_arg(format!(
1200        "the Dockerfile's FROM is {found:?} but base image {:?} pairs with {:?}. These must \
1201         agree: baseImageArn and the FROM select the same base, and a mismatch builds against \
1202         a base none of the measured platform behaviour applies to. Use default_dockerfile \
1203         with this base, or pass a BaseImage whose docker_ref matches.",
1204        base.name, base.docker_ref
1205    )))
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210    use super::*;
1211    use crate::testing::aarch64_daemon;
1212
1213    const DEFAULT_AGENT_PORT_FOR_TESTS: u16 = crate::control::DEFAULT_AGENT_PORT;
1214
1215    /// The archive holds exactly the two entries the build expects, named as the build
1216    /// looks for them.
1217    #[test]
1218    fn the_artifact_holds_a_dockerfile_and_the_daemon() {
1219        let bytes =
1220            build_artifact(&aarch64_daemon(b"fake daemon"), "FROM scratch\n", None).expect("zips");
1221        let mut archive =
1222            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1223
1224        let mut names: Vec<String> = (0..archive.len())
1225            .map(|index| {
1226                archive
1227                    .by_index(index)
1228                    .expect("entry")
1229                    .name()
1230                    .expect("a name")
1231                    .into_owned()
1232            })
1233            .collect();
1234        names.sort();
1235        assert_eq!(names, ["Dockerfile", "agentd"]);
1236    }
1237
1238    /// **BIND-20 where the daemon enters an artifact (#257).** An x86_64 ELF, a script and no bytes
1239    /// at all are each refused as a precondition naming what the bytes are, so the bindings'
1240    /// two-step path (`build_artifact`, then the caller's own upload) never uploads one.
1241    ///
1242    /// **Falsification**: drop the `require_aarch64` call from `build_artifact_with_context`
1243    /// and all three zip.
1244    #[test]
1245    fn an_artifact_refuses_a_daemon_that_is_not_an_aarch64_elf() {
1246        for (binary, why) in [
1247            (crate::testing::elf_daemon(0x3E, b"x86"), "ELF machine 0x3e"),
1248            (b"#!/bin/sh\n".to_vec(), "not an ELF binary"),
1249            (Vec::new(), "not an ELF binary"),
1250        ] {
1251            let error = build_artifact(&binary, "FROM scratch\n", None).expect_err(why);
1252            assert_eq!(error.kind(), ErrorKind::Precondition, "{error}");
1253            assert!(error.to_string().contains(why), "{error}");
1254        }
1255    }
1256
1257    /// The daemon entry carries mode 0755, and the Dockerfile entry does not have to.
1258    ///
1259    /// Read back out of the archive rather than asserted on the constant, because the
1260    /// constant being right and the zip entry carrying it are two different facts — and it
1261    /// is the second one that turns into a run-hook timeout.
1262    ///
1263    /// The permission bits are masked out of the returned mode: `zip` reports the whole
1264    /// Unix mode, so the entry reads as `0o100755` — `S_IFREG | 0o755`. Comparing the
1265    /// unmasked value against `0o755` fails while the archive is perfectly correct, which
1266    /// is a test that would have sent someone to debug the writer.
1267    #[test]
1268    fn the_daemon_entry_carries_the_execute_bit() {
1269        let bytes =
1270            build_artifact(&aarch64_daemon(b"binary"), "FROM scratch\n", None).expect("zips");
1271        let mut archive =
1272            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1273        let mode = archive
1274            .by_name("agentd")
1275            .expect("the daemon entry")
1276            .unix_mode()
1277            .expect("a mode was recorded");
1278        assert_eq!(
1279            mode & 0o777,
1280            AGENTD_MODE,
1281            "a non-executable binary surfaces as a run-hook timeout, not a permission error \
1282             (mode was {mode:o})"
1283        );
1284        assert!(
1285            mode & 0o111 != 0,
1286            "the execute bit is the whole point: {mode:o}"
1287        );
1288    }
1289
1290    /// The bytes round-trip. A zip that holds a truncated or re-encoded binary produces an
1291    /// image whose CMD fails for a reason no message names.
1292    #[test]
1293    fn the_daemon_bytes_survive_the_round_trip() {
1294        use std::io::Read as _;
1295
1296        // Deliberately includes a NUL and a high byte, which is what a real ELF has and
1297        // what a text-mode write would mangle.
1298        let binary = aarch64_daemon(&(0u8..=255).cycle().take(4096).collect::<Vec<u8>>());
1299        let bytes = build_artifact(&binary, "FROM scratch\n", None).expect("zips");
1300        let mut archive =
1301            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1302        let mut read = Vec::new();
1303        archive
1304            .by_name("agentd")
1305            .expect("entry")
1306            .read_to_end(&mut read)
1307            .expect("reads");
1308        assert_eq!(read, binary);
1309    }
1310
1311    /// **AC-2-3, the byte-scan guard.** The agent token must not appear anywhere in the
1312    /// artifact's raw bytes — including the project-file entries #74 added.
1313    ///
1314    /// A byte scan rather than an API review, because the leak this guards against is a
1315    /// *value* turning up somewhere — in the Dockerfile as an `ENV`, in a baked config
1316    /// file, in a stray argument — not a parameter being declared. Scanning the compressed
1317    /// bytes and the decompressed entries both, since deflate would hide a literal from a
1318    /// naive scan of the archive. The artifact under scan carries a full project-file
1319    /// pair, and the entry count is asserted so the scan cannot silently sweep fewer
1320    /// members than the artifact holds.
1321    ///
1322    /// **Falsification** — add the token to the Dockerfile (`ENV AGENT_TOKEN=…`, the
1323    /// plausible mistake) and the decompressed scan fails. Re-run for the #74 members
1324    /// (2026-08-31): append the token to the lockfile entry inside `build_artifact` and
1325    /// the per-entry scan fails naming `uv.lock`; it was restored.
1326    #[test]
1327    fn the_artifact_never_carries_the_agent_token() {
1328        use std::io::Read as _;
1329
1330        let token = "s3cr3t-agent-token-do-not-bake-me";
1331        let dockerfile = default_dockerfile(9000, Some("/opt/work"), &BaseImage::al2023(), None);
1332        assert!(
1333            !dockerfile.contains(token),
1334            "the default Dockerfile must not mention a token"
1335        );
1336
1337        let project = ProjectFiles {
1338            ecosystem: Ecosystem::Uv,
1339            manifest: b"[project]\nname = \"demo\"\n".to_vec(),
1340            lockfile: b"version = 1\n".to_vec(),
1341        };
1342        let bytes =
1343            build_artifact(&aarch64_daemon(b"binary"), &dockerfile, Some(&project)).expect("zips");
1344        assert!(
1345            !bytes
1346                .windows(token.len())
1347                .any(|window| window == token.as_bytes()),
1348            "the token appears in the artifact's raw bytes"
1349        );
1350
1351        let mut archive =
1352            zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1353        assert_eq!(
1354            archive.len(),
1355            4,
1356            "the scan below must sweep every member this artifact can hold"
1357        );
1358        for index in 0..archive.len() {
1359            let mut entry = archive.by_index(index).expect("entry");
1360            let name = entry.name().expect("a name").into_owned();
1361            let mut content = Vec::new();
1362            entry.read_to_end(&mut content).expect("reads");
1363            assert!(
1364                !content
1365                    .windows(token.len())
1366                    .any(|window| window == token.as_bytes()),
1367                "the token appears inside {name} — the image snapshot is shared by every VM \
1368                 launched from it, so a token here is a token shared with every VM"
1369            );
1370        }
1371    }
1372
1373    /// **#74, the build-context half.** A project's manifest and lockfile enter the
1374    /// archive under their ecosystem's fixed names, at the root beside the Dockerfile —
1375    /// the build context root, where the generated `COPY` finds them — and their bytes
1376    /// survive the round trip.
1377    #[test]
1378    fn project_files_enter_the_artifact_under_their_ecosystem_names() {
1379        use std::io::Read as _;
1380
1381        for (ecosystem, manifest_name, lockfile_name) in [
1382            (Ecosystem::Uv, "pyproject.toml", "uv.lock"),
1383            (Ecosystem::Npm, "package.json", "package-lock.json"),
1384            (Ecosystem::Cargo, "Cargo.toml", "Cargo.lock"),
1385        ] {
1386            let project = ProjectFiles {
1387                ecosystem,
1388                manifest: b"manifest-bytes".to_vec(),
1389                lockfile: b"lockfile-bytes".to_vec(),
1390            };
1391            let bytes =
1392                build_artifact(&aarch64_daemon(b"binary"), "FROM scratch\n", Some(&project))
1393                    .expect("zips");
1394            let mut archive =
1395                zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a readable zip");
1396
1397            let mut names: Vec<String> = (0..archive.len())
1398                .map(|index| {
1399                    archive
1400                        .by_index(index)
1401                        .expect("entry")
1402                        .name()
1403                        .expect("a name")
1404                        .into_owned()
1405                })
1406                .collect();
1407            names.sort();
1408            let mut expected = vec![
1409                "Dockerfile".to_string(),
1410                "agentd".to_string(),
1411                manifest_name.to_string(),
1412                lockfile_name.to_string(),
1413            ];
1414            expected.sort();
1415            assert_eq!(names, expected, "{ecosystem:?}");
1416
1417            let mut lockfile = Vec::new();
1418            archive
1419                .by_name(lockfile_name)
1420                .expect("the lockfile entry")
1421                .read_to_end(&mut lockfile)
1422                .expect("reads");
1423            assert_eq!(lockfile, b"lockfile-bytes", "{ecosystem:?}");
1424        }
1425    }
1426
1427    /// **#74's TRAP-5 design guard, the compile surface.** [`ProjectFiles`] has no field
1428    /// that could carry an entry *name* — the names come from the [`Ecosystem`] variant —
1429    /// so a caller cannot put `.env` or a credentials file into the shared snapshot
1430    /// through this type. Asserted by destructuring, the same shape as TRAP-1's
1431    /// `no_request_type_carries_a_caller_supplied_client_token`: a `name`/`path` field
1432    /// added later fails to compile this test.
1433    #[test]
1434    fn project_files_carry_no_caller_named_entry() {
1435        let ProjectFiles {
1436            ecosystem: _,
1437            manifest: _,
1438            lockfile: _,
1439        } = ProjectFiles {
1440            ecosystem: Ecosystem::Npm,
1441            manifest: Vec::new(),
1442            lockfile: Vec::new(),
1443        };
1444    }
1445
1446    /// The content hash is a pure function of the two inputs: equal inputs agree, either
1447    /// input changing changes it, and the boundary between the two inputs is part of the
1448    /// identity.
1449    ///
1450    /// The boundary case is the one worth spelling out: without length prefixes,
1451    /// `("ab", "c")` and `("a", "bc")` hash the same concatenation — and a Dockerfile
1452    /// edit could then collide with a binary edit, serving a stale image for changed
1453    /// inputs, which is the exact hazard the hash exists to close.
1454    #[test]
1455    fn the_content_hash_follows_the_inputs_and_only_the_inputs() {
1456        let hash = artifact_content_hash(b"binary-bytes", "FROM scratch\n", None);
1457        assert_eq!(
1458            hash,
1459            artifact_content_hash(b"binary-bytes", "FROM scratch\n", None)
1460        );
1461        assert_eq!(hash.len(), 64, "sha256 as lowercase hex");
1462        assert!(
1463            hash.chars()
1464                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
1465        );
1466
1467        assert_ne!(
1468            hash,
1469            artifact_content_hash(b"other-bytes", "FROM scratch\n", None)
1470        );
1471        assert_ne!(
1472            hash,
1473            artifact_content_hash(b"binary-bytes", "FROM scratch\nRUN true\n", None)
1474        );
1475        assert_ne!(
1476            artifact_content_hash(b"ab", "c", None),
1477            artifact_content_hash(b"a", "bc", None),
1478            "the input boundary is part of the identity"
1479        );
1480
1481        // The projectless digest is pinned to the exact value this function produced
1482        // before #74. Every image name `build --reuse` ever derived embeds this digest's
1483        // first twelve characters, so changing the no-project stream silently orphans
1484        // every existing reuse — the module docs call that hazard out for the zip's own
1485        // bytes, and it applies to the algorithm the same way. Recomputed independently
1486        // (Python hashlib, 2026-08-31) rather than pasted from this function's output.
1487        assert_eq!(
1488            hash, "90a0ef925a4696b0c0f142241b2c714e63f40071d0d02951e26cb2a1d8bb24fc",
1489            "the no-project digest must stay what it was before #74"
1490        );
1491    }
1492
1493    /// **#74 step 3, the key.** The project files are part of the artifact identity:
1494    /// identical pairs agree, a lockfile edit is a new identity (and so a fresh image
1495    /// name and a fresh build), and the entry names count — the same bytes under a
1496    /// different ecosystem are a different identity, because the Dockerfile that consumes
1497    /// them installs a different environment.
1498    ///
1499    /// **Falsification** — run 2026-08-31 and again 2026-09-02: the lockfile's
1500    /// `hasher.update` lines were dropped from `artifact_content_hash` and the
1501    /// lockfile-edit assertion went red (two different lockfiles, one hash — the
1502    /// stale-reuse hazard verbatim); restored.
1503    #[test]
1504    fn the_content_hash_keys_on_the_lockfile() {
1505        let project = |ecosystem, lockfile: &[u8]| ProjectFiles {
1506            ecosystem,
1507            manifest: b"[project]".to_vec(),
1508            lockfile: lockfile.to_vec(),
1509        };
1510        let hash = artifact_content_hash(
1511            b"binary",
1512            "FROM scratch\n",
1513            Some(&project(Ecosystem::Uv, b"version = 1")),
1514        );
1515        assert_eq!(
1516            hash,
1517            artifact_content_hash(
1518                b"binary",
1519                "FROM scratch\n",
1520                Some(&project(Ecosystem::Uv, b"version = 1")),
1521            ),
1522            "identical dependency files share an image"
1523        );
1524        assert_ne!(
1525            hash,
1526            artifact_content_hash(
1527                b"binary",
1528                "FROM scratch\n",
1529                Some(&project(Ecosystem::Uv, b"version = 2")),
1530            ),
1531            "a lockfile edit is a new image name and a fresh build"
1532        );
1533        assert_ne!(
1534            hash,
1535            artifact_content_hash(b"binary", "FROM scratch\n", None),
1536            "carrying a layer is a different identity from carrying none"
1537        );
1538        assert_ne!(
1539            artifact_content_hash(
1540                b"binary",
1541                "FROM scratch\n",
1542                Some(&project(Ecosystem::Npm, b"version = 1")),
1543            ),
1544            hash,
1545            "the entry names count: the same bytes under another ecosystem install a \
1546             different environment"
1547        );
1548    }
1549
1550    /// The Dockerfile's `FROM` comes from the base image, so the two cannot disagree.
1551    #[test]
1552    fn the_default_dockerfile_derives_its_from_from_the_base_image() {
1553        let base = BaseImage::al2023();
1554        let dockerfile = default_dockerfile(9000, None, &base, None);
1555        assert_eq!(
1556            dockerfile_from_ref(&dockerfile),
1557            Some(base.docker_ref.as_str())
1558        );
1559        assert!(dockerfile.contains(r#"CMD ["/agentd"]"#));
1560        assert!(
1561            dockerfile.contains("ENTRYPOINT []"),
1562            "the trust boundary rests on this line"
1563        );
1564        assert!(dockerfile.contains("ENV AGENTD_PORT=9000"));
1565    }
1566
1567    /// A workdir is written as both a `mkdir` and a `WORKDIR`, and is absent when none was
1568    /// asked for. An empty string counts as none, since that is what an unset value looks
1569    /// like coming from a CLI flag.
1570    #[test]
1571    fn a_workdir_is_created_and_set_or_absent_entirely() {
1572        let base = BaseImage::al2023();
1573        let with = default_dockerfile(9000, Some("/opt/baked-workdir"), &base, None);
1574        assert!(with.contains("RUN mkdir -p /opt/baked-workdir"));
1575        assert!(with.contains("WORKDIR /opt/baked-workdir"));
1576
1577        for none in [None, Some("")] {
1578            let without = default_dockerfile(9000, none, &base, None);
1579            assert!(!without.contains("WORKDIR"), "{without}");
1580        }
1581    }
1582
1583    /// **#74 step 2, the install.** A project Dockerfile copies the ecosystem's pair into
1584    /// the working directory and installs from the lockfile with the lockfile-faithful
1585    /// spelling — `uv sync --locked`, `npm ci`, `cargo fetch --locked` — where the
1586    /// projectless Dockerfile installs nothing (the measured pre-#74 state).
1587    ///
1588    /// **Falsification** — run 2026-08-31: the `COPY` line was dropped from
1589    /// `default_dockerfile` and the copies-its-pair assertion went red for all three
1590    /// ecosystems; restored.
1591    #[test]
1592    fn a_project_dockerfile_installs_from_the_lockfile_it_can_see() {
1593        let base = BaseImage::al2023();
1594        for (ecosystem, install) in [
1595            (Ecosystem::Uv, "uv sync --locked"),
1596            (Ecosystem::Npm, "npm ci"),
1597            (Ecosystem::Cargo, "cargo fetch --locked"),
1598        ] {
1599            let dockerfile = default_dockerfile(9000, None, &base, Some(ecosystem));
1600            assert!(
1601                dockerfile.contains(&format!(
1602                    "COPY {} {} ./",
1603                    ecosystem.manifest_name(),
1604                    ecosystem.lockfile_name(),
1605                )),
1606                "copies its pair: {dockerfile}"
1607            );
1608            assert!(dockerfile.contains(install), "{dockerfile}");
1609            // The layer needs a directory even when the caller named none, because the
1610            // install resolves everything against the current directory.
1611            assert!(
1612                dockerfile.contains(&format!("WORKDIR {DEFAULT_PROJECT_WORKDIR}")),
1613                "{dockerfile}"
1614            );
1615
1616            // A caller-named workdir is where the layer lives instead.
1617            let placed = default_dockerfile(9000, Some("/srv/app"), &base, Some(ecosystem));
1618            assert!(placed.contains("WORKDIR /srv/app"), "{placed}");
1619            assert!(!placed.contains(DEFAULT_PROJECT_WORKDIR), "{placed}");
1620        }
1621
1622        let without = default_dockerfile(9000, None, &base, None);
1623        for install in ["uv sync", "npm ci", "cargo fetch", "COPY pyproject"] {
1624            assert!(!without.contains(install), "{without}");
1625        }
1626    }
1627
1628    /// The project Dockerfile passes every guard the plain one does: the `FROM` matches
1629    /// its base, the port agrees, the daemon stays the `CMD`, and the pair it copies
1630    /// satisfies [`require_project_install`]. A derived Dockerfile that failed its own
1631    /// preflight would refuse every `--project` build at the door.
1632    #[test]
1633    fn the_project_dockerfile_passes_its_own_guards() {
1634        let base = BaseImage::al2023();
1635        for ecosystem in Ecosystem::ALL {
1636            let dockerfile = default_dockerfile(9000, None, &base, Some(ecosystem));
1637            require_matching_from(&base, &dockerfile).expect("its FROM is its base");
1638            require_matching_agentd_port(9000, &dockerfile).expect("its port agrees");
1639            require_daemon_cmd(&dockerfile).expect("the daemon is still the CMD");
1640            let project = ProjectFiles {
1641                ecosystem,
1642                manifest: Vec::new(),
1643                lockfile: Vec::new(),
1644            };
1645            require_project_install(&project, &dockerfile)
1646                .expect("it copies the pair it was derived for");
1647        }
1648    }
1649
1650    /// **#74's silent-degradation guard.** A caller Dockerfile that never mentions the
1651    /// lockfile bakes no environment layer while building cleanly — the symptom is every
1652    /// launch still installing dependencies, with nothing naming the missing `COPY` — so
1653    /// it is refused up front, naming the lockfile, the install command, and both ways
1654    /// out.
1655    ///
1656    /// **Falsification** — run 2026-08-31: the `contains` check was inverted and both
1657    /// halves went red (the ignoring Dockerfile passed, the copying one was refused);
1658    /// restored.
1659    #[test]
1660    fn a_dockerfile_that_ignores_the_project_files_is_refused() {
1661        let project = ProjectFiles {
1662            ecosystem: Ecosystem::Npm,
1663            manifest: b"{}".to_vec(),
1664            lockfile: b"{}".to_vec(),
1665        };
1666        let error = require_project_install(
1667            &project,
1668            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1669             COPY agentd /agentd\n\
1670             ENTRYPOINT []\nCMD [\"/agentd\"]\n",
1671        )
1672        .expect_err("no mention of the lockfile bakes no layer");
1673        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1674        let message = error.to_string();
1675        assert!(message.contains("package-lock.json"), "{message}");
1676        assert!(message.contains("npm ci"), "{message}");
1677        assert!(message.contains("no environment layer"), "{message}");
1678
1679        require_project_install(
1680            &project,
1681            "FROM x\nCOPY package.json package-lock.json ./\nRUN npm ci\nCMD [\"/agentd\"]\n",
1682        )
1683        .expect("a Dockerfile that copies the pair agrees");
1684    }
1685
1686    /// `FROM` parsing tolerates the decoration a real Dockerfile carries: lowercase,
1687    /// leading whitespace, a `--platform` flag, and an `AS` alias.
1688    #[test]
1689    fn the_from_parser_ignores_decoration_rather_than_validating_syntax() {
1690        assert_eq!(dockerfile_from_ref("FROM alpine\n"), Some("alpine"));
1691        assert_eq!(dockerfile_from_ref("  from alpine:3\n"), Some("alpine:3"));
1692        assert_eq!(
1693            dockerfile_from_ref("FROM --platform=linux/arm64 alpine AS build\n"),
1694            Some("alpine")
1695        );
1696        assert_eq!(dockerfile_from_ref("RUN echo from nowhere\n"), None);
1697        assert_eq!(dockerfile_from_ref(""), None);
1698    }
1699
1700    /// A `FROM` that disagrees with the base image is refused, and the message names both
1701    /// refs — the one found and the one expected — because "these must agree" without both
1702    /// values leaves the caller to guess which to change.
1703    #[test]
1704    fn a_dockerfile_from_that_disagrees_with_the_base_is_refused() {
1705        let base = BaseImage::al2023();
1706        let error = require_matching_from(&base, "FROM ubuntu:24.04\nCOPY agentd /agentd\n")
1707            .expect_err("ubuntu is not the managed base");
1708        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1709        let message = error.to_string();
1710        assert!(message.contains("ubuntu:24.04"), "{message}");
1711        assert!(message.contains(&base.docker_ref), "{message}");
1712        assert!(
1713            message.contains("none of the measured platform behaviour applies"),
1714            "{message}"
1715        );
1716
1717        require_matching_from(&base, &default_dockerfile(9000, None, &base, None))
1718            .expect("the derived Dockerfile agrees with its own base");
1719    }
1720
1721    /// A digest-pinned `FROM` of the agreeing ref passes: it names one specific manifest of
1722    /// the base this check already accepts, which is the spelling a supply-chain-conscious
1723    /// caller uses. The boundary cases stay refused — a digest on a *different* ref is still
1724    /// a disagreement, and a malformed digest is not a digest.
1725    #[test]
1726    fn a_digest_pinned_from_of_the_agreeing_ref_passes() {
1727        let base = BaseImage::al2023();
1728        let digest = "c439fb4994ea7ca529233d6256446d3f8b7b4efb58956073e015303a170011de";
1729        let pinned = format!(
1730            "FROM {}@sha256:{digest}\nCOPY agentd /agentd\n",
1731            base.docker_ref
1732        );
1733        require_matching_from(&base, &pinned).expect("a digest pin of the same ref agrees");
1734
1735        require_matching_from(&base, &format!("FROM ubuntu:24.04@sha256:{digest}\n"))
1736            .expect_err("a digest does not launder a different ref");
1737        require_matching_from(&base, &format!("FROM {}@sha256:abc123\n", base.docker_ref))
1738            .expect_err("a 6-character digest is not a digest");
1739        require_matching_from(
1740            &base,
1741            &format!("FROM {}@sha256:{}\n", base.docker_ref, "g".repeat(64)),
1742        )
1743        .expect_err("64 non-hex characters are not a digest");
1744    }
1745
1746    /// A Dockerfile with no `FROM` is not this check's business: the build will say so, and
1747    /// refusing here would be a Dockerfile validator rather than an agreement check.
1748    #[test]
1749    fn a_dockerfile_with_no_from_is_left_to_the_build() {
1750        require_matching_from(&BaseImage::al2023(), "COPY agentd /agentd\n")
1751            .expect("no FROM is not a disagreement");
1752    }
1753
1754    /// The measured case, reproduced from the Dockerfile that spent it: a hand-written
1755    /// guest Dockerfile carrying `ENV AGENTD_PORT=8080` — the plausible port, and the wrong
1756    /// one — against a client sending `hooks.port=9000`. The build succeeds, the daemon logs
1757    /// `agentd listening`, and the image lands in `CREATE_FAILED` naming no port.
1758    #[test]
1759    fn a_dockerfile_port_that_disagrees_with_the_hook_port_is_refused() {
1760        let error = require_matching_agentd_port(
1761            crate::control::DEFAULT_AGENT_PORT,
1762            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1763             COPY agentd /agentd\n\
1764             ENV AGENTD_PORT=8080\n\
1765             EXPOSE 8080\n\
1766             CMD [\"/agentd\"]\n",
1767        )
1768        .expect_err("8080 is not the port the create call sends");
1769        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1770        let message = error.to_string();
1771        assert!(message.contains("8080"), "{message}");
1772        assert!(message.contains("9000"), "{message}");
1773        // The remedy is what a reader acts on, and the diagnostic's value is naming the
1774        // symptom that points away from the cause.
1775        assert!(message.contains("CREATE_FAILED"), "{message}");
1776        assert!(message.contains("ready/validate"), "{message}");
1777
1778        require_matching_agentd_port(
1779            crate::control::DEFAULT_AGENT_PORT,
1780            &default_dockerfile(
1781                crate::control::DEFAULT_AGENT_PORT,
1782                Some("/work"),
1783                &BaseImage::al2023(),
1784                None,
1785            ),
1786        )
1787        .expect("the derived Dockerfile agrees with the port it was derived from");
1788    }
1789
1790    /// Both `ENV` spellings set the variable, so a guard reading only `KEY=VALUE` would pass
1791    /// the legacy form it could not parse. The last assignment wins, as it does at build
1792    /// time.
1793    #[test]
1794    fn the_port_scan_reads_both_env_spellings_and_takes_the_last() {
1795        assert_eq!(dockerfile_agentd_port("ENV AGENTD_PORT=9000\n"), Some(9000));
1796        assert_eq!(dockerfile_agentd_port("ENV AGENTD_PORT 8080\n"), Some(8080));
1797        assert_eq!(dockerfile_agentd_port("env agentd_port=7000\n"), None);
1798        assert_eq!(
1799            dockerfile_agentd_port("ENV AGENTD_PORT=8080\nENV AGENTD_PORT=9000\n"),
1800            Some(9000),
1801        );
1802        assert_eq!(dockerfile_agentd_port("ENV AGENTD_LOG=info\n"), None);
1803        // Neither a missing variable nor an unparseable one is a disagreement: the daemon
1804        // keeps its own default for both (`crates/agentd/src/config.rs:118`).
1805        assert_eq!(
1806            dockerfile_agentd_port("FROM x\nCOPY agentd /agentd\n"),
1807            None
1808        );
1809        assert_eq!(dockerfile_agentd_port("ENV AGENTD_PORT=nine\n"), None);
1810        require_matching_agentd_port(
1811            crate::control::DEFAULT_AGENT_PORT,
1812            "FROM x\nCOPY agentd /agentd\n",
1813        )
1814        .expect("no variable agrees with the default, which is what the daemon will use");
1815    }
1816
1817    /// The other half of the pair, and the harder one to diagnose: a Dockerfile that names
1818    /// no port at all against a client that moved off the default. Silence is not neutral —
1819    /// `Config::from_env` keeps `9000` for an unset variable — so the guest listens on 9000
1820    /// while the hooks are dialled on the client's port, which is the measured failure with
1821    /// nothing in the Dockerfile to point at.
1822    #[test]
1823    fn a_dockerfile_naming_no_port_is_refused_when_the_client_moved_off_the_default() {
1824        let error = require_matching_agentd_port(
1825            8080,
1826            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1827             COPY agentd /agentd\n\
1828             CMD [\"/agentd\"]\n",
1829        )
1830        .expect_err("a silent Dockerfile leaves the daemon on 9000, not on 8080");
1831        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1832        let message = error.to_string();
1833        assert!(message.contains("8080"), "{message}");
1834        assert!(
1835            message.contains(&crate::control::DEFAULT_AGENT_PORT.to_string()),
1836            "the daemon's default is the value the reader has to learn: {message}"
1837        );
1838        assert!(message.contains("CREATE_FAILED"), "{message}");
1839        assert!(message.contains("ready/validate"), "{message}");
1840
1841        // An unparseable value has the same consequence in the guest as no value, so it is
1842        // refused for the same reason rather than passed as "not this guard's business".
1843        require_matching_agentd_port(8080, "FROM x\nENV AGENTD_PORT=nine\n")
1844            .expect_err("a value the daemon cannot parse leaves it on its own default");
1845
1846        // The default-port client is the common case and stays silent: the Dockerfile that
1847        // says nothing and the client that changed nothing already agree.
1848        require_matching_agentd_port(
1849            crate::control::DEFAULT_AGENT_PORT,
1850            "FROM x\nCOPY agentd /agentd\n",
1851        )
1852        .expect("silence agrees with the default");
1853    }
1854
1855    /// The fourth pair of the `FROM`/`WORKDIR`/`AGENTD_PORT` shape, found by sweeping for
1856    /// the others: a keepalive interval the client's silence tolerance is shorter than. The
1857    /// resulting error prints the client's own timeout as though it were the keepalive, so
1858    /// the number a reader would search for never appears.
1859    #[test]
1860    fn a_keepalive_at_or_over_the_client_idle_timeout_is_refused() {
1861        let timeout = crate::session::exec::DEFAULT_STREAM_IDLE_TIMEOUT;
1862        assert_eq!(timeout.as_secs(), 60, "the guard's arithmetic assumes this");
1863
1864        let error =
1865            require_keepalive_under_idle_timeout(timeout, "ENV AGENTD_SSE_KEEPALIVE_SECS=90\n")
1866                .expect_err("90s of scheduled silence exceeds a 60s tolerance");
1867        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1868        let message = error.to_string();
1869        assert!(message.contains("90"), "{message}");
1870        assert!(message.contains("60"), "{message}");
1871
1872        // Equality races rather than passing: the timeout fires on the same tick the
1873        // keepalive is due.
1874        require_keepalive_under_idle_timeout(timeout, "ENV AGENTD_SSE_KEEPALIVE_SECS=60\n")
1875            .expect_err("an interval equal to the tolerance is a race, not a margin");
1876
1877        require_keepalive_under_idle_timeout(timeout, "ENV AGENTD_SSE_KEEPALIVE_SECS 30\n")
1878            .expect("30s leaves a margin, in the legacy spelling");
1879        // The daemon's own default is 15s, so silence is safe for this pair.
1880        require_keepalive_under_idle_timeout(timeout, "FROM x\nCOPY agentd /agentd\n")
1881            .expect("an unset keepalive leaves the daemon at 15s");
1882        require_keepalive_under_idle_timeout(
1883            timeout,
1884            &default_dockerfile(
1885                crate::control::DEFAULT_AGENT_PORT,
1886                Some("/work"),
1887                &BaseImage::al2023(),
1888                None,
1889            ),
1890        )
1891        .expect("the derived Dockerfile sets no keepalive");
1892    }
1893
1894    /// **Issue #46, both refusable halves.** A Dockerfile with no `CMD` builds an image
1895    /// that runs the base's default process; a non-empty `ENTRYPOINT` turns the `CMD` into
1896    /// its arguments. Either way the daemon the artifact carries never starts, and the
1897    /// failure surfaces as `CREATE_FAILED` or a run-hook timeout naming neither
1898    /// instruction — so the message must name both the instruction and that symptom.
1899    #[test]
1900    fn a_dockerfile_that_never_runs_the_daemon_is_refused_naming_the_symptom() {
1901        // No CMD at all: the base's default applies, which is not /agentd.
1902        let error = require_daemon_cmd(
1903            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1904             COPY agentd /agentd\n\
1905             ENV AGENTD_PORT=9000\n",
1906        )
1907        .expect_err("no CMD means the daemon never starts");
1908        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1909        let message = error.to_string();
1910        assert!(message.contains("no CMD"), "{message}");
1911        assert!(message.contains("run-hook timeout"), "{message}");
1912        assert!(message.contains("CREATE_FAILED"), "{message}");
1913
1914        // A non-empty ENTRYPOINT swallows the CMD as its arguments.
1915        let error = require_daemon_cmd(
1916            "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1917             COPY agentd /agentd\n\
1918             ENTRYPOINT [\"/bin/sh\", \"-c\"]\n\
1919             CMD [\"/agentd\"]\n",
1920        )
1921        .expect_err("a non-empty ENTRYPOINT makes CMD its arguments");
1922        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1923        let message = error.to_string();
1924        assert!(message.contains("ENTRYPOINT"), "{message}");
1925        assert!(message.contains("run-hook timeout"), "{message}");
1926
1927        // An empty CMD is the same absence in different spelling.
1928        require_daemon_cmd("FROM x\nCMD []\n").expect_err("CMD [] runs nothing");
1929    }
1930
1931    /// The shapes that must pass: the deployment invariant itself, in exec and spaced
1932    /// spellings, and the invariant's `ENTRYPOINT []` with any interior whitespace. The
1933    /// derived Dockerfile passes its own guard, which is what keeps the default path
1934    /// unaffected.
1935    #[test]
1936    fn the_deployment_invariant_passes_the_daemon_cmd_guard() {
1937        require_daemon_cmd(&default_dockerfile(
1938            9000,
1939            Some("/work"),
1940            &BaseImage::al2023(),
1941            None,
1942        ))
1943        .expect("the derived Dockerfile is the invariant");
1944        require_daemon_cmd("FROM x\nENTRYPOINT []\nCMD [\"/agentd\"]\n").expect("the invariant");
1945        require_daemon_cmd("FROM x\nENTRYPOINT [ ]\nCMD [\"/agentd\"]\n")
1946            .expect("interior whitespace is still the empty exec form");
1947        require_daemon_cmd("FROM x\ncmd [\"/agentd\"]\n").expect("case-insensitive, no ENTRYPOINT");
1948        // Last instruction wins, as at build time: a later empty ENTRYPOINT un-swallows.
1949        require_daemon_cmd("FROM x\nENTRYPOINT [\"/bin/sh\"]\nENTRYPOINT []\nCMD [\"/agentd\"]\n")
1950            .expect("the last ENTRYPOINT is the one the build uses");
1951        // And the reverse ordering is refused for the same reason.
1952        require_daemon_cmd("FROM x\nENTRYPOINT []\nENTRYPOINT [\"/bin/sh\"]\nCMD [\"/agentd\"]\n")
1953            .expect_err("the last ENTRYPOINT is non-empty");
1954    }
1955
1956    /// Workdir inheritance is refused when neither the base nor the Dockerfile declares
1957    /// one, and the message says where the symptom would have appeared — in the guest, a
1958    /// build cycle later.
1959    #[test]
1960    fn inheriting_a_workdir_nothing_declares_is_refused() {
1961        let base = BaseImage::al2023();
1962        assert!(base.working_dir.is_empty(), "the measured case");
1963
1964        let error = require_workdir(&base, None).expect_err("nothing declares a workdir");
1965        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1966        let message = error.to_string();
1967        assert!(message.contains("no WorkingDir"), "{message}");
1968        assert!(message.contains("nothing to inherit"), "{message}");
1969        assert!(message.contains("docs/PLATFORM.md"), "{message}");
1970    }
1971
1972    /// It is accepted when *either* side declares one — the Dockerfile's `WORKDIR` or the
1973    /// base image's own `working_dir`. Both directions, because a check that only read the
1974    /// Dockerfile would refuse a caller on a purpose-built image that declares one.
1975    #[test]
1976    fn either_the_dockerfile_or_the_base_may_supply_the_workdir() {
1977        let base = BaseImage::al2023();
1978        require_workdir(&base, Some("FROM x\nWORKDIR /srv\n"))
1979            .expect("the Dockerfile declares one");
1980
1981        let purpose_built = BaseImage {
1982            working_dir: "/app".to_string(),
1983            ..BaseImage::al2023()
1984        };
1985        require_workdir(&purpose_built, None).expect("the base image declares one");
1986    }
1987
1988    /// A bare `WORKDIR` with no argument does not count as declaring one. It is the shape a
1989    /// truncated edit leaves behind, and treating it as a declaration would pass the guard
1990    /// on a Dockerfile that sets nothing.
1991    #[test]
1992    fn a_workdir_with_no_argument_does_not_count_as_a_declaration() {
1993        let error = require_workdir(&BaseImage::al2023(), Some("FROM x\nWORKDIR\n"))
1994            .expect_err("WORKDIR with no path declares nothing");
1995        assert_eq!(error.kind(), ErrorKind::InvalidArg);
1996    }
1997
1998    /// **IMAGE-1, the acceptance test #220 names.** Wrapping a bare `FROM` produces exactly the
1999    /// default Dockerfile for that base, so the stanza has one source: the default generator's
2000    /// output minus its `FROM` line is what a wrap appends. Checked with and without a workdir,
2001    /// and on a non-default port, because each of those is a branch of the one stanza.
2002    #[test]
2003    fn wrapping_a_bare_from_is_the_default_dockerfile_minus_nothing() {
2004        for (port, workdir) in [
2005            (DEFAULT_AGENT_PORT_FOR_TESTS, None),
2006            (DEFAULT_AGENT_PORT_FOR_TESTS, Some("/srv/task")),
2007            (8080, None),
2008        ] {
2009            let base = BaseImage {
2010                docker_ref: "x".to_string(),
2011                ..BaseImage::al2023()
2012            };
2013            let default = default_dockerfile(port, workdir, &base, None);
2014            let opts = WrapOptions {
2015                port,
2016                workdir: workdir.map(str::to_string),
2017                ..WrapOptions::default()
2018            };
2019            assert_eq!(
2020                wrap_dockerfile("FROM x\n", &opts).expect("a bare FROM wraps"),
2021                default,
2022                "IMAGE-1: port {port} workdir {workdir:?}"
2023            );
2024            let (from, stanza) = default.split_once('\n').expect("lines");
2025            assert_eq!(from, "FROM x");
2026            assert!(stanza.ends_with("CMD [\"/agentd\"]\n"), "{stanza}");
2027        }
2028    }
2029
2030    /// **IMAGE-2.** Whatever the task set — its own entrypoint, command, port, user — the
2031    /// wrapped result ends on the bootstrap invariant with the client's port, and a task that
2032    /// ends on another user has `USER root` restored ahead of the stanza. A task that ends on
2033    /// root, or never changes user, gets no extra line, which is what keeps IMAGE-1's equality.
2034    #[test]
2035    fn a_wrapped_task_ends_on_the_invariant_with_root_restored_when_needed() {
2036        let task = "FROM python:3.12-slim\nWORKDIR /app\nENV AGENTD_PORT=8080\n\
2037                    ENTRYPOINT [\"/bin/sh\", \"-c\"]\nCMD [\"python\", \"serve.py\"]\nUSER app\n";
2038        let wrapped = wrap_dockerfile(task, &WrapOptions::default()).expect("wraps");
2039        let added = wrapped
2040            .strip_prefix(task)
2041            .expect("the task text is kept verbatim");
2042        assert!(
2043            added.starts_with("USER root\nCOPY agentd /agentd\n"),
2044            "{added}"
2045        );
2046        assert_eq!(dockerfile_entrypoint(&wrapped), Some("[]"));
2047        assert_eq!(dockerfile_cmd(&wrapped), Some(r#"["/agentd"]"#));
2048        assert_eq!(dockerfile_agentd_port(&wrapped), Some(9000));
2049        require_daemon_cmd(&wrapped).expect("the daemon is the CMD");
2050        require_matching_agentd_port(9000, &wrapped).expect("the stanza's port wins");
2051
2052        for (last_user, restored) in [
2053            ("USER root", false),
2054            ("USER 0", false),
2055            ("USER root:root", false),
2056            ("USER 0:0", false),
2057            ("user app", true),
2058            ("USER 1000:1000", true),
2059            ("USER root:staff", true),
2060            ("USER ${TASK_USER}", true),
2061        ] {
2062            let task = format!("FROM x\n{last_user}\n");
2063            let added = wrap_dockerfile(&task, &WrapOptions::default())
2064                .expect("wraps")
2065                .strip_prefix(task.as_str())
2066                .expect("verbatim")
2067                .to_string();
2068            assert_eq!(
2069                added.starts_with("USER root\n"),
2070                restored,
2071                "IMAGE-2: {last_user:?}: {added}"
2072            );
2073        }
2074
2075        // Only the last USER counts, as at build time.
2076        let task = "FROM x\nUSER app\nUSER root\n";
2077        let wrapped = wrap_dockerfile(task, &WrapOptions::default()).expect("wraps");
2078        let added = wrapped.strip_prefix(task).expect("verbatim");
2079        assert!(added.starts_with("COPY agentd /agentd\n"), "{added}");
2080    }
2081
2082    /// **IMAGE-2, the newline.** A task file without a trailing newline gets one before the
2083    /// stanza, in either line ending, so the stanza's first line is its own instruction.
2084    #[test]
2085    fn a_task_without_a_trailing_newline_is_normalized() {
2086        let wrapped = wrap_dockerfile("FROM x", &WrapOptions::default()).expect("wraps");
2087        assert!(
2088            wrapped.starts_with("FROM x\nCOPY agentd /agentd\n"),
2089            "{wrapped}"
2090        );
2091        let wrapped =
2092            wrap_dockerfile("FROM x\r\nRUN true", &WrapOptions::default()).expect("wraps");
2093        assert!(
2094            wrapped.starts_with("FROM x\r\nRUN true\nCOPY agentd /agentd\n"),
2095            "{wrapped}"
2096        );
2097        let wrapped = wrap_dockerfile("FROM x\r\n", &WrapOptions::default()).expect("wraps");
2098        assert!(wrapped.starts_with("FROM x\r\nCOPY agentd"), "{wrapped}");
2099    }
2100
2101    /// **IMAGE-3.** Each refusal on its own, against an otherwise wrappable task, names its
2102    /// cause: no `FROM`, a trailing continuation (in the default and a custom escape
2103    /// character, across blank and comment lines, in either line ending), an open heredoc, a
2104    /// keepalive the client cannot tolerate, a bad workdir or port, and inheriting a workdir
2105    /// nothing declares.
2106    #[test]
2107    fn a_task_the_stanza_cannot_follow_is_refused_naming_the_cause() {
2108        let refused = |task: &str, opts: WrapOptions, cause: &str| {
2109            let error = wrap_dockerfile(task, &opts).expect_err(cause);
2110            assert_eq!(error.kind(), ErrorKind::InvalidArg, "{error}");
2111            let message = error.to_string();
2112            assert!(message.contains(cause), "IMAGE-3 {cause:?}: {message}");
2113        };
2114        let none = WrapOptions::default;
2115        refused("RUN echo hello\n", none(), "no FROM");
2116        refused("", none(), "no FROM");
2117        refused("FROM\n", none(), "no FROM");
2118        refused(
2119            "FROM x\nRUN apt-get update && \\\n",
2120            none(),
2121            "line continuation",
2122        );
2123        refused("FROM x\nRUN a \\   \n", none(), "line continuation");
2124        refused("FROM x\nRUN a \\\r\n", none(), "line continuation");
2125        refused(
2126            "FROM x\nRUN a \\\n\n# comment\n",
2127            none(),
2128            "line continuation",
2129        );
2130        refused("# escape=`\nFROM x\nRUN a `\n", none(), "line continuation");
2131        refused("FROM x\nRUN <<EOF\necho never closed\n", none(), "heredoc");
2132        refused("FROM x\nRUN <<-\"END\"\necho x\n", none(), "heredoc");
2133        refused("FROM x\nCOPY <<A <<B /dst/\na\nA\nb\n", none(), "heredoc");
2134        refused(
2135            "FROM x\nENV AGENTD_SSE_KEEPALIVE_SECS=90\n",
2136            none(),
2137            "AGENTD_SSE_KEEPALIVE_SECS=90",
2138        );
2139        for workdir in ["relative/dir", "/srv\nRUN evil", "/my dir", "/tab\there"] {
2140            refused(
2141                "FROM x\n",
2142                WrapOptions {
2143                    workdir: Some(workdir.to_string()),
2144                    ..none()
2145                },
2146                "absolute path",
2147            );
2148        }
2149        refused("FROM x\n", WrapOptions { port: 0, ..none() }, "port");
2150        refused(
2151            "FROM x\n",
2152            WrapOptions {
2153                inherit_workdir: true,
2154                ..none()
2155            },
2156            "nothing to inherit",
2157        );
2158    }
2159
2160    /// **IMAGE-3, the other side.** What looks like a refusal but is not: a backslash under a
2161    /// backtick escape, a continuation that was finished, a closed heredoc (including a `<<-`
2162    /// terminator indented with tabs), a here-string, an escaped keepalive under the timeout,
2163    /// and inheriting a workdir the task or the options declare.
2164    #[test]
2165    fn a_finished_task_is_wrapped_even_when_it_looks_unfinished() {
2166        let none = WrapOptions::default;
2167        for task in [
2168            "# escape=`\nFROM x\nRUN a \\\n",
2169            "FROM x\nRUN a \\\n  && b\n",
2170            "FROM x\nRUN <<EOF\necho closed\nEOF\n",
2171            "FROM x\nRUN <<-EOF\n\techo closed\n\tEOF\n",
2172            "FROM x\nCOPY <<A <<B /dst/\na\nA\nb\nB\n",
2173            "FROM x\nRUN cat <<< word\n",
2174            "FROM x\n# a trailing comment \\\n",
2175            "FROM x\nENV AGENTD_SSE_KEEPALIVE_SECS=30\n",
2176        ] {
2177            wrap_dockerfile(task, &none())
2178                .unwrap_or_else(|error| panic!("{task:?} was refused: {error}"));
2179        }
2180        wrap_dockerfile(
2181            "FROM x\nWORKDIR /app\n",
2182            &WrapOptions {
2183                inherit_workdir: true,
2184                ..none()
2185            },
2186        )
2187        .expect("the task declares one");
2188        wrap_dockerfile(
2189            "FROM x\n",
2190            &WrapOptions {
2191                inherit_workdir: true,
2192                workdir: Some("/srv".to_string()),
2193                ..none()
2194            },
2195        )
2196        .expect("the options declare one");
2197        wrap_dockerfile(
2198            "FROM x\n",
2199            &WrapOptions {
2200                workdir: Some(String::new()),
2201                ..none()
2202            },
2203        )
2204        .expect("an empty workdir is none, as default_dockerfile reads it");
2205    }
2206
2207    /// **IMAGE-4.** A derived base takes its ref from the first `FROM`, keeps the managed
2208    /// base's name (so `baseImageArn` is unchanged) and an empty working dir, and pairs with
2209    /// the Dockerfile it came from under the `FROM` guard — digest pins included, since the
2210    /// ref is taken whole. A Dockerfile with no `FROM` has nothing to derive.
2211    #[test]
2212    fn a_base_derived_from_a_dockerfile_pairs_with_it_by_construction() {
2213        let digest = "c439fb4994ea7ca529233d6256446d3f8b7b4efb58956073e015303a170011de";
2214        for (task, docker_ref) in [
2215            ("FROM python:3.12-slim\n", "python:3.12-slim".to_string()),
2216            (
2217                "FROM --platform=linux/arm64 golang:1.23 AS build\nFROM python:3.12-slim\n",
2218                "golang:1.23".to_string(),
2219            ),
2220            (
2221                &*format!("FROM ubuntu:24.04@sha256:{digest}\n"),
2222                format!("ubuntu:24.04@sha256:{digest}"),
2223            ),
2224        ] {
2225            let base = BaseImage::from_dockerfile(task).expect("a FROM");
2226            assert_eq!(base.docker_ref, docker_ref);
2227            assert_eq!(
2228                base.name,
2229                BaseImage::al2023().name,
2230                "IMAGE-4 keeps the managed base"
2231            );
2232            assert_eq!(base.working_dir, "");
2233            let wrapped = wrap_dockerfile(task, &WrapOptions::default()).expect("wraps");
2234            require_matching_from(&base, &wrapped).expect("IMAGE-4: the pair agrees");
2235            assert_eq!(BaseImage::from_dockerfile(&wrapped).expect("a FROM"), base);
2236        }
2237        // The inversion #220 removes: under the managed base, a task on another base is
2238        // refused.
2239        require_matching_from(
2240            &BaseImage::al2023(),
2241            &wrap_dockerfile("FROM python:3.12-slim\n", &WrapOptions::default()).expect("wraps"),
2242        )
2243        .expect_err("the managed base does not pair with python:3.12-slim");
2244
2245        let error = BaseImage::from_dockerfile("RUN echo hello\n").expect_err("no FROM");
2246        assert_eq!(error.kind(), ErrorKind::InvalidArg);
2247        assert!(error.to_string().contains("no FROM"), "{error}");
2248    }
2249
2250    /// **The table `crates/model/src/wrap.rs` specifies**, rendered as real Dockerfile text: every
2251    /// task and option combination the model enumerates, and the refusal (or the `USER root`
2252    /// verdict) the model's `specified` gives it. The model crate cannot be a dependency here
2253    /// (this crate is published and the model isn't), so the table is restated as `expected`
2254    /// below, and `crates/model-conformance/tests/tables.rs` drives this function over the model's rows.
2255    #[test]
2256    fn wrap_agrees_with_the_model_table() {
2257        #[derive(Debug)]
2258        enum Expect {
2259            Refused(&'static str),
2260            Wrapped { user_root: bool },
2261        }
2262        let digest = "c439fb4994ea7ca529233d6256446d3f8b7b4efb58956073e015303a170011de";
2263        let managed = BaseImage::al2023().docker_ref;
2264        let froms = [
2265            None,
2266            Some(managed.clone()),
2267            Some(format!("{managed}@sha256:{digest}")),
2268            Some("python:3.12-slim".to_string()),
2269        ];
2270        let mut checked = 0;
2271        for from in &froms {
2272            for tail in 0..3 {
2273                for user in 0..3 {
2274                    for declares_workdir in [false, true] {
2275                        for keepalive_too_long in [false, true] {
2276                            for workdir in 0..3 {
2277                                for inherit_workdir in [false, true] {
2278                                    let mut text = String::new();
2279                                    match from {
2280                                        Some(from) => text.push_str(&format!("FROM {from}\n")),
2281                                        None => text.push_str("RUN echo no base\n"),
2282                                    }
2283                                    if declares_workdir {
2284                                        text.push_str("WORKDIR /app\n");
2285                                    }
2286                                    if keepalive_too_long {
2287                                        text.push_str("ENV AGENTD_SSE_KEEPALIVE_SECS=60\n");
2288                                    }
2289                                    match user {
2290                                        1 => text.push_str("USER root\n"),
2291                                        2 => text.push_str("USER app\n"),
2292                                        _ => {}
2293                                    }
2294                                    match tail {
2295                                        1 => text.push_str("RUN make \\\n"),
2296                                        2 => text.push_str("RUN <<EOF\necho open\n"),
2297                                        _ => {}
2298                                    }
2299                                    let opts = WrapOptions {
2300                                        workdir: match workdir {
2301                                            1 => Some("/srv".to_string()),
2302                                            2 => Some("srv".to_string()),
2303                                            _ => None,
2304                                        },
2305                                        inherit_workdir,
2306                                        ..WrapOptions::default()
2307                                    };
2308                                    let expected = if from.is_none() {
2309                                        Expect::Refused("no FROM")
2310                                    } else if tail != 0 {
2311                                        Expect::Refused(if tail == 1 {
2312                                            "line continuation"
2313                                        } else {
2314                                            "heredoc"
2315                                        })
2316                                    } else if keepalive_too_long {
2317                                        Expect::Refused("AGENTD_SSE_KEEPALIVE_SECS")
2318                                    } else if workdir == 2 {
2319                                        Expect::Refused("absolute path")
2320                                    } else if inherit_workdir && !declares_workdir && workdir == 0 {
2321                                        Expect::Refused("nothing to inherit")
2322                                    } else {
2323                                        Expect::Wrapped {
2324                                            user_root: user == 2,
2325                                        }
2326                                    };
2327                                    let got = wrap_dockerfile(&text, &opts);
2328                                    match (&expected, &got) {
2329                                        (Expect::Refused(cause), Err(error)) => assert!(
2330                                            error.to_string().contains(cause),
2331                                            "{expected:?} for {text:?} {opts:?}: {error}"
2332                                        ),
2333                                        (Expect::Wrapped { user_root }, Ok(out)) => assert_eq!(
2334                                            out.strip_prefix(text.as_str())
2335                                                .expect("verbatim")
2336                                                .starts_with("USER root\n"),
2337                                            *user_root,
2338                                            "{text:?} {opts:?}"
2339                                        ),
2340                                        _ => panic!(
2341                                            "{expected:?} for {text:?} {opts:?}, got {got:?}"
2342                                        ),
2343                                    }
2344                                    checked += 1;
2345                                }
2346                            }
2347                        }
2348                    }
2349                }
2350            }
2351        }
2352        assert_eq!(
2353            checked,
2354            4 * 3 * 3 * 2 * 2 * 3 * 2,
2355            "every combination the model has"
2356        );
2357    }
2358
2359    fn context_of(entries: &[(&str, u32, &[u8])]) -> crate::control::context::BuildContext {
2360        crate::control::context::BuildContext::from_entries(
2361            entries
2362                .iter()
2363                .map(
2364                    |(name, mode, bytes)| crate::control::context::ContextEntry {
2365                        name: (*name).to_string(),
2366                        mode: *mode,
2367                        bytes: bytes.to_vec(),
2368                    },
2369                )
2370                .collect(),
2371        )
2372        .expect("valid entries")
2373    }
2374
2375    /// **IMAGE-6, the pin.** A request with no build context — `None`, or an empty one — hashes
2376    /// to exactly what `artifact_content_hash` produced before #221, so no `build --reuse` or
2377    /// `AgentVm` image name moves. The vector is the one pinned for #74, recomputed
2378    /// independently with Python's hashlib then.
2379    #[test]
2380    fn a_request_without_a_context_keeps_its_digest() {
2381        let pinned = "90a0ef925a4696b0c0f142241b2c714e63f40071d0d02951e26cb2a1d8bb24fc";
2382        assert_eq!(
2383            artifact_content_hash_with_context(b"binary-bytes", "FROM scratch\n", None, None),
2384            pinned,
2385            "IMAGE-6: the no-context digest is the pre-#221 digest"
2386        );
2387        let empty = crate::control::context::BuildContext::default();
2388        assert_eq!(
2389            artifact_content_hash_with_context(
2390                b"binary-bytes",
2391                "FROM scratch\n",
2392                None,
2393                Some(&empty)
2394            ),
2395            pinned,
2396            "an empty context carries no extra entries, so it is the same artifact"
2397        );
2398        assert_eq!(
2399            artifact_content_hash(b"binary-bytes", "FROM scratch\n", None),
2400            pinned
2401        );
2402    }
2403
2404    /// **IMAGE-6, the extension.** Each entry's name, mode, and bytes are part of the
2405    /// identity; the order entries were read in is not, because a context is sorted by name.
2406    #[test]
2407    fn the_context_hash_follows_every_entry_and_not_their_order() {
2408        let hash = |context: &crate::control::context::BuildContext| {
2409            artifact_content_hash_with_context(b"bin", "FROM x\n", None, Some(context))
2410        };
2411        let base = hash(&context_of(&[
2412            ("a.txt", 0o644, b"a"),
2413            ("b.txt", 0o644, b"b"),
2414        ]));
2415        assert_ne!(
2416            base,
2417            artifact_content_hash_with_context(b"bin", "FROM x\n", None, None),
2418            "IMAGE-6: a context is part of the identity"
2419        );
2420        assert_eq!(
2421            base,
2422            hash(&context_of(&[
2423                ("b.txt", 0o644, b"b"),
2424                ("a.txt", 0o644, b"a")
2425            ])),
2426            "the read order is not"
2427        );
2428        for (changed, what) in [
2429            (
2430                context_of(&[("a.txt", 0o644, b"A"), ("b.txt", 0o644, b"b")]),
2431                "bytes",
2432            ),
2433            (
2434                context_of(&[("a.txt", 0o755, b"a"), ("b.txt", 0o644, b"b")]),
2435                "mode",
2436            ),
2437            (
2438                context_of(&[("c.txt", 0o644, b"a"), ("b.txt", 0o644, b"b")]),
2439                "name",
2440            ),
2441            (context_of(&[("a.txt", 0o644, b"ab")]), "boundary"),
2442        ] {
2443            assert_ne!(base, hash(&changed), "IMAGE-6: the entry {what} counts");
2444        }
2445    }
2446
2447    /// **IMAGE-7, the zip.** Equal inputs make byte-identical artifacts, so equal inputs are
2448    /// one S3 object: every entry carries the DOS epoch as its date and a fixed mode, the
2449    /// context entries sit beside the Dockerfile at the root, and the Dockerfile entry is the
2450    /// one passed in. The same build a second apart, which needs a real sleep this crate
2451    /// can't make, is `crates/microvms-core/tests/artifact_across_seconds.rs`.
2452    #[test]
2453    fn the_artifact_is_deterministic_with_fixed_dates_and_modes() {
2454        use std::io::Read as _;
2455
2456        let context = context_of(&[("app/run.sh", 0o755, b"#!/bin/sh\n"), ("data", 0o644, b"d")]);
2457        let build = || {
2458            build_artifact_with_context(
2459                &aarch64_daemon(b"daemon"),
2460                "FROM x\n",
2461                None,
2462                Some(&context),
2463            )
2464            .expect("zips")
2465        };
2466        let first = build();
2467        assert_eq!(first, build(), "IMAGE-7: equal inputs, identical bytes");
2468
2469        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(first)).expect("a zip");
2470        let mut names = Vec::new();
2471        for index in 0..archive.len() {
2472            let entry = archive.by_index(index).expect("entry");
2473            let name = entry.name().expect("a name").into_owned();
2474            let modified = entry.last_modified().expect("a date");
2475            assert_eq!(
2476                (modified.year(), modified.month(), modified.day()),
2477                (1980, 1, 1),
2478                "IMAGE-7: {name} carries a fixed date"
2479            );
2480            let mode = entry.unix_mode().expect("a mode") & 0o777;
2481            let expected = match name.as_str() {
2482                "agentd" | "app/run.sh" => 0o755,
2483                _ => 0o644,
2484            };
2485            assert_eq!(mode, expected, "IMAGE-7: {name} mode {mode:o}");
2486            names.push(name);
2487        }
2488        assert_eq!(names, ["Dockerfile", "agentd", "app/run.sh", "data"]);
2489        let mut dockerfile = String::new();
2490        archive
2491            .by_name("Dockerfile")
2492            .expect("entry")
2493            .read_to_string(&mut dockerfile)
2494            .expect("reads");
2495        assert_eq!(dockerfile, "FROM x\n");
2496    }
2497
2498    /// **IMAGE-7, the host system.** Every entry's central-directory header records Unix (3)
2499    /// as the system that made it, whatever host builds the artifact. zip records the running
2500    /// host otherwise, MS-DOS (0) on Windows, and that one byte made a Windows build differ
2501    /// from a Linux build of the same inputs and let a reader that follows it take the
2502    /// entries' modes for DOS attributes.
2503    ///
2504    /// **Falsification**: set `.system(zip::System::Dos)`, the Windows default, in
2505    /// `build_artifact_with_context`'s options, and every host byte reads 0.
2506    #[test]
2507    fn every_artifact_entry_records_unix_as_its_host_system() {
2508        let context = context_of(&[("app/run.sh", 0o755, b"#!/bin/sh\n")]);
2509        let bytes = build_artifact_with_context(
2510            &aarch64_daemon(b"daemon"),
2511            "FROM x\n",
2512            None,
2513            Some(&context),
2514        )
2515        .expect("zips");
2516        assert_eq!(
2517            central_directory_hosts(&bytes),
2518            [3, 3, 3],
2519            "IMAGE-7: every entry's host system is Unix"
2520        );
2521    }
2522
2523    /// The host-system byte of each central-directory header, in order (APPNOTE 4.3.12 and
2524    /// 4.4.2: the high byte of "version made by"). The artifact carries no archive comment, so
2525    /// its end record is the last 22 bytes: the entry count at +10, the directory's offset at
2526    /// +16.
2527    fn central_directory_hosts(bytes: &[u8]) -> Vec<u8> {
2528        let u16_at = |at: usize| usize::from(u16::from_le_bytes([bytes[at], bytes[at + 1]]));
2529        let end = bytes.len() - 22;
2530        assert_eq!(&bytes[end..end + 4], b"PK\x05\x06", "the end record");
2531        let offset = bytes[end + 16..end + 20].try_into().expect("four bytes");
2532        let mut at = usize::try_from(u32::from_le_bytes(offset)).expect("fits");
2533        (0..u16_at(end + 10))
2534            .map(|_| {
2535                assert_eq!(
2536                    &bytes[at..at + 4],
2537                    b"PK\x01\x02",
2538                    "a central-directory header"
2539                );
2540                let host = bytes[at + 5];
2541                at += 46 + u16_at(at + 28) + u16_at(at + 30) + u16_at(at + 32);
2542                host
2543            })
2544            .collect()
2545    }
2546
2547    /// **IMAGE-7, the byte scan extended.** The agent token has no path into a context either:
2548    /// the artifact built from a context is scanned the way AC-2-3 scans the plain one.
2549    #[test]
2550    fn a_context_artifact_never_carries_the_agent_token() {
2551        let token = "s3cr3t-agent-token-do-not-bake-me";
2552        let context = context_of(&[("app/main.py", 0o644, b"print('hi')\n")]);
2553        let bytes = build_artifact_with_context(
2554            &aarch64_daemon(b"binary"),
2555            &wrap_dockerfile("FROM x\n", &WrapOptions::default()).expect("wraps"),
2556            None,
2557            Some(&context),
2558        )
2559        .expect("zips");
2560        assert!(
2561            !bytes
2562                .windows(token.len())
2563                .any(|window| window == token.as_bytes())
2564        );
2565    }
2566
2567    /// The base image ARN, for the region it is requested in.
2568    ///
2569    /// `microvm-image:` with a **colon**, which is the spelling for a managed base *and* for
2570    /// a customer image alike — measured 2026-08-15 against real ARNs in us-east-1, and the
2571    /// only form the model's `TaggableResource` pattern admits. The docs above this function
2572    /// carry the measurement.
2573    ///
2574    /// **Falsification** — change the separator to `/` and both assertions go red. That was
2575    /// the state twelve fakes and the transport encoding test were in, which is why this
2576    /// test now asserts the separator explicitly rather than only the region.
2577    #[test]
2578    fn the_base_image_arn_names_the_request_region_with_a_colon_separator() {
2579        assert_eq!(
2580            BaseImage::al2023().arn(&crate::region::Region::UsEast1),
2581            "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"
2582        );
2583        assert_eq!(
2584            BaseImage::al2023().arn(&crate::region::Region::ApNortheast1),
2585            "arn:aws:lambda:ap-northeast-1:aws:microvm-image:al2023-1"
2586        );
2587        assert!(
2588            !BaseImage::al2023()
2589                .arn(&crate::region::Region::UsEast1)
2590                .contains("microvm-image/"),
2591            "the slash form answers AccessDeniedException, not a validation error"
2592        );
2593    }
2594}