microvms_app/control/image.rs
1// SPDX-License-Identifier: Apache-2.0
2//! Image create, the build wait, and the stalled-build probe (TRAP-1, TRAP-2).
3//!
4//! # Why the wait needs a probe at all
5//!
6//! `CREATING` covers two situations that are indistinguishable from the outside: a build in
7//! progress, and a build the service **never scheduled**. The second is the `clientToken`
8//! replay signature — the image was created as a no-op replay of an earlier create, its
9//! builds were never queued, it cannot be deleted (`CREATING` forbids it) and its only
10//! version cannot be dropped (it is the last one).
11//!
12//! Waiting through it burns the full 45-minute build timeout and then reports "did not
13//! become usable in time", which is a timeout message hiding a cause that was knowable in
14//! four minutes. So after [`WaitOpts::stall_grace`] the wait probes the build list: every
15//! build still `PENDING` means nothing was ever scheduled, and that is reported as
16//! [`ErrorKind::BuildWedged`] naming the replay signature.
17//!
18//! # The field is `buildState`
19//!
20//! `MicrovmImageBuildSummary` has no `state` member. Reading `state` returns nothing from
21//! every real response, which is exactly how this guard was dead for a review round while
22//! its unit test passed — see [`crate::control::ops`]. The deserializer refuses a
23//! `state`-spelled summary outright, so that failure mode is now a test rather than a
24//! comment.
25
26use std::time::Duration;
27
28use super::transport::{Call, paths, send_with_retry};
29use super::{ControlPlane, CreateImageRequest, artifact, hooks_block, ops, timed_out, token};
30use crate::error::{Error, ErrorKind};
31use crate::sizing::SizeClass;
32
33/// How long an image may sit in `CREATING` before the stall probe runs.
34///
35/// Four minutes: long enough that a genuinely slow build is not accused, short enough that a
36/// wedged one does not burn the full build timeout in silence.
37pub const DEFAULT_STALL_GRACE: Duration = Duration::from_secs(240);
38
39/// The default build timeout, 45 minutes.
40pub const DEFAULT_BUILD_TIMEOUT: Duration = Duration::from_secs(45 * 60);
41
42/// The default gap between polls.
43///
44/// Fifteen seconds, matching the Python client's `max(poll_interval, 15.0)` for the image
45/// wait: a build takes minutes, so a tighter interval only spends control-plane quota.
46pub const DEFAULT_IMAGE_POLL_INTERVAL: Duration = Duration::from_secs(15);
47
48/// The log-group prefix the service writes build logs under.
49///
50/// Measured 2026-08-05. **Not** `/aws/lambda/microvms/*` — an IAM policy granting that
51/// plausible-looking prefix instead produces server-side builds with **no logs at all**,
52/// and then every build failure reads `reason=unknown`, which looks like the service
53/// failing to populate `stateReason` when it is the caller's own policy discarding the
54/// evidence.
55pub const BUILD_LOG_GROUP_PREFIX: &str = "/aws/lambda-microvms";
56
57/// A built image, and the log group the service created alongside it.
58#[derive(Clone, Debug, Eq, PartialEq)]
59pub struct Image {
60 /// The image ARN, which is what `imageIdentifier` takes.
61 pub identifier: String,
62 /// The image name.
63 pub name: String,
64 /// The version the create call produced.
65 pub version: String,
66 /// The state the service last reported.
67 pub state: String,
68 /// The class the requested baseline selected.
69 ///
70 /// Carried on the image because billing follows the baseline requested at *create*
71 /// time, and by the time anyone asks what a run cost the request is gone.
72 pub size: SizeClass,
73 /// The build log group the create call configured, or `None` for the service default
74 /// ([`Image::build_log_group`]'s derivation).
75 ///
76 /// Carried for the same reason `size` is: by the time anyone asks where the build's
77 /// logs went, the request is gone.
78 pub log_group: Option<String>,
79 /// The **resolved** exact log stream the create call configured — the caller's prefix
80 /// plus `/` plus the sixteen-hex per-build discriminator — or `None` when no stream
81 /// was configured.
82 ///
83 /// This is the only place the resolved name exists: the discriminator is minted fresh
84 /// inside [`ControlPlane::create_image`], so a caller who wants to read their build's
85 /// logs has to read the name off this field rather than re-deriving it. The CLI's
86 /// build envelope reports it as `logStream` for exactly that reason.
87 pub log_stream: Option<String>,
88}
89
90impl Image {
91 /// The configured build log group, or the derived default
92 /// `/aws/lambda-microvms/<image-name>`.
93 ///
94 /// The default is the group the service creates itself, so a Terraform stack never
95 /// owns it and `terraform destroy` leaves it behind — "the stack destroyed cleanly"
96 /// is not "the account is clean". Six of these accumulated before anyone noticed. A
97 /// configured group ([`crate::control::CreateImageRequest::log_group`]) replaces the
98 /// derivation, because the derived name is then a group no build ever writes to.
99 pub fn build_log_group(&self) -> String {
100 match &self.log_group {
101 Some(group) => group.clone(),
102 None => format!("{BUILD_LOG_GROUP_PREFIX}/{}", self.name),
103 }
104 }
105
106 /// Whether the state the service reported means "built and usable".
107 ///
108 /// Accepts the two model-backed spellings and the two tolerated ones. Kept generous
109 /// because the service has answered differently across API versions, and a hard
110 /// equality check on one spelling is how a working build looks like a stalled one.
111 pub fn is_ready(state: &str) -> bool {
112 crate::constants::MODEL_IMAGE_READY_STATES.contains(&state)
113 || crate::constants::TOLERATED_IMAGE_READY_STATES.contains(&state)
114 }
115
116 /// Whether the state means the build failed.
117 ///
118 /// A substring test rather than a set, because the model's failure spellings are
119 /// `CREATE_FAILED`, `UPDATE_FAILED`, and `DELETE_FAILED` and the thing they share is
120 /// the word — matching that means a fourth added later is still recognised as a
121 /// failure rather than polled until the deadline.
122 pub fn is_failed(state: &str) -> bool {
123 state.contains("FAILED")
124 }
125}
126
127/// How long to wait and how often to poll.
128#[derive(Clone, Copy, Debug)]
129pub struct WaitOpts {
130 /// The client-side deadline.
131 pub timeout: Duration,
132 /// The gap between polls.
133 pub poll_interval: Duration,
134 /// How long `CREATING` is tolerated before the stall probe runs (TRAP-2).
135 ///
136 /// Only meaningful for the image wait; the launch wait has no equivalent, because a
137 /// launch has no build list to probe.
138 pub stall_grace: Duration,
139}
140
141impl Default for WaitOpts {
142 fn default() -> Self {
143 Self {
144 timeout: DEFAULT_BUILD_TIMEOUT,
145 poll_interval: DEFAULT_IMAGE_POLL_INTERVAL,
146 stall_grace: DEFAULT_STALL_GRACE,
147 }
148 }
149}
150
151impl WaitOpts {
152 /// Options for the launch wait: [`crate::sandbox::DEFAULT_LIFECYCLE_TIMEOUT`] at
153 /// [`crate::sandbox::LIFECYCLE_POLL_INTERVAL`], five minutes at five-second polls.
154 pub fn for_launch() -> Self {
155 Self::for_lifecycle(crate::sandbox::DEFAULT_LIFECYCLE_TIMEOUT)
156 }
157
158 /// Options for a lifecycle wait (a launch, suspend, resume or terminate) with the caller's
159 /// deadline: core's [`crate::sandbox::LIFECYCLE_POLL_INTERVAL`], and no stall probe.
160 ///
161 /// Every surface's lifecycle wait starts here, so what a lifecycle wait is lives in one
162 /// place (#266); a caller that polls at another rate sets `poll_interval` on the result.
163 /// `stall_grace` is set past any deadline rather than to zero, since a zero grace would
164 /// read as "probe immediately", and a lifecycle transition has no build list to probe
165 /// (TRAP-2 is the image build's).
166 pub fn for_lifecycle(timeout: Duration) -> Self {
167 Self {
168 timeout,
169 poll_interval: crate::sandbox::LIFECYCLE_POLL_INTERVAL,
170 stall_grace: Duration::MAX,
171 }
172 }
173}
174
175impl ControlPlane {
176 /// Creates an image, closing every local guard **before** the call.
177 ///
178 /// Order matters and is the same order the Python client uses for the same reason: the
179 /// create call happens *after* the artifact upload, so a rejection the service raises
180 /// costs the caller the upload first. Everything checkable is checked here — and the
181 /// checks are [`Self::preflight`], so an uploading caller can run the same list before
182 /// the upload and pay nothing for a request this client itself refuses.
183 ///
184 /// The artifact is built here too, but **not** uploaded:
185 /// [`CreateImageRequest::code_artifact_uri`] is where the caller says they have already
186 /// put it, and [`ControlPlane::build_artifact_for`] produces the bytes to upload.
187 /// [`crate::sandbox::Sandbox::ensure_image`] is the path that uploads for itself.
188 pub async fn create_image(&self, request: CreateImageRequest) -> Result<Image, Error> {
189 self.preflight(&request)?;
190
191 // The discriminator rule: a configured logStream never reaches the wire verbatim.
192 // The member is an EXACT stream name (prefixes unsupported) and one build is three
193 // VMs writing three streams, so a verbatim name collapses every build's streams
194 // into one — this suffixes `/<16 hex>` of fresh CSPRNG per create attempt, the
195 // same mechanism as the clientToken nonce below (docs/PLATFORM.md, 'An image
196 // build is three VMs and three log streams'). Resolved here, once, so the value
197 // on the wire and the value returned to the caller are the same string.
198 let resolved_stream = request
199 .log_stream
200 .as_deref()
201 .map(|prefix| token::resolve_log_stream(prefix, self.entropy()))
202 .transpose()?;
203 let logging = request
204 .log_group
205 .as_deref()
206 .map(|group| ops::Logging::cloud_watch(group, resolved_stream.clone()));
207
208 let wire = ops::CreateMicrovmImageWire {
209 name: request.name.clone(),
210 base_image_arn: request.base_image.arn(&self.region),
211 base_image_version: request.base_image_version.clone(),
212 build_role_arn: request.build_role_arn.clone(),
213 code_artifact: ops::CodeArtifact {
214 uri: request.code_artifact_uri.clone(),
215 },
216 // The enum's only value. Injected rather than accepted, because a field could
217 // only ever express a request AWS rejects — after the upload.
218 cpu_configurations: vec![ops::CpuConfiguration {
219 architecture: crate::constants::ARCHITECTURES[0].to_string(),
220 }],
221 resources: vec![ops::Resources {
222 minimum_memory_in_mib: request.size.baseline_mib(),
223 }],
224 hooks: hooks_block(
225 self.port,
226 request.run_hook_timeout,
227 request.build_hook_timeout,
228 ),
229 // TRAP-3: the boolean intent becomes the one accepted enum value. There is no
230 // list a caller could put `CAP_SYS_ADMIN` in.
231 additional_os_capabilities: request
232 .repair_guest_identity
233 .then(|| vec![crate::constants::CAPABILITIES[0].to_string()]),
234 logging,
235 tags: (!request.tags.is_empty()).then(|| request.tags.clone()),
236 // TRAP-1: minted here, from a label. Never from the caller.
237 client_token: token::create_token_with(
238 request.token_scope.as_deref().unwrap_or(&request.name),
239 self.entropy(),
240 )?,
241 };
242
243 let call = Call::post_json("CreateMicrovmImage", paths::microvm_images(), &wire)?;
244 let reply = send_with_retry(self.transport(), call).await?;
245 let created: ops::CreateMicrovmImageResponseWire = reply.json("CreateMicrovmImage")?;
246
247 Ok(Image {
248 identifier: created.image_arn,
249 name: created.name,
250 version: created.image_version,
251 state: created.state,
252 size: request.size,
253 log_group: request.log_group.clone(),
254 // The resolved name, discriminator included, so the caller can find their
255 // logs — the wire value is the only copy and it was minted here.
256 log_stream: resolved_stream,
257 })
258 }
259
260 /// Every local guard [`Self::create_image`] runs, callable **before** the artifact upload.
261 ///
262 /// # One list of guards, reachable from before the upload
263 ///
264 /// The guards below are pure functions of the request — no call, no credential — and
265 /// `create_image` runs them before its own wire call. But `create_image` runs *after*
266 /// the caller's artifact upload, so from inside it a locally-refusable request has
267 /// already cost the caller the S3 PUT (issue #47). This method is the same list,
268 /// extracted so an uploading caller invokes it first and the list cannot drift between
269 /// call sites — `create_image` delegates here rather than keeping its own copy.
270 ///
271 /// A caller who skips it loses nothing but the upload: `create_image` still refuses
272 /// before the wire.
273 pub fn preflight(&self, request: &CreateImageRequest) -> Result<(), Error> {
274 super::require_valid_image_name(&request.name)?;
275
276 if request.inherit_workdir {
277 artifact::require_workdir(&request.base_image, request.dockerfile.as_deref())?;
278 }
279 if let Some(dockerfile) = request.dockerfile.as_deref() {
280 artifact::require_matching_from(&request.base_image, dockerfile)?;
281 artifact::require_matching_agentd_port(self.port, dockerfile)?;
282 artifact::require_keepalive_under_idle_timeout(
283 crate::session::exec::DEFAULT_STREAM_IDLE_TIMEOUT,
284 dockerfile,
285 )?;
286 // The artifact carries the daemon unconditionally; a Dockerfile that never runs
287 // it builds cleanly and fails as a run-hook timeout naming nothing (issue #46).
288 artifact::require_daemon_cmd(dockerfile)?;
289 // Same shape for the project files (#74): they enter the artifact
290 // unconditionally, and a Dockerfile that ignores them bakes no layer while
291 // building cleanly.
292 if let Some(project) = &request.project_files {
293 artifact::require_project_install(project, dockerfile)?;
294 }
295 }
296
297 // Pinned only when the caller asked for it, and refused locally when they asked for
298 // something the `Version` shape cannot carry — see `require_valid_version`. A blank
299 // or whitespace-bearing value here is a `ValidationException` raised *after* the
300 // artifact upload, which is the ordering this whole function is arranged to protect
301 // against.
302 if let Some(version) = request.base_image_version.as_deref() {
303 super::require_valid_version("baseImageVersion", version)?;
304 }
305
306 // The logging pair, when configured. The stream requires the group because a
307 // stream inside a group the service names randomly is a stream whose location
308 // nobody can predict — the configured pair is the whole point of configuring.
309 // Both checked here for the create-after-upload ordering everything else in this
310 // list is about.
311 if let Some(group) = request.log_group.as_deref() {
312 super::require_valid_log_group(group)?;
313 }
314 if let Some(stream) = request.log_stream.as_deref() {
315 if request.log_group.is_none() {
316 return Err(Error::invalid_arg(
317 "logging.cloudWatch.logStream was configured with no logGroup. The \
318 stream lives inside the group, and with no group configured the \
319 service creates one with random stream names — so a configured \
320 stream alone names a location that does not exist. Configure the \
321 group too, or drop the stream."
322 .to_string(),
323 ));
324 }
325 super::require_valid_log_stream(stream)?;
326 }
327
328 // Every remaining member the model constrains, in the order the request lists them.
329 // Each one is here for the same reason `require_valid_image_name` above is: the
330 // create call happens *after* the caller's artifact upload, so a rejection the
331 // service raises has already cost them the upload. Issue #24 listed all four as
332 // reachable with no guard.
333 //
334 // `baseImageArn` is derived from `BaseImage` and the region, so it cannot be blank
335 // today — checked anyway, because `BaseImage` is a public type with public fields and
336 // a caller can construct one with an empty `name`, which renders an ARN this client
337 // built and the service refuses.
338 // `hooks.port` is deliberately **not** checked here. `ControlPlane::port` is private and
339 // `with_port` is its only setter, and that setter refuses 0 against
340 // `HooksPortInteger.min` — so a plane whose port is illegal cannot exist and a check here
341 // would be a branch no input can reach. An unfalsifiable guard is worse than none: it
342 // reads as protection and no test can make it fire. See
343 // `the_hooks_port_that_reaches_the_wire_is_legal_by_construction`.
344 super::require_valid_role_arn("buildRoleArn", &request.build_role_arn)?;
345 super::require_non_blank("codeArtifact.uri", &request.code_artifact_uri)?;
346 super::require_non_blank("baseImageArn", &request.base_image.arn(&self.region))?;
347 super::require_valid_tags(&request.tags)?;
348
349 // The daemon, when the request carries one (#257). A wrong-architecture daemon builds
350 // cleanly and fails as a run-hook timeout, so this is the one guard here whose
351 // failure AWS would report last rather than first. No bytes means the caller's
352 // `codeArtifact.uri` already holds the daemon (`--artifact-uri`, #249) and nothing of
353 // this request enters an artifact; the bytes that do are refused where they enter one
354 // (`artifact::build_artifact_with_context`).
355 if request.binary.is_empty() {
356 return Ok(());
357 }
358 microvms_domain::provision::require_aarch64(&request.binary)
359 }
360
361 /// The artifact bytes to upload to [`CreateImageRequest::code_artifact_uri`].
362 ///
363 /// Separate from [`ControlPlane::create_image`] because the upload is the caller's — and
364 /// because the byte-scan guard (AC-2-3) needs to inspect these bytes without making a
365 /// control-plane call.
366 pub fn build_artifact_for(&self, request: &CreateImageRequest) -> Result<Vec<u8>, Error> {
367 let dockerfile = self.dockerfile_for(request);
368 artifact::build_artifact(&request.binary, &dockerfile, request.project_files.as_ref())
369 }
370
371 /// The Dockerfile `request` builds with: its own, or the default stanza for its base,
372 /// this plane's port and its project's ecosystem. The one fallback the artifact, its
373 /// content hash and an ensure request built from `request` all take.
374 pub fn dockerfile_for(&self, request: &CreateImageRequest) -> String {
375 match request.dockerfile.as_deref() {
376 Some(dockerfile) => dockerfile.to_string(),
377 None => artifact::default_dockerfile(
378 self.port,
379 None,
380 &request.base_image,
381 request.project_files.as_ref().map(|files| files.ecosystem),
382 ),
383 }
384 }
385
386 /// Polls until the image is usable, distinguishing a stalled build from a slow one.
387 ///
388 /// Returns the image as the service last described it. Raises
389 /// [`ErrorKind::BuildWedged`] for the replay signature (TRAP-2),
390 /// [`ErrorKind::Platform`] for a reported build failure, and [`ErrorKind::Timeout`]
391 /// when the deadline elapses.
392 pub async fn wait_for_image(
393 &self,
394 identifier: &str,
395 size: SizeClass,
396 opts: WaitOpts,
397 ) -> Result<Image, Error> {
398 // Before the loop rather than inside it: an empty identifier would collapse the URI
399 // onto the collection and poll the *listing* until the deadline, which is a 45-minute
400 // timeout about a resource nobody addressed. See `require_valid_identifier`.
401 super::require_valid_identifier("imageIdentifier", identifier)?;
402 let started = self.clock().elapsed();
403 let mut probed = false;
404
405 loop {
406 let call = Call::get("GetMicrovmImage", paths::microvm_image(identifier));
407 let reply = send_with_retry(self.transport(), call).await?;
408 let got: ops::GetMicrovmImageResponseWire = reply.json("GetMicrovmImage")?;
409
410 if Image::is_ready(&got.state) {
411 return Ok(Image {
412 identifier: got.image_arn,
413 name: got.name,
414 version: got.latest_active_image_version.unwrap_or_default(),
415 state: got.state,
416 size,
417 // `None`, not "unknown": `GetMicrovmImage` reports no logging config,
418 // so the wait cannot know one. The create call is the only place the
419 // resolved stream exists, and `Sandbox::build_image` carries the
420 // create's values across this readback for that reason.
421 log_group: None,
422 log_stream: None,
423 });
424 }
425 if Image::is_failed(&got.state) {
426 return Err(self.build_failure(&got).await);
427 }
428
429 let elapsed = self.clock().elapsed().saturating_sub(started);
430 if !probed && elapsed > opts.stall_grace {
431 probed = true;
432 // Raises for the replay signature; returns for anything else, including a
433 // listing that failed.
434 self.probe_stalled_build(identifier, elapsed).await?;
435 }
436 if elapsed >= opts.timeout {
437 return Err(timed_out(
438 &format!(
439 "image {identifier} did not become usable (last state {})",
440 got.state
441 ),
442 elapsed,
443 ));
444 }
445 self.clock().sleep(opts.poll_interval).await;
446 }
447 }
448
449 /// Raises [`ErrorKind::BuildWedged`] when every build is still `PENDING`.
450 ///
451 /// # Why a listing failure is not swallowed silently
452 ///
453 /// The Python probe caught every exception and returned, on the reasoning that a
454 /// best-effort probe must never break the wait (`sandbox.py:879`). That is right about
455 /// the wait and wrong about the diagnosis: a probe that cannot see the build list
456 /// cannot say the build is wedged, but it also should not report "everything is fine".
457 /// So a listing failure is **mapped to retryable and returned as `Ok`** — the wait
458 /// continues, the probe re-arms nothing, and the caller ends up with the honest
459 /// timeout rather than a wedge claim made without evidence.
460 ///
461 /// The distinction that matters is the one the empty-log-group diagnostic makes for
462 /// build failures: unknown is not empty, and a claim made on a throttled API call sends
463 /// the reader after the wrong cause.
464 async fn probe_stalled_build(&self, identifier: &str, elapsed: Duration) -> Result<(), Error> {
465 let Some(builds) = self.builds_of_first_version(identifier).await else {
466 // Could not see the build list. Say nothing rather than guess.
467 return Ok(());
468 };
469
470 if builds.is_empty() {
471 // No builds listed at all is not the signature: the replay case lists builds
472 // and leaves them PENDING. An empty list is a version whose builds have not
473 // been enumerated yet.
474 return Ok(());
475 }
476 // `buildState`, not `state`. The deserializer refuses the other spelling, so this
477 // read cannot silently produce nothing the way `b.get("state")` did.
478 if !builds.iter().all(|build| build.build_state == "PENDING") {
479 return Ok(());
480 }
481
482 Err(Error::new(
483 ErrorKind::BuildWedged,
484 format!(
485 "build never scheduled after {:.0}s: all {} builds are still PENDING ({}). This \
486 is the clientToken replay signature — a clientToken is a permanent idempotency \
487 key, so a create whose token repeats an earlier one is replayed as a no-op: the \
488 image sits in CREATING with its builds never queued, cannot be deleted (CREATING \
489 forbids it), and its only version cannot be dropped either because it is the last \
490 one. Two images were wedged this way for ~15 hours (docs/PLATFORM.md, \
491 '`clientToken` is a permanent idempotency key'). Waiting will not help.",
492 elapsed.as_secs_f64(),
493 builds.len(),
494 builds
495 .iter()
496 .map(ops::MicrovmImageBuildSummaryWire::describe)
497 .collect::<Vec<_>>()
498 .join(", "),
499 ),
500 ))
501 }
502
503 /// Every build of the image's first version, or `None` when the listing could not be
504 /// read.
505 ///
506 /// Two calls — versions, then builds — because `ListMicrovmImageBuilds` requires an
507 /// `imageVersion` in its path.
508 ///
509 /// # Every page, because the verdict is over *all* builds
510 ///
511 /// `ListMicrovmImageBuilds` caps `maxResults` at 50, and [`Self::probe_stalled_build`]
512 /// asserts **all** builds are `PENDING`. Over a truncated page that quantifier is a
513 /// claim about a subset presented as a claim about the set, and it is wrong in both
514 /// directions: 50 pending builds on page one with a scheduled build on page two reads
515 /// as a wedge on a healthy image, and one page of scheduled builds hides a real wedge.
516 /// Since the verdict is a universal, the loop reads to the last page before deciding.
517 async fn builds_of_first_version(
518 &self,
519 identifier: &str,
520 ) -> Option<Vec<ops::MicrovmImageBuildSummaryWire>> {
521 let version = self.first_version(identifier).await?.image_version;
522 self.builds_of_version(identifier, &version).await
523 }
524
525 /// Every build of `version`, or `None` when the listing could not be read.
526 async fn builds_of_version(
527 &self,
528 identifier: &str,
529 version: &str,
530 ) -> Option<Vec<ops::MicrovmImageBuildSummaryWire>> {
531 let mut builds = Vec::new();
532 let mut next_token: Option<String> = None;
533 loop {
534 let call = Call::get(
535 "ListMicrovmImageBuilds",
536 paths::image_builds(identifier, version, next_token.as_deref()),
537 );
538 let page: ops::ListImageBuildsResponseWire = send_with_retry(self.transport(), call)
539 .await
540 .ok()?
541 .json("ListMicrovmImageBuilds")
542 .ok()?;
543 builds.extend(page.items);
544 match page.next_token {
545 Some(token) => next_token = Some(token),
546 None => return Some(builds),
547 }
548 }
549 }
550
551 /// The first version listed, or `None` when the listing could not be read or the image
552 /// has none.
553 ///
554 /// Only the first page is fetched, and that is correct rather than a second instance
555 /// of the same bug: this reads `items.first()`, so a later page cannot change the
556 /// answer. Fetching the rest would be calls whose results are discarded.
557 async fn first_version(&self, identifier: &str) -> Option<ops::MicrovmImageVersionSummaryWire> {
558 let call = Call::get(
559 "ListMicrovmImageVersions",
560 paths::image_versions(identifier, None),
561 );
562 let versions: ops::ListImageVersionsResponseWire = send_with_retry(self.transport(), call)
563 .await
564 .ok()?
565 .json("ListMicrovmImageVersions")
566 .ok()?;
567 versions.items.into_iter().next()
568 }
569
570 /// The message for a build the service reported as failed, with whatever reason the
571 /// service already stated.
572 ///
573 /// # The reasons come first, because the service usually has one
574 ///
575 /// `GetMicrovmImage` has no `stateReason` member — the shape structurally cannot carry
576 /// one — so for a while this message could only name the log group and guess. It does
577 /// not have to guess: `MicrovmImageVersionSummary` and `MicrovmImageBuildSummary` both
578 /// carry a `stateReason`, and `GetMicrovmImage` names the failed version in
579 /// `latestFailedImageVersion`. So two listings the client already knows how to make
580 /// turn "the build failed, here is where the logs would be" into "the build failed
581 /// because X".
582 ///
583 /// The lookup is **best effort**: a listing that cannot be read leaves the reasons out
584 /// and the message keeps its log-group remedy, for the reason
585 /// [`Self::probe_stalled_build`] gives at length — a diagnosis made on a throttled call
586 /// sends the reader after the wrong cause. What it must never do is turn a real build
587 /// failure into a listing error, so nothing here returns `Err`.
588 ///
589 /// # The log-group paragraph stays
590 ///
591 /// It names the required prefix, because a failure that reads as "unknown" is most often
592 /// a build role granted the *plausible* prefix rather than the measured one. This client
593 /// cannot check the log group — CloudWatch is not in its dependency set — so the prefix
594 /// is named whenever no reason was found, rather than unconditionally. That conditional
595 /// is what the reasons above buy back: this used to be "a deliberate weakening" of the
596 /// Python diagnostic precisely because the client had no reason in hand, and now it does.
597 /// The full assessment of why no log *read* happens here is in
598 /// `crates/microvms-cli/src/commands/local.rs`'s `logs`, beside the command a caller reaches
599 /// for instead.
600 async fn build_failure(&self, got: &ops::GetMicrovmImageResponseWire) -> Error {
601 let name = &got.name;
602 let state = &got.state;
603 let reasons = self.failure_reasons(got).await;
604
605 let said = if reasons.is_empty() {
606 format!(
607 "Neither the failed version nor any of its builds carried a stateReason, so the \
608 service stated no cause. If the build log group {BUILD_LOG_GROUP_PREFIX}/{name} \
609 also contains no events, the cause is most likely the build role's log \
610 permissions rather than a silent service: the role must grant logs on the \
611 {BUILD_LOG_GROUP_PREFIX}/* prefix, and a policy granting /aws/lambda/microvms/* \
612 instead — the plausible spelling, and the wrong one — produces builds with no \
613 logs at all (docs/PLATFORM.md, 'Build logs go to \
614 {BUILD_LOG_GROUP_PREFIX}/<image-name>')."
615 )
616 } else {
617 format!(
618 "The service stated the cause: {}. Full build logs are in \
619 {BUILD_LOG_GROUP_PREFIX}/{name}.",
620 reasons.join("; "),
621 )
622 };
623
624 Error::new(
625 ErrorKind::Platform,
626 format!("the image build for {name:?} failed: {state}. {said}"),
627 )
628 }
629
630 /// Every `stateReason` the service already stated about this image's failure: the
631 /// version's, then each failed build's.
632 ///
633 /// Empty when nothing could be read or nothing carried a reason, which the caller
634 /// reports as the service having stated no cause rather than as an absent lookup.
635 async fn failure_reasons(&self, got: &ops::GetMicrovmImageResponseWire) -> Vec<String> {
636 // The version the service itself named as the failed one, falling back to the first
637 // listed — which is what an image whose only version failed looks like.
638 let Some(version) = self.failed_version(got).await else {
639 return Vec::new();
640 };
641
642 let mut reasons = Vec::new();
643 if let Some(reason) = version.state_reason.as_deref() {
644 reasons.push(format!(
645 "version {} is {} because {reason}",
646 version.image_version, version.state
647 ));
648 }
649
650 // The build-level reasons are the specific ones: a version's reason is often "one
651 // or more builds failed", which names the shape of the problem and not the problem.
652 if let Some(builds) = self
653 .builds_of_version(&got.image_arn, &version.image_version)
654 .await
655 {
656 for build in builds
657 .iter()
658 .filter(|build| build.state_reason.is_some() && build.build_state != "PENDING")
659 {
660 reasons.push(format!(
661 "build {}",
662 self.describe_build_deeply(&got.image_arn, &version.image_version, build)
663 .await
664 ));
665 }
666 }
667 reasons
668 }
669
670 /// One failed build, described as fully as the service will say: the listing's line, or
671 /// `GetMicrovmImageBuild`'s richer one when that call answers.
672 ///
673 /// # What the extra call buys, and why it is worth one per failed build
674 ///
675 /// The listing already carries the `stateReason`, so this is not about the reason. It is
676 /// about `snapshotBuild`, which the listing has no member for and which is the **only**
677 /// size any operation in this model reports. On a real failure it comes back **partial** —
678 /// measured 2026-08-16 against a `FAILED` build, `codeInstallSizeInBytes` alone with no
679 /// memory and no disk snapshot — and that partial shape is itself the diagnosis: the build
680 /// installed 1.7 GB of code and then never produced a snapshot, which distinguishes "the
681 /// image was too big / the ready hook never answered" from "the Dockerfile failed before
682 /// anything was installed". It also names the `chipsetGeneration`, which matters because
683 /// one `CreateMicrovmImage` fans out into one build per generation and they can disagree.
684 ///
685 /// # Best effort, in the same sense the rest of this diagnosis is
686 ///
687 /// A `GetMicrovmImageBuild` that fails leaves the listing's own line in place rather than
688 /// dropping the build from the report or turning a build failure into a lookup error. That
689 /// is the rule [`Self::probe_stalled_build`] states at length: a diagnosis made on a
690 /// throttled call sends the reader after the wrong cause, and the reason the listing
691 /// already gave is not made less true by a second call failing.
692 async fn describe_build_deeply(
693 &self,
694 identifier: &str,
695 version: &str,
696 listed: &ops::MicrovmImageBuildSummaryWire,
697 ) -> String {
698 match self
699 .get_image_build(identifier, version, &listed.build_id)
700 .await
701 {
702 Ok(deeper) => deeper.describe(),
703 Err(_) => listed.describe(),
704 }
705 }
706
707 /// The version `latestFailedImageVersion` names, or the first version listed when the
708 /// service named none.
709 async fn failed_version(
710 &self,
711 got: &ops::GetMicrovmImageResponseWire,
712 ) -> Option<ops::MicrovmImageVersionSummaryWire> {
713 let Some(wanted) = got.latest_failed_image_version.as_deref() else {
714 return self.first_version(&got.image_arn).await;
715 };
716
717 let mut next_token: Option<String> = None;
718 loop {
719 let call = Call::get(
720 "ListMicrovmImageVersions",
721 paths::image_versions(&got.image_arn, next_token.as_deref()),
722 );
723 let page: ops::ListImageVersionsResponseWire = send_with_retry(self.transport(), call)
724 .await
725 .ok()?
726 .json("ListMicrovmImageVersions")
727 .ok()?;
728 if let Some(hit) = page
729 .items
730 .into_iter()
731 .find(|item| item.image_version == wanted)
732 {
733 return Some(hit);
734 }
735 next_token = Some(page.next_token?);
736 }
737 }
738
739 // ── build and version introspection ──────────────────────────────────────
740
741 /// `GetMicrovmImageBuild`: one build, with the snapshot sizes the listing does not carry.
742 ///
743 /// # What this adds over the listing, and it is not marginal
744 ///
745 /// `snapshotBuild` — the memory, code, and disk byte counts — is the **only** size any
746 /// operation in this model reports for anything the platform builds. `GetMicrovmImage`
747 /// carries none, `GetMicrovm` carries none, and both listings carry none, so a storage
748 /// estimate had nothing to multiply but the size class's baseline. These three figures are
749 /// what the snapshot read, write, and storage line items actually bill on.
750 ///
751 /// It also carries a `stateReason` at the same level the listing does, which is the level
752 /// that is populated on a real failure — the version's is null (docs/PLATFORM.md).
753 ///
754 /// `build_id` comes off [`ops::MicrovmImageBuildSummaryWire::build_id`], which the listing
755 /// already parses; nothing else in the API mints one.
756 pub async fn get_image_build(
757 &self,
758 identifier: &str,
759 version: &str,
760 build_id: &str,
761 ) -> Result<ops::GetImageBuildResponseWire, Error> {
762 super::require_valid_identifier("imageIdentifier", identifier)?;
763 // Both URI members are `NonBlankString`, not `Version` — `GetMicrovmImageBuild` is the
764 // one operation where `imageVersion` names the reused shape rather than the version one,
765 // and the two are identical today. Checked as what the model says they are.
766 super::require_non_blank("imageVersion", version)?;
767 super::require_non_blank("buildId", build_id)?;
768 let call = Call::get(
769 "GetMicrovmImageBuild",
770 paths::image_build(identifier, version, build_id),
771 );
772 let reply = send_with_retry(self.transport(), call).await?;
773 reply.json("GetMicrovmImageBuild")
774 }
775
776 /// `GetMicrovmImageVersion`: one version's whole configuration, its state, and its
777 /// availability status.
778 ///
779 /// # The only full config readback there is
780 ///
781 /// The response echoes the creation request: `baseImageArn` with the `baseImageVersion`
782 /// that was actually used, the `buildRoleArn`, the `codeArtifact` URI, the egress
783 /// connectors, the CPU configurations, and `resources` — which is where a built image's
784 /// size class lives, since `GetMicrovm` reports no memory figure at all. It is how a
785 /// caller who no longer holds the request finds out what an image was built with.
786 ///
787 /// `status` is the member that matters for a retire: `ACTIVE` means `RunMicrovm` will
788 /// launch this version, `INACTIVE` means it refuses. See
789 /// [`Self::set_image_version_status`].
790 ///
791 /// One call rather than a filtered `ListMicrovmImageVersions`, and the difference is not
792 /// only cost: a listing can page, so "find version X" is a loop that may read the whole
793 /// history, while this addresses the version directly and answers
794 /// `ResourceNotFoundException` when it is gone.
795 pub async fn get_image_version(
796 &self,
797 identifier: &str,
798 version: &str,
799 ) -> Result<ops::MicrovmImageVersionSummaryWire, Error> {
800 super::require_valid_identifier("imageIdentifier", identifier)?;
801 super::require_non_blank("imageVersion", version)?;
802 let call = Call::get(
803 "GetMicrovmImageVersion",
804 paths::image_version(identifier, version),
805 );
806 let reply = send_with_retry(self.transport(), call).await?;
807 reply.json("GetMicrovmImageVersion")
808 }
809
810 /// `UpdateMicrovmImageVersion`: set a version `ACTIVE` or `INACTIVE`.
811 ///
812 /// # The model's only non-destructive retire
813 ///
814 /// `DeleteMicrovmImageVersion` is the alternative and it is irreversible, cannot be
815 /// applied to an image's last version at all, and destroys the readback a post-mortem
816 /// needs. `INACTIVE` does none of that: `RunMicrovm` refuses to launch the version,
817 /// **already-running VMs keep running**, and [`Self::get_image_version`] still answers
818 /// with the whole configuration. So the rollback for a bad build is two calls that both
819 /// preserve evidence — set the new version INACTIVE, re-pin the launch to the old one —
820 /// rather than a delete.
821 ///
822 /// # Why the status is typed and the version is checked
823 ///
824 /// [`ops::VersionStatus`] has two variants, so `"INACTIVATE"` is a compile error rather
825 /// than a `ValidationException` on the only member this request has. The version string is
826 /// checked against the `Version` shape locally for the reason
827 /// [`super::require_valid_version`] gives: this call is made at the moment someone is
828 /// rolling back, which is when a failure about the request rather than about the version
829 /// is most expensive.
830 ///
831 /// Returns the readback, which carries the status the service now reports — so a caller
832 /// confirms the change rather than assuming the 200 meant it took.
833 pub async fn set_image_version_status(
834 &self,
835 identifier: &str,
836 version: &str,
837 status: ops::VersionStatus,
838 ) -> Result<ops::MicrovmImageVersionSummaryWire, Error> {
839 super::require_valid_identifier("imageIdentifier", identifier)?;
840 super::require_valid_version("imageVersion", version)?;
841
842 let wire = ops::UpdateImageVersionWire { status };
843 let call = Call::patch_json(
844 "UpdateMicrovmImageVersion",
845 paths::image_version(identifier, version),
846 &wire,
847 )?;
848 let reply = send_with_retry(self.transport(), call).await?;
849 let updated: ops::MicrovmImageVersionSummaryWire =
850 reply.json("UpdateMicrovmImageVersion")?;
851
852 // The readback is asserted rather than trusted, for the reason
853 // `ops::DeleteImageResponseWire` gives about a 2xx that reports a failure state: a
854 // request the service accepts and does not apply is indistinguishable from one it
855 // applied, and here the consequence is a version a caller believes is retired while
856 // `RunMicrovm` still launches it.
857 if updated.status != status.as_str() {
858 return Err(Error::new(
859 ErrorKind::Platform,
860 format!(
861 "UpdateMicrovmImageVersion answered 2xx for version {version} of \
862 {identifier} but read back status {} rather than the requested {status}. A \
863 version that is still ACTIVE is one RunMicrovm will still launch, so \
864 treating the 200 as the change having taken would leave a retired version \
865 reachable.",
866 updated.status,
867 ),
868 ));
869 }
870 Ok(updated)
871 }
872
873 /// `ListManagedMicrovmImageVersions`, read to its last page: the versions of a managed
874 /// base image, newest first as the service orders them.
875 ///
876 /// # What this is for
877 ///
878 /// [`ops::CreateMicrovmImageWire::base_image_version`] is how a build stops floating on
879 /// whatever the service currently defaults to, and this is the only operation that says
880 /// what the legal values are. The default has already moved once: `al2023-1` carried one
881 /// version in June and two by July (`"0"` and `"1"`, measured 2026-08-16), so every build
882 /// made before this existed recorded no base version and is not reproducible.
883 ///
884 /// # Every page, and an ARN rather than a name
885 ///
886 /// Every page for the reason the other listings give: a version on page two is still a
887 /// version, and a caller pinning "the newest" from a truncated page pins the wrong one.
888 ///
889 /// The identifier must be the base's **full ARN** — a bare `al2023-1` answers
890 /// `ValidationException: Invalid ARN format` (measured 2026-08-16) — so that is checked
891 /// here rather than at the wire, because the service's message names the value without
892 /// saying which member wanted an ARN or that
893 /// [`super::BaseImage::arn`] is what produces one.
894 pub async fn managed_base_versions(
895 &self,
896 base_image_arn: &str,
897 ) -> Result<Vec<ops::ManagedMicrovmImageVersionWire>, Error> {
898 // The shape bound first, then the ARN precondition. Order matters only for the empty
899 // case: `""` is not an ARN either, and "needs the full ARN, not \"\"" is a less useful
900 // message than the identifier guard's account of what an empty URI parameter does to the
901 // path.
902 super::require_valid_identifier("imageIdentifier", base_image_arn)?;
903 if !base_image_arn.starts_with("arn:") {
904 return Err(Error::new(
905 ErrorKind::Precondition,
906 format!(
907 "ListManagedMicrovmImageVersions needs the managed base's full ARN, not \
908 {base_image_arn:?}. The service answers `ValidationException: Invalid ARN \
909 format: {base_image_arn}` for a bare name (measured 2026-08-16), which \
910 names the value without saying which member wanted an ARN. \
911 `BaseImage::al2023().arn(region)` builds one — \
912 arn:aws:lambda:{}:aws:microvm-image:{base_image_arn}.",
913 self.region.as_str(),
914 ),
915 ));
916 }
917
918 let mut items = Vec::new();
919 let mut next_token: Option<String> = None;
920 loop {
921 let call = Call::get(
922 "ListManagedMicrovmImageVersions",
923 paths::managed_image_versions(base_image_arn, next_token.as_deref()),
924 );
925 let reply = send_with_retry(self.transport(), call).await?;
926 let page: ops::ListManagedVersionsResponseWire =
927 reply.json("ListManagedMicrovmImageVersions")?;
928 items.extend(page.items);
929 match page.next_token {
930 Some(token) => next_token = Some(token),
931 None => return Ok(items),
932 }
933 }
934 }
935
936 /// `ListManagedMicrovmImages`, read to its last page: the base images AWS publishes.
937 ///
938 /// # Informational only, and that is a limitation rather than a choice
939 ///
940 /// `ManagedMicrovmImageSummary` carries an ARN and two timestamps and **nothing else** —
941 /// no registry reference, no architecture, no working directory. A
942 /// [`super::BaseImage`] needs all three of ARN, Dockerfile `FROM`, and WORKDIR knowledge,
943 /// because `require_matching_from` compares a caller's Dockerfile against the `FROM` and
944 /// `require_workdir` refuses inheritance when the base declares none. Neither guard has an
945 /// input here, and the registry ref is not derivable from the ARN — `al2023-1` pairs with
946 /// `public.ecr.aws/amazonlinux/amazonlinux:2023-minimal` and nothing in the ARN says so.
947 ///
948 /// So a discovered base **cannot safely be built from**, and this exists to answer one
949 /// question: has AWS published a base this client does not know about? `microvm doctor`
950 /// reports it. Measured 2026-08-16, the answer is one item, so hardcoding `al2023-1`
951 /// currently misses nothing.
952 pub async fn managed_base_images(
953 &self,
954 ) -> Result<Vec<ops::ManagedMicrovmImageSummaryWire>, Error> {
955 let mut items = Vec::new();
956 let mut next_token: Option<String> = None;
957 loop {
958 let call = Call::get(
959 "ListManagedMicrovmImages",
960 paths::managed_microvm_images(next_token.as_deref()),
961 );
962 let reply = send_with_retry(self.transport(), call).await?;
963 let page: ops::ListManagedImagesResponseWire =
964 reply.json("ListManagedMicrovmImages")?;
965 items.extend(page.items);
966 match page.next_token {
967 Some(token) => next_token = Some(token),
968 None => return Ok(items),
969 }
970 }
971 }
972
973 /// One page of `ListManagedMicrovmImages`: whether the service answers a signed,
974 /// free, read-only request in this region (BIND-15's service check), and how many managed
975 /// bases the page carried.
976 ///
977 /// One operation, never the whole listing, so a preflight makes one AWS operation at most
978 /// (BIND-16); `send_with_retry` may repeat it on a throttle. An unsupported region answers
979 /// `AccessDeniedException` with a null message (TRAP-6), which this surfaces as the error
980 /// it is.
981 pub async fn answers_listing(&self) -> Result<usize, Error> {
982 let call = Call::get(
983 "ListManagedMicrovmImages",
984 paths::managed_microvm_images(None),
985 );
986 let reply = send_with_retry(self.transport(), call).await?;
987 let page: ops::ListManagedImagesResponseWire = reply.json("ListManagedMicrovmImages")?;
988 Ok(page.items.len())
989 }
990
991 /// Resolves the credentials this client signs with, sending nothing to the service
992 /// (BIND-15's credentials check). See [`super::transport::Transport::resolve_credentials`].
993 pub async fn resolve_credentials(&self) -> Result<(), Error> {
994 self.transport().resolve_credentials().await
995 }
996
997 /// `ListMicrovmImages`, read to its last page.
998 ///
999 /// # Why this is public where the private walkers are not
1000 ///
1001 /// [`Self::find_image_by_name`] sends `nameFilter` and answers one image, which is what a
1002 /// resolver wants and is a different question from "what is in this account". The live tier
1003 /// asks the second: `tests/live_versions.rs` walks the account looking for an image with a
1004 /// version in a particular state, because *which* image that is is an account fact a test
1005 /// must not hardcode. `microvm ls` deliberately does **not** use this — it reads the local
1006 /// ledger, because the resources worth asking about are the ones a killed process never got
1007 /// to report and no listing can attribute those back to a command.
1008 pub async fn list_images(&self) -> Result<Vec<ops::MicrovmImageSummaryWire>, Error> {
1009 let mut items = Vec::new();
1010 let mut next_token: Option<String> = None;
1011 loop {
1012 let call = Call::get(
1013 "ListMicrovmImages",
1014 paths::microvm_images_list(None, next_token.as_deref()),
1015 );
1016 let reply = send_with_retry(self.transport(), call).await?;
1017 let page: ops::ListImagesResponseWire = reply.json("ListMicrovmImages")?;
1018 items.extend(page.items);
1019 match page.next_token {
1020 Some(token) => next_token = Some(token),
1021 None => return Ok(items),
1022 }
1023 }
1024 }
1025
1026 /// `ListMicrovmImageVersions`, read to its last page.
1027 ///
1028 /// A `Result` where the private [`Self::builds_of_version`] answers `Option`, and the
1029 /// difference is the caller: the private one feeds a *diagnosis*, where a listing failure
1030 /// must not become a wedge claim, and this one feeds a caller who asked about the versions
1031 /// and needs to know if the answer is unavailable.
1032 pub async fn list_image_versions(
1033 &self,
1034 identifier: &str,
1035 ) -> Result<Vec<ops::MicrovmImageVersionSummaryWire>, Error> {
1036 super::require_valid_identifier("imageIdentifier", identifier)?;
1037 let mut items = Vec::new();
1038 let mut next_token: Option<String> = None;
1039 loop {
1040 let call = Call::get(
1041 "ListMicrovmImageVersions",
1042 paths::image_versions(identifier, next_token.as_deref()),
1043 );
1044 let reply = send_with_retry(self.transport(), call).await?;
1045 let page: ops::ListImageVersionsResponseWire =
1046 reply.json("ListMicrovmImageVersions")?;
1047 items.extend(page.items);
1048 match page.next_token {
1049 Some(token) => next_token = Some(token),
1050 None => return Ok(items),
1051 }
1052 }
1053 }
1054
1055 /// `ListMicrovmImageBuilds` for one version, read to its last page.
1056 ///
1057 /// The identifiers [`Self::get_image_build`] takes come from here: nothing else in the API
1058 /// mints a `buildId`. See [`Self::list_image_versions`] on why this answers a `Result` where
1059 /// the diagnosis path's walker answers an `Option`.
1060 pub async fn list_image_builds(
1061 &self,
1062 identifier: &str,
1063 version: &str,
1064 ) -> Result<Vec<ops::MicrovmImageBuildSummaryWire>, Error> {
1065 super::require_valid_identifier("imageIdentifier", identifier)?;
1066 super::require_non_blank("imageVersion", version)?;
1067 let mut items = Vec::new();
1068 let mut next_token: Option<String> = None;
1069 loop {
1070 let call = Call::get(
1071 "ListMicrovmImageBuilds",
1072 paths::image_builds(identifier, version, next_token.as_deref()),
1073 );
1074 let reply = send_with_retry(self.transport(), call).await?;
1075 let page: ops::ListImageBuildsResponseWire = reply.json("ListMicrovmImageBuilds")?;
1076 items.extend(page.items);
1077 match page.next_token {
1078 Some(token) => next_token = Some(token),
1079 None => return Ok(items),
1080 }
1081 }
1082 }
1083
1084 /// The image with exactly `name`, or `None` when no page of the listing has one.
1085 ///
1086 /// # `nameFilter` narrows, it does not answer
1087 ///
1088 /// The model's `nameFilter` is a server-side **substring** filter ("images whose name
1089 /// contains the specified string"), so `coding-agents` also matches
1090 /// `coding-agents-old`. The filter is sent — it keeps a large account's listing to one
1091 /// page in practice — and the exact-match comparison happens here, on the client,
1092 /// because "contains" and "is" are different questions and only the second one is
1093 /// safe to launch from.
1094 ///
1095 /// # The listing paginates, and every page is read
1096 ///
1097 /// An image on page two is still an image. A resolver that read only the first page
1098 /// would answer "no image named X" for a name that exists — the confident wrong
1099 /// answer, which then sends the caller to rebuild an image they already paid for.
1100 pub async fn find_image_by_name(
1101 &self,
1102 name: &str,
1103 ) -> Result<Option<ops::MicrovmImageSummaryWire>, Error> {
1104 // `nameFilter` is a `NonBlankString` **querystring** member, which is the reason a blank
1105 // one is worth refusing rather than letting through: it does not fail as a missing field,
1106 // it goes out as `?nameFilter=` and either 400s or filters differently from what was
1107 // meant. This function is the resolver a launch depends on, so a silently different
1108 // filter is a launch against the wrong image.
1109 super::require_non_blank("nameFilter", name)?;
1110 let mut next_token: Option<String> = None;
1111 loop {
1112 let call = Call::get(
1113 "ListMicrovmImages",
1114 paths::microvm_images_list(Some(name), next_token.as_deref()),
1115 );
1116 let reply = send_with_retry(self.transport(), call).await?;
1117 let listed: ops::ListImagesResponseWire = reply.json("ListMicrovmImages")?;
1118
1119 if let Some(hit) = listed.items.into_iter().find(|item| item.name == name) {
1120 return Ok(Some(hit));
1121 }
1122 match listed.next_token {
1123 Some(token) => next_token = Some(token),
1124 None => return Ok(None),
1125 }
1126 }
1127 }
1128
1129 /// The ARN for `identifier`: an ARN passes through untouched, a bare name is
1130 /// resolved through the image listing by exact name.
1131 ///
1132 /// # Why this exists
1133 ///
1134 /// `RunMicrovm.imageIdentifier` takes an ARN, and a bare name sent verbatim is
1135 /// answered with HTTP 400 "Malformed ARN" — after a credential resolution and a
1136 /// signed call, and with a message that says nothing about names. Every consumer was
1137 /// scripting this resolution with the AWS CLI (the coding-agents example did); this
1138 /// is that script, once, with the pagination handled.
1139 ///
1140 /// # An ARN costs zero calls
1141 ///
1142 /// The passthrough is checked first, so a caller who already holds the ARN pays
1143 /// nothing for the convenience existing. The prefix test is `arn:` exactly — the one
1144 /// spelling every AWS ARN starts with, and a string the `ImageName` pattern
1145 /// (`[a-zA-Z0-9-_]+`) cannot produce, so no legal image name is mistaken for one.
1146 pub async fn resolve_image_arn(&self, identifier: &str) -> Result<String, Error> {
1147 if identifier.starts_with("arn:") {
1148 return Ok(identifier.to_string());
1149 }
1150 match self.find_image_by_name(identifier).await? {
1151 Some(image) => Ok(image.image_arn),
1152 None => Err(Error::new(
1153 ErrorKind::Precondition,
1154 format!(
1155 "no image named {identifier:?} exists in {} (the listing was read to its \
1156 last page and resolution requires an exact name match). Build one first — \
1157 `microvm build <binary> --name {identifier}` — or pass the image ARN \
1158 directly.",
1159 self.region.as_str(),
1160 ),
1161 )),
1162 }
1163 }
1164
1165 /// The content hash of the artifact `request` would build, for content-addressed
1166 /// image reuse.
1167 ///
1168 /// Derives the Dockerfile exactly as [`ControlPlane::build_artifact_for`] does —
1169 /// same default, same port — so the name a reuse check computes is the name a build
1170 /// of the same request would carry. See [`artifact::artifact_content_hash`] for what
1171 /// is hashed and why it is the inputs rather than the zip.
1172 pub fn artifact_content_hash_for(&self, request: &CreateImageRequest) -> String {
1173 let dockerfile = self.dockerfile_for(request);
1174 artifact::artifact_content_hash(
1175 &request.binary,
1176 &dockerfile,
1177 request.project_files.as_ref(),
1178 )
1179 }
1180
1181 /// Deletes every version but the first, then the image, retrying.
1182 ///
1183 /// # Why it retries
1184 ///
1185 /// Not politeness: an image in `CREATING` refuses deletion and a VM still terminating
1186 /// holds a reference. This loop is the difference between a clean account and a billed
1187 /// leak.
1188 ///
1189 /// # Why not `backon`, unlike `transport::send_with_retry`
1190 ///
1191 /// Assessed for the dependency sweep (issue #91) and kept as a loop: the sleeps here
1192 /// go through the injected [`Clock`] seam so tests drive them without real time, and
1193 /// `Clock::sleep` returns a future borrowing `&self` — `backon`'s `Sleeper` needs a
1194 /// future that owns its state, so bridging the seam costs an adapter bigger than the
1195 /// five lines it would replace. The fixed interval is also the contract: teardown
1196 /// polls a state that resolves on the service's schedule, not a growing backoff.
1197 ///
1198 /// # Why the first version is kept
1199 ///
1200 /// The last remaining version cannot be deleted on its own, only together with the
1201 /// image. Trying produces a `ConflictException` that reads like a permissions problem.
1202 ///
1203 /// Returns `true` when the image was deleted, `false` when every attempt failed. It
1204 /// does not raise, because the caller is a teardown path and the original failure is
1205 /// the one worth reading.
1206 ///
1207 /// # The identifier check is here rather than in [`Self::try_delete_image`]
1208 ///
1209 /// Inside the attempt it would be re-decided on every retry, which for the default twenty
1210 /// attempts is nineteen backoff sleeps over a value that cannot become valid. Before the loop
1211 /// it costs one comparison and zero calls. The refusal is a `false` rather than an `Err`
1212 /// because this function's whole contract is that it does not raise into a teardown path —
1213 /// and `false` from here is honest: no image was deleted.
1214 pub async fn delete_image(&self, identifier: &str, attempts: u32, backoff: Duration) -> bool {
1215 if super::require_valid_identifier("imageIdentifier", identifier).is_err() {
1216 return false;
1217 }
1218 for attempt in 0..attempts.max(1) {
1219 if attempt > 0 {
1220 self.clock().sleep(backoff).await;
1221 }
1222 if self.try_delete_image(identifier).await.is_ok() {
1223 return true;
1224 }
1225 }
1226 false
1227 }
1228
1229 /// One deletion attempt: drop the extra versions, then the image.
1230 ///
1231 /// # Every page of versions, or the image cannot be deleted at all
1232 ///
1233 /// `ListMicrovmImageVersions` caps `maxResults` at 50. Reading one page and then
1234 /// deleting the image is not a partial cleanup, it is a **permanent** one: the versions
1235 /// on page two still exist, so the final `DeleteMicrovmImage` answers
1236 /// `ConflictException`, [`Self::delete_image`]'s retry loop re-reads the same first
1237 /// page every attempt, and the call returns `false` forever. The outcome is a billing
1238 /// image nothing can delete through this client, which is the exact outcome the retry
1239 /// loop exists to prevent.
1240 ///
1241 /// The whole listing is collected before the first delete rather than deleted
1242 /// page-by-page, because deleting from under a cursor is how a paginated traversal
1243 /// skips items: the service's page boundaries move as the collection shrinks.
1244 async fn try_delete_image(&self, identifier: &str) -> Result<(), Error> {
1245 let mut versions: Vec<String> = Vec::new();
1246 let mut next_token: Option<String> = None;
1247 loop {
1248 let call = Call::get(
1249 "ListMicrovmImageVersions",
1250 paths::image_versions(identifier, next_token.as_deref()),
1251 );
1252 let page: ops::ListImageVersionsResponseWire = send_with_retry(self.transport(), call)
1253 .await?
1254 .json("ListMicrovmImageVersions")?;
1255 versions.extend(page.items.into_iter().map(|item| item.image_version));
1256 match page.next_token {
1257 Some(token) => next_token = Some(token),
1258 None => break,
1259 }
1260 }
1261
1262 // Skip the first: the last remaining version goes with the image.
1263 for version in versions.iter().skip(1) {
1264 let call = Call::delete(
1265 "DeleteMicrovmImageVersion",
1266 paths::image_version(identifier, version),
1267 );
1268 send_with_retry(self.transport(), call).await?;
1269 }
1270
1271 let call = Call::delete("DeleteMicrovmImage", paths::microvm_image(identifier));
1272 let reply = send_with_retry(self.transport(), call).await?;
1273
1274 // The readback is parsed rather than discarded, so `DeleteImageResponseWire` is a
1275 // live shape. See [`ops::DeleteImageResponseWire`] for why the state is checked
1276 // for a *failure* spelling only: DELETING and DELETED are both the call having
1277 // worked, and treating DELETING as incomplete would retry a deletion in progress.
1278 let deleted: ops::DeleteImageResponseWire = reply.json("DeleteMicrovmImage")?;
1279 if Image::is_failed(&deleted.state) {
1280 return Err(Error::new(
1281 ErrorKind::Platform,
1282 format!(
1283 "DeleteMicrovmImage answered 2xx for {} but reported state {}, so the image \
1284 still exists and still bills. A DELETE_FAILED readback is the service \
1285 accepting the request and refusing the work, which is not something a retry \
1286 of the identical request fixes.",
1287 deleted.image_identifier, deleted.state,
1288 ),
1289 ));
1290 }
1291 Ok(())
1292 }
1293}
1294
1295#[cfg(test)]
1296mod tests {
1297 use std::sync::Arc;
1298
1299 use super::super::fake::{self as fake, Answer, FakeControlPlane, TestClock};
1300 use super::*;
1301 use crate::hooks::{BuildHookTimeout, RunHookTimeout};
1302 use crate::region::Region;
1303
1304 /// A plane over the fake, and the two handles a test asserts through.
1305 fn planted() -> (ControlPlane, Arc<FakeControlPlane>, Arc<TestClock>) {
1306 let fake = Arc::new(FakeControlPlane::new());
1307 let clock = Arc::new(TestClock::new());
1308 let plane = crate::testing::control_plane(fake.clone(), Region::UsEast1, clock.clone());
1309 (plane, fake, clock)
1310 }
1311
1312 fn a_request() -> CreateImageRequest {
1313 CreateImageRequest::new(
1314 "agentd-conformance",
1315 crate::testing::aarch64_daemon(b"fake daemon"),
1316 "s3://bucket/agentd-conformance.zip",
1317 "arn:aws:iam::123456789012:role/build",
1318 )
1319 }
1320
1321 /// The create request lands on the model's path and method, and its body carries the
1322 /// model's member names. Asserted through the recorder's generic JSON view, so a
1323 /// misspelled member here is visible rather than hidden by a matching struct.
1324 #[tokio::test]
1325 async fn create_image_emits_the_models_path_method_and_members() {
1326 let (plane, fake, _) = planted();
1327 fake.answer(
1328 "CreateMicrovmImage",
1329 Answer::created(fake::create_image_response("agentd-conformance")),
1330 );
1331
1332 let image = plane.create_image(a_request()).await.expect("creates");
1333 assert_eq!(image.name, "agentd-conformance");
1334 assert_eq!(image.state, "CREATING");
1335 assert_eq!(image.version, "1");
1336
1337 let calls = fake.calls();
1338 assert_eq!(calls.len(), 1);
1339 assert_eq!(calls[0].method, super::super::transport::Method::Post);
1340 assert_eq!(calls[0].path, "/2025-09-09/microvm-images");
1341
1342 let body = fake.first_body("CreateMicrovmImage");
1343 assert_eq!(body["name"], "agentd-conformance");
1344 assert_eq!(
1345 body["baseImageArn"],
1346 "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"
1347 );
1348 assert_eq!(
1349 body["codeArtifact"]["uri"],
1350 "s3://bucket/agentd-conformance.zip"
1351 );
1352 assert_eq!(body["cpuConfigurations"][0]["architecture"], "ARM_64");
1353 assert_eq!(body["resources"][0]["minimumMemoryInMiB"], 2048);
1354 assert_eq!(body["hooks"]["port"], 9000);
1355 }
1356
1357 /// **TRAP-3.** Identity repair sets `additionalOsCapabilities` to exactly `["ALL"]`,
1358 /// and the field is **absent** when repair was not requested.
1359 ///
1360 /// Read off the wire member, which is the assertion that matters: a bool field on the
1361 /// request type proves nothing about what got emitted.
1362 ///
1363 /// **Falsification** — change the injection to a caller-supplied list and there is no
1364 /// longer a bool to set, so this test does not compile; change it to emit
1365 /// `["CAP_SYS_ADMIN"]` and the first assertion fails.
1366 #[tokio::test]
1367 async fn identity_repair_sets_the_one_accepted_capability_and_nothing_else() {
1368 let (plane, fake, _) = planted();
1369 fake.answer(
1370 "CreateMicrovmImage",
1371 Answer::created(fake::create_image_response("img")),
1372 );
1373 let mut request = a_request();
1374 request.repair_guest_identity = true;
1375 plane.create_image(request).await.expect("creates");
1376
1377 let body = fake.first_body("CreateMicrovmImage");
1378 assert_eq!(
1379 body["additionalOsCapabilities"],
1380 serde_json::json!(["ALL"]),
1381 "the Capability enum has exactly one value"
1382 );
1383
1384 let (plane, fake, _) = planted();
1385 fake.answer(
1386 "CreateMicrovmImage",
1387 Answer::created(fake::create_image_response("img")),
1388 );
1389 plane.create_image(a_request()).await.expect("creates");
1390 let body = fake.first_body("CreateMicrovmImage");
1391 assert!(
1392 body.get("additionalOsCapabilities").is_none(),
1393 "omitted rather than empty when repair was not asked for: {body}"
1394 );
1395 }
1396
1397 /// **TRAP-1, observed on the wire.** Creating the same image name twice emits two
1398 /// distinct `clientToken` values, as the fake saw them.
1399 ///
1400 /// This is the create-delete-recreate case: same name, same bytes, same scope. A token
1401 /// derived from any of those would repeat and wedge the image.
1402 ///
1403 /// **Falsification** — replace the nonce with a digest of the scope and this fails
1404 /// with two identical tokens.
1405 #[tokio::test]
1406 async fn recreating_the_same_image_name_emits_two_distinct_client_tokens() {
1407 let (plane, fake, _) = planted();
1408 fake.answer(
1409 "CreateMicrovmImage",
1410 Answer::created(fake::create_image_response("img")),
1411 );
1412
1413 plane.create_image(a_request()).await.expect("first create");
1414 plane.create_image(a_request()).await.expect("recreate");
1415
1416 let tokens = fake.client_tokens();
1417 assert_eq!(tokens.len(), 2, "both creates carried a token");
1418 assert_ne!(
1419 tokens[0], tokens[1],
1420 "a repeated clientToken wedges the image in CREATING for ~15 hours"
1421 );
1422 for token in &tokens {
1423 assert!(token.starts_with("create-"), "{token}");
1424 assert!(
1425 token.len() <= crate::constants::MAX_CLIENT_TOKEN_LEN,
1426 "{token}"
1427 );
1428 }
1429 }
1430
1431 /// The token's label follows `token_scope` when one is given — the CloudTrail
1432 /// readability affordance — and the token is still per-attempt distinct.
1433 #[tokio::test]
1434 async fn a_token_scope_labels_the_token_without_becoming_it() {
1435 let (plane, fake, _) = planted();
1436 fake.answer(
1437 "CreateMicrovmImage",
1438 Answer::created(fake::create_image_response("img")),
1439 );
1440 let mut request = a_request();
1441 request.token_scope = Some("nightly-run-42".to_string());
1442 plane.create_image(request.clone()).await.expect("creates");
1443 plane.create_image(request).await.expect("creates again");
1444
1445 let tokens = fake.client_tokens();
1446 assert!(tokens[0].contains("nightly-run-42"), "{}", tokens[0]);
1447 assert_ne!(tokens[0], tokens[1], "the label is not the token");
1448 }
1449
1450 /// **A create draws its log-stream discriminator and its client-token nonce from the
1451 /// plane's entropy**, stream first, so a swapped source decides both.
1452 ///
1453 /// **Falsification**: resolve either through `OsEntropy` instead of `self.entropy()` and
1454 /// its assertion reads a value the scripted source never produced.
1455 #[tokio::test]
1456 async fn a_create_draws_its_random_values_from_the_planes_entropy() {
1457 use crate::entropy::testing::SequenceEntropy;
1458 let fake = Arc::new(FakeControlPlane::new());
1459 let plane = crate::testing::control_plane(
1460 fake.clone(),
1461 Region::UsEast1,
1462 Arc::new(TestClock::new()),
1463 )
1464 .with_entropy(Arc::new(SequenceEntropy::new()));
1465 fake.answer(
1466 "CreateMicrovmImage",
1467 Answer::created(fake::create_image_response("img")),
1468 );
1469 let mut request = a_request();
1470 request.log_group = Some("/aws/lambda-microvms/conformance-builds".to_string());
1471 request.log_stream = Some("ci-image".to_string());
1472
1473 plane.create_image(request).await.expect("creates");
1474
1475 let body = fake.first_body("CreateMicrovmImage");
1476 let draw = |n| const_hex::encode(SequenceEntropy::draw(n, 8));
1477 assert_eq!(
1478 body["logging"]["cloudWatch"]["logStream"],
1479 format!("ci-image/{}", draw(1))
1480 );
1481 assert_eq!(
1482 body["clientToken"],
1483 format!("create-agentd-conformance-{}", draw(2))
1484 );
1485 }
1486
1487 /// An unavailable source refuses the create before anything reaches the plane.
1488 #[tokio::test]
1489 async fn an_unavailable_entropy_source_refuses_the_create() {
1490 use crate::entropy::testing::SequenceEntropy;
1491 let fake = Arc::new(FakeControlPlane::new());
1492 let plane = crate::testing::control_plane(
1493 fake.clone(),
1494 Region::UsEast1,
1495 Arc::new(TestClock::new()),
1496 )
1497 .with_entropy(Arc::new(SequenceEntropy::unavailable()));
1498 let err = plane
1499 .create_image(a_request())
1500 .await
1501 .expect_err("no pool, no client token");
1502 assert_eq!(err.kind(), crate::error::ErrorKind::Unexpected, "{err}");
1503 assert!(fake.calls().is_empty());
1504 }
1505
1506 /// **The discriminator rule, observed on the wire.** A configured log stream reaches
1507 /// `CreateMicrovmImage` as `<user value>/<16 hex>` — never verbatim — and the resolved
1508 /// name on the returned [`Image`] is byte-identical to what went out.
1509 ///
1510 /// Asserted on the serialized body through the recorder's generic JSON view, because
1511 /// the claim is about what the service sees: the member is an exact stream name, one
1512 /// build is three VMs writing three streams, and a verbatim configured name collapses
1513 /// them all (docs/PLATFORM.md, 'An image build is three VMs and three log streams').
1514 ///
1515 /// **Falsification** — pass `request.log_stream` straight into `Logging::cloud_watch`
1516 /// instead of through `token::resolve_log_stream` and the suffix assertions go red
1517 /// with the verbatim name on the wire. Done 2026-08-30; failed as stated; restored.
1518 #[tokio::test]
1519 async fn a_configured_log_stream_reaches_the_wire_with_a_fresh_discriminator() {
1520 let (plane, fake, _) = planted();
1521 fake.answer(
1522 "CreateMicrovmImage",
1523 Answer::created(fake::create_image_response("img")),
1524 );
1525 let mut request = a_request();
1526 request.log_group = Some("/aws/lambda-microvms/conformance-builds".to_string());
1527 request.log_stream = Some("ci-image".to_string());
1528
1529 let image = plane.create_image(request).await.expect("creates");
1530
1531 let body = fake.first_body("CreateMicrovmImage");
1532 assert_eq!(
1533 body["logging"]["cloudWatch"]["logGroup"],
1534 "/aws/lambda-microvms/conformance-builds"
1535 );
1536 let wire_stream = body["logging"]["cloudWatch"]["logStream"]
1537 .as_str()
1538 .expect("a stream was sent");
1539 assert_ne!(
1540 wire_stream, "ci-image",
1541 "the caller's value must never reach the wire verbatim"
1542 );
1543 assert!(
1544 wire_stream.starts_with("ci-image/"),
1545 "the caller's value survives as the prefix: {wire_stream}"
1546 );
1547 let suffix = &wire_stream["ci-image/".len()..];
1548 assert_eq!(suffix.len(), 16, "{wire_stream}");
1549 assert!(
1550 suffix.bytes().all(|b| b.is_ascii_hexdigit()),
1551 "the discriminator is sixteen hex characters: {wire_stream}"
1552 );
1553
1554 // The resolved name is threaded back, byte-identical to the wire's — this is the
1555 // only copy of the discriminator, so the caller reads it here or never.
1556 assert_eq!(image.log_stream.as_deref(), Some(wire_stream));
1557 assert_eq!(
1558 image.log_group.as_deref(),
1559 Some("/aws/lambda-microvms/conformance-builds")
1560 );
1561 assert_eq!(
1562 image.build_log_group(),
1563 "/aws/lambda-microvms/conformance-builds",
1564 "a configured group replaces the derived default"
1565 );
1566 }
1567
1568 /// Two creates from the **same** request resolve two different streams — the
1569 /// per-attempt property, which is what keeps successive builds of one image apart.
1570 ///
1571 /// The same claim `recreating_the_same_image_name_emits_two_distinct_client_tokens`
1572 /// makes for the token, on the surface that reuses its nonce.
1573 #[tokio::test]
1574 async fn two_creates_from_one_request_resolve_two_different_streams() {
1575 let (plane, fake, _) = planted();
1576 fake.answer(
1577 "CreateMicrovmImage",
1578 Answer::created(fake::create_image_response("img")),
1579 );
1580 let mut request = a_request();
1581 request.log_group = Some("/aws/lambda-microvms/builds".to_string());
1582 request.log_stream = Some("ci".to_string());
1583
1584 let first = plane
1585 .create_image(request.clone())
1586 .await
1587 .expect("first create");
1588 let second = plane.create_image(request).await.expect("second create");
1589
1590 assert_ne!(
1591 first.log_stream, second.log_stream,
1592 "a repeated stream name collapses two builds' logs into one"
1593 );
1594
1595 let streams: Vec<String> = fake
1596 .bodies_as_text()
1597 .iter()
1598 .filter_map(|body| {
1599 serde_json::from_str::<serde_json::Value>(body)
1600 .ok()
1601 .map(|v| {
1602 v["logging"]["cloudWatch"]["logStream"]
1603 .as_str()
1604 .unwrap_or_default()
1605 .to_string()
1606 })
1607 })
1608 .filter(|stream| !stream.is_empty())
1609 .collect();
1610 assert_eq!(streams.len(), 2, "both creates carried a stream");
1611 assert_ne!(streams[0], streams[1], "distinct on the wire too");
1612 }
1613
1614 /// A create with no logging config serialises **no** `logging` member at all —
1615 /// absent, not null — so an unconfigured build emits byte-for-byte the request this
1616 /// client always sent.
1617 #[tokio::test]
1618 async fn an_unconfigured_build_serialises_no_logging_member() {
1619 let (plane, fake, _) = planted();
1620 fake.answer(
1621 "CreateMicrovmImage",
1622 Answer::created(fake::create_image_response("img")),
1623 );
1624 let image = plane.create_image(a_request()).await.expect("creates");
1625
1626 let body = fake.first_body("CreateMicrovmImage");
1627 assert!(
1628 body.get("logging").is_none(),
1629 "absent, not null: an absent member takes the service default: {body}"
1630 );
1631 assert_eq!(image.log_group, None);
1632 assert_eq!(image.log_stream, None);
1633 assert_eq!(
1634 image.build_log_group(),
1635 "/aws/lambda-microvms/img",
1636 "no configured group means the derived default"
1637 );
1638 }
1639
1640 /// A group with no stream sends the group alone, and the service names the streams:
1641 /// the `logStream` member is omitted rather than sent empty or invented.
1642 #[tokio::test]
1643 async fn a_group_without_a_stream_sends_the_group_alone() {
1644 let (plane, fake, _) = planted();
1645 fake.answer(
1646 "CreateMicrovmImage",
1647 Answer::created(fake::create_image_response("img")),
1648 );
1649 let mut request = a_request();
1650 request.log_group = Some("/aws/lambda-microvms/builds".to_string());
1651
1652 let image = plane.create_image(request).await.expect("creates");
1653 let body = fake.first_body("CreateMicrovmImage");
1654 assert_eq!(
1655 body["logging"]["cloudWatch"]["logGroup"],
1656 "/aws/lambda-microvms/builds"
1657 );
1658 assert!(
1659 body["logging"]["cloudWatch"].get("logStream").is_none(),
1660 "no configured stream, no invented one: {body}"
1661 );
1662 assert_eq!(image.log_stream, None);
1663 }
1664
1665 /// The log-stream pattern's two forbidden characters are refused locally, with zero
1666 /// calls, naming the platform pattern — and the length checks bracket the caller's
1667 /// 495 ceiling.
1668 ///
1669 /// 495 rather than the shape's 512, because the discriminator needs its 17 characters:
1670 /// the boundary cases assert that 495 passes and 496 is refused with the arithmetic in
1671 /// the message.
1672 #[tokio::test]
1673 async fn an_illegal_log_stream_is_refused_before_any_call() {
1674 for (label, stream, named) in [
1675 ("a colon", "ci:image".to_string(), "[^:*]*"),
1676 ("a star", "ci-*".to_string(), "[^:*]*"),
1677 ("over the caller ceiling", "s".repeat(496), "495"),
1678 ] {
1679 let (plane, fake, _) = planted();
1680 let mut request = a_request();
1681 request.log_group = Some("/aws/lambda-microvms/builds".to_string());
1682 request.log_stream = Some(stream);
1683
1684 let error = plane.create_image(request).await.expect_err(label);
1685 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{label}");
1686 assert_eq!(error.code(), "ERR_INVALID_ARG", "{label}");
1687 assert!(
1688 error.to_string().contains(named),
1689 "{label}: the refusal must name the constraint: {error}"
1690 );
1691 assert_eq!(fake.calls().len(), 0, "{label}: nothing reached the wire");
1692 }
1693
1694 // The boundary passes: 495 characters resolve to exactly the shape's 512.
1695 let (plane, fake, _) = planted();
1696 fake.answer(
1697 "CreateMicrovmImage",
1698 Answer::created(fake::create_image_response("img")),
1699 );
1700 let mut request = a_request();
1701 request.log_group = Some("g".to_string());
1702 request.log_stream = Some("s".repeat(495));
1703 let image = plane.create_image(request).await.expect("495 is legal");
1704 assert_eq!(
1705 image.log_stream.expect("resolved").len(),
1706 512,
1707 "the longest legal prefix resolves to exactly the shape's ceiling"
1708 );
1709 }
1710
1711 /// An illegal log group is refused locally too, with the pattern named — the colon
1712 /// case is a pasted ARN, which is the mistake the message calls out.
1713 #[tokio::test]
1714 async fn an_illegal_log_group_is_refused_before_any_call() {
1715 for (label, group) in [
1716 (
1717 "a pasted ARN",
1718 "arn:aws:logs:us-east-1:1:log-group:g".to_string(),
1719 ),
1720 ("a space", "my builds".to_string()),
1721 ("over the ceiling", "g".repeat(513)),
1722 ("empty", String::new()),
1723 ] {
1724 let (plane, fake, _) = planted();
1725 let mut request = a_request();
1726 request.log_group = Some(group);
1727
1728 let error = plane.create_image(request).await.expect_err(label);
1729 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{label}");
1730 assert_eq!(fake.calls().len(), 0, "{label}: nothing reached the wire");
1731 }
1732 }
1733
1734 /// A stream with no group is refused: the stream lives inside the group, and with no
1735 /// group configured the service creates one with random stream names, so the
1736 /// configured stream would name a location that does not exist.
1737 #[tokio::test]
1738 async fn a_stream_without_a_group_is_refused_before_any_call() {
1739 let (plane, fake, _) = planted();
1740 let mut request = a_request();
1741 request.log_stream = Some("ci".to_string());
1742
1743 let error = plane.create_image(request).await.expect_err("refused");
1744 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1745 assert!(error.to_string().contains("logGroup"), "{error}");
1746 assert_eq!(fake.calls().len(), 0);
1747 }
1748
1749 /// A name the service would reject never reaches the wire, so the caller does not pay
1750 /// for the artifact upload first.
1751 #[tokio::test]
1752 async fn an_invalid_image_name_is_refused_before_any_call() {
1753 let (plane, fake, _) = planted();
1754 let mut request = a_request();
1755 request.name = "my.image".to_string();
1756
1757 let error = plane
1758 .create_image(request)
1759 .await
1760 .expect_err("dots are refused");
1761 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1762 assert_eq!(fake.calls().len(), 0, "nothing reached the control plane");
1763 }
1764
1765 /// **BIND-20 at the build (#257).** `preflight` refuses a request whose daemon is an x86_64 ELF or
1766 /// no ELF at all, as a precondition naming what the bytes are, and `create_image` refuses
1767 /// it before any call. A request with no bytes passes: its `codeArtifact.uri` already
1768 /// holds the daemon (`--artifact-uri`, #249), and nothing of it enters an artifact.
1769 ///
1770 /// **Falsification**: drop the `require_aarch64` call from `preflight` and both requests
1771 /// pass it, and the create reaches the fake.
1772 #[tokio::test]
1773 async fn preflight_refuses_a_daemon_that_is_not_an_aarch64_elf() {
1774 for (binary, why) in [
1775 (
1776 crate::testing::elf_daemon(0x3E, b"x86"),
1777 "ELF machine 0x3e, not aarch64",
1778 ),
1779 (b"#!/bin/sh\n".to_vec(), "not an ELF binary at all"),
1780 ] {
1781 let (plane, fake, _) = planted();
1782 fake.answer(
1783 "CreateMicrovmImage",
1784 Answer::created(fake::create_image_response("agentd-conformance")),
1785 );
1786 let mut request = a_request();
1787 request.binary = binary;
1788 let error = plane.preflight(&request).expect_err(why);
1789 assert_eq!(error.kind(), ErrorKind::Precondition, "{error}");
1790 assert!(error.to_string().contains(why), "{error}");
1791 let error = plane.create_image(request).await.expect_err(why);
1792 assert_eq!(error.kind(), ErrorKind::Precondition, "{error}");
1793 assert!(fake.calls().is_empty(), "{why}: nothing reached the plane");
1794 }
1795 let (plane, _, _) = planted();
1796 let mut request = a_request();
1797 request.binary = Vec::new();
1798 plane
1799 .preflight(&request)
1800 .expect("no bytes: the caller's artifact carries the daemon");
1801 }
1802
1803 /// A Dockerfile disagreeing with the base image is refused locally too — same reason,
1804 /// and the check is only run when a Dockerfile was supplied.
1805 #[tokio::test]
1806 async fn a_mismatched_dockerfile_is_refused_before_any_call() {
1807 let (plane, fake, _) = planted();
1808 let mut request = a_request();
1809 request.dockerfile = Some("FROM ubuntu:24.04\n".to_string());
1810
1811 let error = plane.create_image(request).await.expect_err("refused");
1812 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1813 assert!(error.to_string().contains("ubuntu:24.04"), "{error}");
1814 assert_eq!(fake.calls().len(), 0);
1815 }
1816
1817 /// **Issue #46 at the create boundary.** A Dockerfile that never runs the daemon — no
1818 /// `CMD`, or an `ENTRYPOINT` that swallows it — is refused before any call, like every
1819 /// other agreement guard.
1820 ///
1821 /// **Falsification** — run 2026-08-17. Delete the `require_daemon_cmd` call from
1822 /// `preflight` and both halves go red with the create having reached the fake.
1823 #[tokio::test]
1824 async fn a_dockerfile_that_never_runs_the_daemon_is_refused_before_any_call() {
1825 for dockerfile in [
1826 // No CMD: the base's default process runs instead of the daemon.
1827 "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\nCOPY agentd /agentd\n",
1828 // A non-empty ENTRYPOINT: the CMD becomes its arguments.
1829 "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n\
1830 ENTRYPOINT [\"/bin/sh\", \"-c\"]\nCMD [\"/agentd\"]\n",
1831 ] {
1832 let (plane, fake, _) = planted();
1833 let mut request = a_request();
1834 request.dockerfile = Some(dockerfile.to_string());
1835
1836 let error = plane.create_image(request).await.expect_err("refused");
1837 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{dockerfile}");
1838 assert!(
1839 error.to_string().contains("run-hook timeout"),
1840 "the symptom the reader would otherwise chase has to be named: {error}"
1841 );
1842 assert_eq!(fake.calls().len(), 0, "nothing reached the control plane");
1843 }
1844 }
1845
1846 /// **Issue #47's contract, stated at the library boundary.** `preflight` and
1847 /// `create_image` refuse the same request for the same reason, with zero calls — which
1848 /// is what lets an uploading caller run the list before paying for the upload.
1849 ///
1850 /// Asserted over every guard family `preflight` carries, not just the Dockerfile ones,
1851 /// because the extraction's risk is a guard left behind in `create_image` where the
1852 /// pre-upload caller never sees it.
1853 #[tokio::test]
1854 async fn preflight_and_create_image_refuse_identically_with_zero_calls() {
1855 type Breakage = Box<dyn Fn(&mut CreateImageRequest)>;
1856 let broken: [(&str, Breakage); 7] = [
1857 ("an invalid name", Box::new(|r| r.name = "my.image".into())),
1858 (
1859 "a log group with a colon",
1860 Box::new(|r| r.log_group = Some("arn:aws:logs:g".into())),
1861 ),
1862 (
1863 "a log stream with no group",
1864 Box::new(|r| r.log_stream = Some("ci".into())),
1865 ),
1866 (
1867 "a mismatched FROM",
1868 Box::new(|r| r.dockerfile = Some("FROM ubuntu:24.04\nCMD [\"/agentd\"]\n".into())),
1869 ),
1870 (
1871 "a Dockerfile with no CMD",
1872 Box::new(|r| {
1873 r.dockerfile =
1874 Some("FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\n".into());
1875 }),
1876 ),
1877 (
1878 "a blank base version",
1879 Box::new(|r| r.base_image_version = Some(" ".into())),
1880 ),
1881 (
1882 "a blank build role",
1883 Box::new(|r| r.build_role_arn = String::new()),
1884 ),
1885 ];
1886
1887 for (label, break_it) in broken {
1888 let (plane, fake, _) = planted();
1889 let mut request = a_request();
1890 break_it(&mut request);
1891
1892 let from_preflight = plane.preflight(&request).expect_err(label).to_string();
1893 let from_create = plane
1894 .create_image(request)
1895 .await
1896 .expect_err(label)
1897 .to_string();
1898 assert_eq!(
1899 from_preflight, from_create,
1900 "{label}: one list of guards, not two that can drift"
1901 );
1902 assert_eq!(fake.calls().len(), 0, "{label}: zero calls either way");
1903 }
1904
1905 // And the request every other test builds passes preflight, so the guard list is
1906 // refusing the breakage rather than the baseline.
1907 let (plane, _, _) = planted();
1908 plane.preflight(&a_request()).expect("the baseline passes");
1909 }
1910
1911 /// The hook timeouts reach the wire in their own families, so a build-sized value
1912 /// cannot land in a run-family field.
1913 #[tokio::test]
1914 async fn the_two_hook_families_reach_their_own_wire_members() {
1915 let (plane, fake, _) = planted();
1916 fake.answer(
1917 "CreateMicrovmImage",
1918 Answer::created(fake::create_image_response("img")),
1919 );
1920 let mut request = a_request();
1921 request.run_hook_timeout = RunHookTimeout::try_new(60).expect("the run ceiling");
1922 request.build_hook_timeout = BuildHookTimeout::try_new(3600).expect("the build ceiling");
1923 plane.create_image(request).await.expect("creates");
1924
1925 let body = fake.first_body("CreateMicrovmImage");
1926 assert_eq!(body["hooks"]["microvmHooks"]["runTimeoutInSeconds"], 60);
1927 assert_eq!(
1928 body["hooks"]["microvmImageHooks"]["readyTimeoutInSeconds"],
1929 3600
1930 );
1931 }
1932
1933 /// The wait returns as soon as the image is usable, and accepts every ready spelling —
1934 /// including the two tolerated ones, since a hard check on `CREATED` alone is how a
1935 /// working build looks like a stalled one.
1936 #[tokio::test]
1937 async fn the_wait_returns_on_every_ready_spelling() {
1938 for state in ["CREATED", "UPDATED", "ACTIVE", "AVAILABLE"] {
1939 let (plane, fake, _) = planted();
1940 fake.answer(
1941 "GetMicrovmImage",
1942 Answer::ok(fake::get_image_response("img", state)),
1943 );
1944 let image = plane
1945 .wait_for_image("arn:image", SizeClass::DEFAULT, WaitOpts::default())
1946 .await
1947 .unwrap_or_else(|error| panic!("{state} is usable: {error}"));
1948 assert_eq!(image.state, state);
1949 assert_eq!(fake.call_count("GetMicrovmImage"), 1, "no extra polls");
1950 }
1951 }
1952
1953 /// It polls through `CREATING` and returns when the state changes, without the stall
1954 /// probe firing — the grace period has not elapsed.
1955 #[tokio::test]
1956 async fn the_wait_polls_through_creating_without_probing_inside_the_grace() {
1957 let (plane, fake, _) = planted();
1958 fake.answer(
1959 "GetMicrovmImage",
1960 Answer::ok(fake::get_image_response("img", "CREATING")),
1961 )
1962 .answer(
1963 "GetMicrovmImage",
1964 Answer::ok(fake::get_image_response("img", "CREATED")),
1965 );
1966
1967 let image = plane
1968 .wait_for_image("arn:image", SizeClass::DEFAULT, WaitOpts::default())
1969 .await
1970 .expect("becomes usable");
1971 assert_eq!(image.state, "CREATED");
1972 assert_eq!(fake.call_count("GetMicrovmImage"), 2);
1973 assert_eq!(
1974 fake.call_count("ListMicrovmImageBuilds"),
1975 0,
1976 "one poll interval is well inside the four-minute grace"
1977 );
1978 }
1979
1980 /// **TRAP-2.** Past the grace, in `CREATING`, with every build `PENDING`: the wait is
1981 /// rejected naming the client-token replay signature.
1982 ///
1983 /// The response bodies are literal model-spelled JSON from the fake — `buildState`, not
1984 /// `state` — which is what makes this guard falsifiable at all.
1985 ///
1986 /// **Falsification** — three of them, and all three were run: (a) delete the
1987 /// `probe_stalled_build` call from the wait and this test times out instead, (b) read
1988 /// `state` instead of `buildState` and the deserializer refuses the fake's body, (c)
1989 /// drop the `all PENDING` condition and the polls-through-CREATING test above goes red.
1990 #[tokio::test]
1991 async fn a_build_stuck_creating_with_all_builds_pending_names_the_replay_signature() {
1992 let (plane, fake, _) = planted();
1993 fake.answer(
1994 "GetMicrovmImage",
1995 Answer::ok(fake::get_image_response("img", "CREATING")),
1996 )
1997 .answer(
1998 "ListMicrovmImageVersions",
1999 Answer::ok(fake::list_versions_response("1")),
2000 )
2001 .answer(
2002 "ListMicrovmImageBuilds",
2003 Answer::ok(fake::list_builds_response("PENDING")),
2004 );
2005
2006 let error = plane
2007 .wait_for_image(
2008 "arn:image",
2009 SizeClass::DEFAULT,
2010 WaitOpts {
2011 stall_grace: Duration::from_secs(240),
2012 poll_interval: Duration::from_secs(120),
2013 timeout: Duration::from_secs(2700),
2014 },
2015 )
2016 .await
2017 .expect_err("a wedged image must not be waited out");
2018
2019 assert_eq!(error.kind(), ErrorKind::BuildWedged);
2020 assert_eq!(error.code(), "ERR_BUILD_WEDGED");
2021 let message = error.to_string();
2022 assert!(
2023 message.contains("clientToken replay signature"),
2024 "the message must name the signature: {message}"
2025 );
2026 assert!(message.contains("PENDING"), "{message}");
2027 assert!(
2028 message.contains("permanent idempotency key"),
2029 "the cause has to be nameable: {message}"
2030 );
2031 assert!(
2032 message.contains("Waiting will not help"),
2033 "the remedy is not patience: {message}"
2034 );
2035 assert!(message.contains("docs/PLATFORM.md"), "{message}");
2036 }
2037
2038 /// A build that is genuinely in progress past the grace is **not** accused. `IN_PROGRESS`
2039 /// means the service scheduled it, which is exactly what the replay case never does.
2040 ///
2041 /// Three `CREATING` answers rather than two, because the probe only runs on a poll that
2042 /// *sees* `CREATING` after the grace has elapsed: with two answers the second poll
2043 /// already returns `CREATED` and the probe never fires, so the test would assert nothing
2044 /// about the probe's verdict. The `ListMicrovmImageBuilds` count at the bottom is what
2045 /// keeps that honest.
2046 #[tokio::test]
2047 async fn a_slow_but_scheduled_build_is_not_accused_of_being_wedged() {
2048 let (plane, fake, _) = planted();
2049 fake.answer(
2050 "GetMicrovmImage",
2051 Answer::ok(fake::get_image_response("img", "CREATING")),
2052 )
2053 .answer(
2054 "GetMicrovmImage",
2055 Answer::ok(fake::get_image_response("img", "CREATING")),
2056 )
2057 .answer(
2058 "GetMicrovmImage",
2059 Answer::ok(fake::get_image_response("img", "CREATED")),
2060 )
2061 .answer(
2062 "ListMicrovmImageVersions",
2063 Answer::ok(fake::list_versions_response("1")),
2064 )
2065 .answer(
2066 "ListMicrovmImageBuilds",
2067 Answer::ok(fake::list_builds_response("IN_PROGRESS")),
2068 );
2069
2070 let image = plane
2071 .wait_for_image(
2072 "arn:image",
2073 SizeClass::DEFAULT,
2074 WaitOpts {
2075 stall_grace: Duration::from_secs(240),
2076 poll_interval: Duration::from_secs(300),
2077 timeout: Duration::from_secs(2700),
2078 },
2079 )
2080 .await
2081 .expect("a scheduled build is allowed to be slow");
2082 assert_eq!(image.state, "CREATED");
2083 assert_eq!(
2084 fake.call_count("ListMicrovmImageBuilds"),
2085 1,
2086 "the probe runs once and does not re-arm"
2087 );
2088 }
2089
2090 /// **Issue #23.** One scheduled build on page **two** of the build listing is enough to
2091 /// clear a healthy image, so a truncated page cannot produce a false wedge verdict.
2092 ///
2093 /// `probe_stalled_build` asserts **all** builds are PENDING. Over one page that
2094 /// quantifier is a claim about a subset presented as a claim about the set: fifty pending
2095 /// builds on page one plus one `IN_PROGRESS` build on page two is a healthy image that
2096 /// the old code would have called wedged, and `ERR_BUILD_WEDGED` is an exit code a caller
2097 /// is told to trust.
2098 ///
2099 /// **Falsification** — run 2026-08-15. Stop the loop after the first page in
2100 /// `builds_of_version` and this fails with `ErrorKind::BuildWedged`, which is exactly the
2101 /// false verdict issue #23 describes. Restored.
2102 #[tokio::test]
2103 async fn a_scheduled_build_on_page_two_prevents_a_false_wedge_verdict() {
2104 let (plane, fake, _) = planted();
2105 fake.answer(
2106 "GetMicrovmImage",
2107 Answer::ok(fake::get_image_response("img", "CREATING")),
2108 )
2109 .answer(
2110 "GetMicrovmImage",
2111 Answer::ok(fake::get_image_response("img", "CREATING")),
2112 )
2113 .answer(
2114 "GetMicrovmImage",
2115 Answer::ok(fake::get_image_response("img", "CREATED")),
2116 )
2117 .answer(
2118 "ListMicrovmImageVersions",
2119 Answer::ok(fake::list_versions_response("1")),
2120 )
2121 // Page one is entirely PENDING, which is the wedge signature over a partial list.
2122 .answer(
2123 "ListMicrovmImageBuilds",
2124 Answer::ok(fake::list_builds_page(
2125 &[("build-1", "PENDING"), ("build-2", "PENDING")],
2126 Some("builds-page-2"),
2127 )),
2128 )
2129 // Page two says the service scheduled something, so nothing is wedged.
2130 .answer(
2131 "ListMicrovmImageBuilds",
2132 Answer::ok(fake::list_builds_page(&[("build-3", "IN_PROGRESS")], None)),
2133 );
2134
2135 let image = plane
2136 .wait_for_image(
2137 "arn:image",
2138 SizeClass::DEFAULT,
2139 WaitOpts {
2140 stall_grace: Duration::from_secs(240),
2141 poll_interval: Duration::from_secs(300),
2142 timeout: Duration::from_secs(2700),
2143 },
2144 )
2145 .await
2146 .expect("a build scheduled on page two is a scheduled build");
2147 assert_eq!(image.state, "CREATED");
2148 assert_eq!(
2149 fake.call_count("ListMicrovmImageBuilds"),
2150 2,
2151 "the probe read both pages before deciding"
2152 );
2153
2154 let listings: Vec<String> = fake
2155 .calls()
2156 .into_iter()
2157 .filter(|call| call.operation == "ListMicrovmImageBuilds")
2158 .map(|call| call.path)
2159 .collect();
2160 assert!(
2161 listings[1].contains("nextToken=builds-page-2"),
2162 "the second request must carry the first page's token: {}",
2163 listings[1]
2164 );
2165 }
2166
2167 /// The other direction: a wedge that is only visible on page two is still caught. All
2168 /// builds PENDING **across every page** is the signature, and the page-two builds are
2169 /// named in the message.
2170 ///
2171 /// Without this, a paginating probe that read every page but formed its verdict from the
2172 /// last one would pass the test above while missing a real wedge.
2173 #[tokio::test]
2174 async fn a_wedge_is_still_named_when_the_builds_span_two_pages() {
2175 let (plane, fake, _) = planted();
2176 fake.answer(
2177 "GetMicrovmImage",
2178 Answer::ok(fake::get_image_response("img", "CREATING")),
2179 )
2180 .answer(
2181 "ListMicrovmImageVersions",
2182 Answer::ok(fake::list_versions_response("1")),
2183 )
2184 .answer(
2185 "ListMicrovmImageBuilds",
2186 Answer::ok(fake::list_builds_page(
2187 &[("build-1", "PENDING")],
2188 Some("builds-page-2"),
2189 )),
2190 )
2191 .answer(
2192 "ListMicrovmImageBuilds",
2193 Answer::ok(fake::list_builds_page(&[("build-2", "PENDING")], None)),
2194 );
2195
2196 let error = plane
2197 .wait_for_image(
2198 "arn:image",
2199 SizeClass::DEFAULT,
2200 WaitOpts {
2201 stall_grace: Duration::from_secs(240),
2202 poll_interval: Duration::from_secs(120),
2203 timeout: Duration::from_secs(2700),
2204 },
2205 )
2206 .await
2207 .expect_err("a wedged image must not be waited out");
2208
2209 assert_eq!(error.kind(), ErrorKind::BuildWedged);
2210 let message = error.to_string();
2211 assert!(
2212 message.contains("all 2 builds"),
2213 "the count must be over every page, not one: {message}"
2214 );
2215 assert!(
2216 message.contains("build-2"),
2217 "the page-two build must be in the verdict: {message}"
2218 );
2219 assert!(message.contains("build-1"), "{message}");
2220 }
2221
2222 /// A build list that cannot be read produces **no** wedge claim. Unknown is not
2223 /// wedged, and a claim made on a throttled call sends the reader after the wrong cause.
2224 #[tokio::test]
2225 async fn an_unreadable_build_list_does_not_produce_a_wedge_claim() {
2226 let (plane, fake, _) = planted();
2227 fake.answer(
2228 "GetMicrovmImage",
2229 Answer::ok(fake::get_image_response("img", "CREATING")),
2230 )
2231 .answer(
2232 "ListMicrovmImageVersions",
2233 Answer::failure(429, "Rate exceeded"),
2234 );
2235
2236 let error = plane
2237 .wait_for_image(
2238 "arn:image",
2239 SizeClass::DEFAULT,
2240 WaitOpts {
2241 stall_grace: Duration::from_secs(240),
2242 poll_interval: Duration::from_secs(300),
2243 timeout: Duration::from_secs(600),
2244 },
2245 )
2246 .await
2247 .expect_err("the wait still ends at its deadline");
2248
2249 assert_eq!(
2250 error.kind(),
2251 ErrorKind::Timeout,
2252 "an honest timeout, not a wedge claim: {error}"
2253 );
2254 assert!(!error.to_string().contains("replay signature"), "{error}");
2255 }
2256
2257 /// A reported build failure with **no** reason anywhere names the required log-group
2258 /// prefix, because a failure that reads as "unknown" is most often the wrong IAM prefix
2259 /// rather than a silent service.
2260 ///
2261 /// The listings answer, and answer with no `stateReason`, which is the case that
2262 /// distinguishes "the service stated no cause" from "we did not look".
2263 #[tokio::test]
2264 async fn a_failed_build_with_no_stated_reason_names_the_required_log_group_prefix() {
2265 let (plane, fake, _) = planted();
2266 fake.answer(
2267 "GetMicrovmImage",
2268 Answer::ok(fake::get_image_response("img", "CREATE_FAILED")),
2269 )
2270 .answer(
2271 "ListMicrovmImageVersions",
2272 Answer::ok(fake::list_versions_response("1")),
2273 )
2274 .answer(
2275 "ListMicrovmImageBuilds",
2276 Answer::ok(fake::list_builds_response("FAILED")),
2277 );
2278
2279 let error = plane
2280 .wait_for_image("arn:image", SizeClass::DEFAULT, WaitOpts::default())
2281 .await
2282 .expect_err("a failed build is a failure");
2283 assert_eq!(error.kind(), ErrorKind::Platform);
2284 let message = error.to_string();
2285 assert!(
2286 message.contains("stated no cause"),
2287 "the absence has to be stated as an absence: {message}"
2288 );
2289 assert!(message.contains("/aws/lambda-microvms/img"), "{message}");
2290 assert!(
2291 message.contains("/aws/lambda/microvms/*"),
2292 "the wrong prefix has to be named as wrong: {message}"
2293 );
2294 assert!(message.contains("the plausible spelling"), "{message}");
2295 }
2296
2297 /// **Issue #25.** A build failure reports the `stateReason` the service already stated,
2298 /// at both levels: the version's and the failed build's.
2299 ///
2300 /// `GetMicrovmImage` structurally cannot carry a reason — the shape has no such member —
2301 /// so before this the message could only name a log group and guess. The version reason
2302 /// is the general one ("one or more builds failed") and the build reason is the specific
2303 /// one, which is why both are surfaced rather than just the nearest.
2304 ///
2305 /// The failed build is on **page two** of the build listing, so this doubles as a
2306 /// pagination guard on the diagnosis path.
2307 ///
2308 /// # And now the build's own `GetMicrovmImageBuild`, for the sizes
2309 ///
2310 /// The listing's reason is not the whole of what the service will say. `GetMicrovmImageBuild`
2311 /// adds `snapshotBuild`, and on a real failure it comes back **partial** — measured
2312 /// 2026-08-16, a `FAILED` build answered `codeInstallSizeInBytes` alone with no memory and
2313 /// no disk snapshot, which is a build that installed the code and then never produced a
2314 /// snapshot. That distinguishes "the ready hook never answered" from "the Dockerfile broke
2315 /// before installing anything", and the listing has no member for it. The generation is in
2316 /// the line for the same reason: one create fans out per Graviton generation and they can
2317 /// disagree.
2318 ///
2319 /// **Falsification** — (a) Drop the `failure_reasons` call from `build_failure` and the
2320 /// message loses both reasons: the first two assertions go red. (b) Stop following
2321 /// `nextToken` in `builds_of_version` (return `Some(builds)` in the `Some(token)` arm) and
2322 /// only the version reason survives: the `no space left` assertion goes red. (c) Drop
2323 /// `state_reason` from `MicrovmImageBuildSummaryWire` and it does not compile. (d) Replace
2324 /// `describe_build_deeply` with `listed.describe()` and the size and generation assertions
2325 /// go red while the reason ones still pass — which is what makes the extra call earn itself.
2326 /// All four run.
2327 #[tokio::test]
2328 async fn a_failed_build_reports_the_reason_the_service_already_stated() {
2329 let (plane, fake, _) = planted();
2330 fake.answer(
2331 "GetMicrovmImage",
2332 Answer::ok(fake::get_image_response_failed("img", "CREATE_FAILED", "2")),
2333 )
2334 // Version "2" is on page two of the version listing, and it is the one
2335 // `latestFailedImageVersion` names — so a resolver reading one page finds the wrong
2336 // version, or none.
2337 .answer(
2338 "ListMicrovmImageVersions",
2339 Answer::ok(fake::list_versions_page(&["1"], Some("versions-page-2"))),
2340 )
2341 .answer(
2342 "ListMicrovmImageVersions",
2343 Answer::ok(fake::list_versions_response_failed(
2344 "2",
2345 "FAILED",
2346 Some("one or more builds failed"),
2347 )),
2348 )
2349 // The build that carries the specific reason is on page two of the build listing.
2350 .answer(
2351 "ListMicrovmImageBuilds",
2352 Answer::ok(fake::list_builds_page_with_reasons(
2353 &[("build-1", "SUCCESSFUL", None)],
2354 Some("builds-page-2"),
2355 )),
2356 )
2357 .answer(
2358 "ListMicrovmImageBuilds",
2359 Answer::ok(fake::list_builds_page_with_reasons(
2360 &[("build-2", "FAILED", Some("no space left on device"))],
2361 None,
2362 )),
2363 )
2364 // The per-build `GetMicrovmImageBuild`, answering the partial `snapshotBuild` a real
2365 // failed build carries: code installed, no snapshot produced.
2366 .answer(
2367 "GetMicrovmImageBuild",
2368 Answer::ok(fake::get_image_build_response(
2369 "build-2",
2370 "FAILED",
2371 "4",
2372 Some("no space left on device"),
2373 Some(r#"{"codeInstallSizeInBytes": 1724940288}"#),
2374 )),
2375 );
2376
2377 let error = plane
2378 .wait_for_image("arn:image", SizeClass::DEFAULT, WaitOpts::default())
2379 .await
2380 .expect_err("a failed build is a failure");
2381 assert_eq!(error.kind(), ErrorKind::Platform);
2382 let message = error.to_string();
2383
2384 assert!(
2385 message.contains("one or more builds failed"),
2386 "the version-level reason must reach the message: {message}"
2387 );
2388 assert!(
2389 message.contains("no space left on device"),
2390 "the build-level reason is the specific one, and it was on page two: {message}"
2391 );
2392 assert!(
2393 message.contains("build-2"),
2394 "the buildId is what GetMicrovmImageBuild takes, so it has to be named: {message}"
2395 );
2396 // The two things only `GetMicrovmImageBuild` can say. The size is the diagnosis a
2397 // listing structurally cannot carry, and the generation is which of the fan-out's
2398 // builds this was.
2399 assert!(
2400 message.contains("code 1724940288 bytes"),
2401 "the snapshot size the listing has no member for must reach the message: {message}"
2402 );
2403 assert!(
2404 message.contains("chipset generation 4"),
2405 "one create fans out per generation, so the failing one has to be named: {message}"
2406 );
2407 assert!(
2408 !message.contains("memory"),
2409 "a size the service did not report must not be invented: {message}"
2410 );
2411 assert_eq!(
2412 fake.call_count("GetMicrovmImageBuild"),
2413 1,
2414 "one call per failed build carrying a reason, not per listed build"
2415 );
2416 assert!(
2417 message.contains("The service stated the cause"),
2418 "{message}"
2419 );
2420 assert!(
2421 !message.contains("stated no cause"),
2422 "a message with reasons must not also claim there were none: {message}"
2423 );
2424
2425 assert_eq!(
2426 fake.call_count("ListMicrovmImageVersions"),
2427 2,
2428 "both version pages were read to find the version the service named"
2429 );
2430 assert_eq!(
2431 fake.call_count("ListMicrovmImageBuilds"),
2432 2,
2433 "both build pages were read"
2434 );
2435 }
2436
2437 /// A build failure whose listings cannot be read at all still reports the failure, and
2438 /// still names the log group. A diagnosis lookup must never turn a real build failure
2439 /// into a listing error.
2440 #[tokio::test]
2441 async fn an_unreadable_listing_still_reports_the_build_failure() {
2442 let (plane, fake, _) = planted();
2443 fake.answer(
2444 "GetMicrovmImage",
2445 Answer::ok(fake::get_image_response("img", "CREATE_FAILED")),
2446 )
2447 .answer(
2448 "ListMicrovmImageVersions",
2449 Answer::failure(429, "Rate exceeded"),
2450 );
2451
2452 let error = plane
2453 .wait_for_image("arn:image", SizeClass::DEFAULT, WaitOpts::default())
2454 .await
2455 .expect_err("the build still failed");
2456 assert_eq!(
2457 error.kind(),
2458 ErrorKind::Platform,
2459 "a build failure, not a throttle: {error}"
2460 );
2461 assert!(error.to_string().contains("CREATE_FAILED"), "{error}");
2462 assert!(
2463 error.to_string().contains("/aws/lambda-microvms/img"),
2464 "{error}"
2465 );
2466 }
2467
2468 /// Every model failure spelling is recognised, so a build that failed is never polled
2469 /// to the deadline.
2470 #[test]
2471 fn every_model_failure_state_is_recognised_as_a_failure() {
2472 for state in ["CREATE_FAILED", "UPDATE_FAILED", "DELETE_FAILED"] {
2473 assert!(Image::is_failed(state), "{state}");
2474 assert!(!Image::is_ready(state), "{state}");
2475 }
2476 for state in ["CREATING", "UPDATING", "DELETING", "DELETED"] {
2477 assert!(!Image::is_failed(state), "{state}");
2478 assert!(!Image::is_ready(state), "{state}");
2479 }
2480 }
2481
2482 /// The wait ends at its deadline with a `Timeout` naming the last state seen — which is
2483 /// the difference between "we gave up" and "we gave up while it was still CREATING".
2484 #[tokio::test]
2485 async fn the_wait_ends_at_its_deadline_naming_the_last_state() {
2486 let (plane, fake, _) = planted();
2487 fake.answer(
2488 "GetMicrovmImage",
2489 Answer::ok(fake::get_image_response("img", "CREATING")),
2490 );
2491
2492 let error = plane
2493 .wait_for_image(
2494 "arn:image",
2495 SizeClass::DEFAULT,
2496 WaitOpts {
2497 timeout: Duration::from_secs(60),
2498 poll_interval: Duration::from_secs(30),
2499 stall_grace: Duration::MAX,
2500 },
2501 )
2502 .await
2503 .expect_err("the deadline elapses");
2504 assert_eq!(error.kind(), ErrorKind::Timeout);
2505 let message = error.to_string();
2506 assert!(message.contains("CREATING"), "{message}");
2507 assert!(message.contains("nothing was cancelled"), "{message}");
2508 }
2509
2510 /// The log group is the measured prefix, not the plausible one.
2511 #[test]
2512 fn the_build_log_group_uses_the_measured_prefix() {
2513 let image = Image {
2514 identifier: "arn:image".to_string(),
2515 name: "agentd-conformance".to_string(),
2516 version: "1".to_string(),
2517 state: "CREATED".to_string(),
2518 size: SizeClass::DEFAULT,
2519 log_group: None,
2520 log_stream: None,
2521 };
2522 assert_eq!(
2523 image.build_log_group(),
2524 "/aws/lambda-microvms/agentd-conformance"
2525 );
2526 assert!(
2527 !image.build_log_group().starts_with("/aws/lambda/microvms"),
2528 "the wrong prefix produces builds with no logs at all"
2529 );
2530 }
2531
2532 /// Deletion drops every version but the first, then the image. The first is kept
2533 /// because the last remaining version cannot be deleted alone.
2534 #[tokio::test]
2535 async fn deletion_keeps_the_first_version_and_deletes_the_image() {
2536 let (plane, fake, _) = planted();
2537 fake.answer(
2538 "ListMicrovmImageVersions",
2539 Answer::ok(fake::list_versions_response("1")),
2540 )
2541 .answer(
2542 "DeleteMicrovmImage",
2543 Answer::ok(fake::delete_image_response()),
2544 );
2545
2546 assert!(
2547 plane
2548 .delete_image("arn:image", 20, Duration::from_secs(15))
2549 .await
2550 );
2551 assert_eq!(
2552 fake.call_count("DeleteMicrovmImageVersion"),
2553 0,
2554 "one version means nothing to delete separately"
2555 );
2556 assert_eq!(fake.call_count("DeleteMicrovmImage"), 1);
2557 }
2558
2559 /// **Issue #23, the worst of the three.** Deletion follows `nextToken` and drops the
2560 /// versions on page **two**, so an image with more versions than one page can hold is
2561 /// still deletable.
2562 ///
2563 /// Reading one page and then deleting the image is not a partial cleanup, it is a
2564 /// permanent one: page-two versions still exist, the final `DeleteMicrovmImage` conflicts,
2565 /// the retry loop re-reads the same first page every attempt, and `delete_image` returns
2566 /// `false` forever — a billing image nothing can delete through this client.
2567 ///
2568 /// The assertion is the **delete count**, not the call count: five versions across two
2569 /// pages means four `DeleteMicrovmImageVersion` calls, and the two on page two are named
2570 /// individually so a loop that read the second page but deleted from the first would
2571 /// still fail.
2572 ///
2573 /// **Falsification** — run 2026-08-15. Replace the `Some(token) => next_token = ...` arm
2574 /// with `Some(_) => break` and this fails with 1 deletion instead of 4, and the
2575 /// `v-4`/`v-5` path assertions go red. Restored.
2576 #[tokio::test]
2577 async fn deletion_follows_next_token_and_drops_the_versions_on_page_two() {
2578 let (plane, fake, _) = planted();
2579 fake.answer(
2580 "ListMicrovmImageVersions",
2581 Answer::ok(fake::list_versions_page(
2582 &["v-1", "v-2", "v-3"],
2583 Some("versions-page-2"),
2584 )),
2585 )
2586 .answer(
2587 "ListMicrovmImageVersions",
2588 Answer::ok(fake::list_versions_page(&["v-4", "v-5"], None)),
2589 )
2590 .answer(
2591 "DeleteMicrovmImageVersion",
2592 Answer::ok(fake::empty_response()),
2593 )
2594 .answer(
2595 "DeleteMicrovmImage",
2596 Answer::ok(fake::delete_image_response()),
2597 );
2598
2599 assert!(
2600 plane
2601 .delete_image("arn:image", 20, Duration::from_secs(15))
2602 .await,
2603 "an image whose versions span two pages must still be deletable"
2604 );
2605
2606 // The delete count first, because it is the outcome the bug produced: reading one
2607 // page deletes one version and leaves two billing. A call count would report the
2608 // same breakage as "one listing" and bury what that cost.
2609 assert_eq!(
2610 fake.call_count("DeleteMicrovmImageVersion"),
2611 4,
2612 "five versions, keeping the first: four deletions, two of them from page two"
2613 );
2614
2615 // Named individually, because a loop that reads page two and then deletes from page
2616 // one would still make four calls.
2617 let deleted: Vec<String> = fake
2618 .calls()
2619 .into_iter()
2620 .filter(|call| call.operation == "DeleteMicrovmImageVersion")
2621 .map(|call| call.path)
2622 .collect();
2623 for version in ["v-2", "v-3", "v-4", "v-5"] {
2624 assert!(
2625 deleted.iter().any(|path| path.ends_with(version)),
2626 "version {version} was never deleted, so it still bills: {deleted:?}"
2627 );
2628 }
2629 assert!(
2630 !deleted.iter().any(|path| path.ends_with("v-1")),
2631 "the first version goes with the image: {deleted:?}"
2632 );
2633 assert_eq!(fake.call_count("DeleteMicrovmImage"), 1);
2634 assert_eq!(
2635 fake.call_count("ListMicrovmImageVersions"),
2636 2,
2637 "both pages were read"
2638 );
2639
2640 // The second listing request carries the first page's cursor. Without this the loop
2641 // could re-read page one forever and still satisfy a count of two.
2642 let listings: Vec<String> = fake
2643 .calls()
2644 .into_iter()
2645 .filter(|call| call.operation == "ListMicrovmImageVersions")
2646 .map(|call| call.path)
2647 .collect();
2648 assert!(
2649 listings[1].contains("nextToken=versions-page-2"),
2650 "the second request must carry the first page's token: {}",
2651 listings[1]
2652 );
2653 assert!(
2654 !listings[0].contains("nextToken"),
2655 "the first request carries no cursor: {}",
2656 listings[0]
2657 );
2658 }
2659
2660 /// **Issue #25.** A `DeleteMicrovmImage` that answers 2xx while reporting a `*_FAILED`
2661 /// state is a failure, not a success.
2662 ///
2663 /// That readback is why `DeleteImageResponseWire` is kept rather than deleted as dead:
2664 /// without it the service can accept the delete request, refuse the work, and have
2665 /// `delete_image` answer `true` — teardown reports clean and the image keeps billing.
2666 ///
2667 /// **Falsification** — run 2026-08-15. Drop the `Image::is_failed` check from
2668 /// `try_delete_image` and this reports `true` after one attempt: both assertions go red.
2669 /// Restored.
2670 #[tokio::test]
2671 async fn a_delete_that_reads_back_failed_is_not_reported_as_deleted() {
2672 let (plane, fake, _) = planted();
2673 fake.answer(
2674 "ListMicrovmImageVersions",
2675 Answer::ok(fake::list_versions_response("1")),
2676 )
2677 .answer(
2678 "DeleteMicrovmImage",
2679 Answer::ok(fake::delete_image_response_in("DELETE_FAILED")),
2680 );
2681
2682 assert!(
2683 !plane
2684 .delete_image("arn:image", 2, Duration::from_secs(15))
2685 .await,
2686 "a DELETE_FAILED readback means the image still exists and still bills"
2687 );
2688 assert_eq!(
2689 fake.call_count("DeleteMicrovmImage"),
2690 2,
2691 "every attempt ran rather than the first being taken as success"
2692 );
2693 }
2694
2695 /// `DELETING` and `DELETED` are **both** success. The deletion is asynchronous, so
2696 /// `DELETING` is the ordinary answer, and treating it as incomplete would re-issue a
2697 /// delete already in progress and then report failure on the conflict that comes back.
2698 #[tokio::test]
2699 async fn both_deleting_and_deleted_read_back_as_success() {
2700 for state in ["DELETING", "DELETED"] {
2701 let (plane, fake, _) = planted();
2702 fake.answer(
2703 "ListMicrovmImageVersions",
2704 Answer::ok(fake::list_versions_response("1")),
2705 )
2706 .answer(
2707 "DeleteMicrovmImage",
2708 Answer::ok(fake::delete_image_response_in(state)),
2709 );
2710
2711 assert!(
2712 plane
2713 .delete_image("arn:image", 20, Duration::from_secs(15))
2714 .await,
2715 "{state} is the delete having worked"
2716 );
2717 assert_eq!(
2718 fake.call_count("DeleteMicrovmImage"),
2719 1,
2720 "{state} must not be retried"
2721 );
2722 }
2723 }
2724
2725 /// Deletion retries a conflict — an image in `CREATING` refuses deletion, and a VM
2726 /// still terminating holds a reference — and gives up without raising, because the
2727 /// caller is a teardown path.
2728 #[tokio::test]
2729 async fn deletion_retries_a_conflict_and_gives_up_without_raising() {
2730 let (plane, fake, clock) = planted();
2731 fake.answer(
2732 "ListMicrovmImageVersions",
2733 Answer::ok(fake::list_versions_response("1")),
2734 )
2735 .answer(
2736 "DeleteMicrovmImage",
2737 Answer::failure(409, "image is in CREATING"),
2738 );
2739
2740 let deleted = plane
2741 .delete_image("arn:image", 3, Duration::from_secs(15))
2742 .await;
2743 assert!(!deleted, "it reports failure rather than raising");
2744 assert_eq!(
2745 fake.call_count("DeleteMicrovmImage"),
2746 3,
2747 "every attempt ran"
2748 );
2749 assert_eq!(
2750 clock.now(),
2751 Duration::from_secs(30),
2752 "two backoffs between three attempts"
2753 );
2754 }
2755
2756 /// A deletion that succeeds on the second attempt stops there.
2757 #[tokio::test]
2758 async fn deletion_stops_as_soon_as_it_succeeds() {
2759 let (plane, fake, _) = planted();
2760 fake.answer(
2761 "ListMicrovmImageVersions",
2762 Answer::ok(fake::list_versions_response("1")),
2763 )
2764 .answer("DeleteMicrovmImage", Answer::failure(409, "still CREATING"))
2765 .answer(
2766 "DeleteMicrovmImage",
2767 Answer::ok(fake::delete_image_response()),
2768 );
2769
2770 assert!(
2771 plane
2772 .delete_image("arn:image", 20, Duration::from_secs(15))
2773 .await
2774 );
2775 assert_eq!(fake.call_count("DeleteMicrovmImage"), 2);
2776 }
2777
2778 /// **The one Dockerfile fallback (#258).** A request's own Dockerfile, or the default
2779 /// stanza for its base and this plane's port, and the artifact carries exactly that text
2780 /// beside the daemon, so an ensure built from the request and its two-step build agree.
2781 #[test]
2782 fn the_artifact_carries_the_dockerfile_the_request_builds_with() {
2783 use std::io::Read as _;
2784
2785 let (plane, fake, _) = planted();
2786 let mut request = a_request();
2787 request.dockerfile = None;
2788 let default = plane.dockerfile_for(&request);
2789 assert_eq!(
2790 default,
2791 artifact::default_dockerfile(
2792 crate::control::DEFAULT_AGENT_PORT,
2793 None,
2794 &request.base_image,
2795 None
2796 )
2797 );
2798 let sandbox = crate::sandbox::Sandbox::with_control_plane(planted().0);
2799 assert_eq!(sandbox.dockerfile_for(&request), default);
2800
2801 let own = "FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal\nCMD [\"/agentd\"]\n";
2802 request.dockerfile = Some(own.to_string());
2803 assert_eq!(plane.dockerfile_for(&request), own);
2804
2805 let bytes = plane.build_artifact_for(&request).expect("builds the zip");
2806 let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a zip");
2807 let mut dockerfile = String::new();
2808 archive
2809 .by_name("Dockerfile")
2810 .expect("the Dockerfile entry")
2811 .read_to_string(&mut dockerfile)
2812 .expect("reads");
2813 assert_eq!(dockerfile, own);
2814 let mut daemon = Vec::new();
2815 archive
2816 .by_name("agentd")
2817 .expect("the daemon entry")
2818 .read_to_end(&mut daemon)
2819 .expect("reads");
2820 assert_eq!(daemon, request.binary);
2821 assert_eq!(fake.calls().len(), 0);
2822 }
2823
2824 /// The artifact bytes are available without a control-plane call, which is what lets the
2825 /// byte-scan guard inspect them.
2826 #[test]
2827 fn the_artifact_is_buildable_without_touching_the_control_plane() {
2828 let (plane, fake, _) = planted();
2829 let bytes = plane
2830 .build_artifact_for(&a_request())
2831 .expect("builds the zip");
2832 assert!(!bytes.is_empty());
2833 assert_eq!(fake.calls().len(), 0);
2834 }
2835
2836 // ── name resolution ──────────────────────────────────────────────────────
2837
2838 /// A bare name resolves to its image's ARN through the listing, and the request
2839 /// carries the model's `nameFilter` query member.
2840 ///
2841 /// The listing here answers with a *substring* superset — `agentd-conformance-old`
2842 /// beside the exact name — because that is what `nameFilter` really returns, and the
2843 /// exact-match rule is what this test is for: `contains` and `is` are different
2844 /// questions, and only `is` is safe to launch from.
2845 ///
2846 /// **Falsification** — return the first item regardless of name match (replace the
2847 /// `item.name == name` comparison with `true`) and this resolves to `...-old`'s ARN:
2848 /// the equality below goes red. Run 2026-08-14; it failed exactly there and was
2849 /// restored.
2850 #[tokio::test]
2851 async fn a_bare_name_resolves_to_the_exactly_matching_images_arn() {
2852 let (plane, fake, _) = planted();
2853 fake.answer(
2854 "ListMicrovmImages",
2855 Answer::ok(fake::list_images_response(
2856 &["agentd-conformance-old", "agentd-conformance"],
2857 None,
2858 )),
2859 );
2860
2861 let arn = plane
2862 .resolve_image_arn("agentd-conformance")
2863 .await
2864 .expect("resolves");
2865 assert_eq!(
2866 arn, "arn:aws:lambda:us-east-1:123456789012:microvm-image:agentd-conformance",
2867 "the exact match wins, not the first substring hit"
2868 );
2869
2870 let calls = fake.calls();
2871 assert_eq!(calls.len(), 1);
2872 assert_eq!(calls[0].method, super::super::transport::Method::Get);
2873 assert_eq!(
2874 calls[0].path,
2875 "/2025-09-09/microvm-images?nameFilter=agentd-conformance"
2876 );
2877 }
2878
2879 /// An identifier already shaped like an ARN passes through untouched, with **zero**
2880 /// listing calls — the caller who holds the ARN pays nothing.
2881 #[tokio::test]
2882 async fn an_arn_identifier_passes_through_with_no_listing_call() {
2883 let (plane, fake, _) = planted();
2884 let arn = "arn:aws:lambda:us-east-1:123456789012:microvm-image:img";
2885 let resolved = plane.resolve_image_arn(arn).await.expect("passes through");
2886 assert_eq!(resolved, arn);
2887 assert_eq!(
2888 fake.call_count("ListMicrovmImages"),
2889 0,
2890 "an ARN must cost zero extra calls"
2891 );
2892 assert_eq!(fake.calls().len(), 0);
2893 }
2894
2895 /// Zero matches is a local `Precondition` error naming the name and the remedy —
2896 /// not the service's "Malformed ARN", which says nothing about names.
2897 #[tokio::test]
2898 async fn an_unknown_name_is_a_precondition_error_naming_the_name_and_the_remedy() {
2899 let (plane, fake, _) = planted();
2900 fake.answer(
2901 "ListMicrovmImages",
2902 Answer::ok(fake::list_images_response(&[], None)),
2903 );
2904
2905 let error = plane
2906 .resolve_image_arn("no-such-image")
2907 .await
2908 .expect_err("nothing to resolve");
2909 assert_eq!(error.kind(), ErrorKind::Precondition);
2910 assert_eq!(error.code(), "ERR_PRECONDITION");
2911 let message = error.to_string();
2912 assert!(message.contains("no-such-image"), "{message}");
2913 assert!(message.contains("microvm build"), "{message}");
2914 assert!(
2915 message.contains("last page"),
2916 "the message must say the whole listing was read: {message}"
2917 );
2918 }
2919
2920 /// Resolution follows `nextToken` across pages: an image on page two is found, and
2921 /// the second request carries the first page's token.
2922 ///
2923 /// **Falsification** — stop the loop after the first page (replace the
2924 /// `Some(token)` arm with `return Ok(None)`) and this reports the name missing.
2925 /// Run 2026-08-14; it failed exactly there and was restored.
2926 #[tokio::test]
2927 async fn resolution_follows_next_token_to_an_image_on_the_second_page() {
2928 let (plane, fake, _) = planted();
2929 fake.answer(
2930 "ListMicrovmImages",
2931 Answer::ok(fake::list_images_response(
2932 &["some-other-image"],
2933 Some("page-2-token"),
2934 )),
2935 )
2936 .answer(
2937 "ListMicrovmImages",
2938 Answer::ok(fake::list_images_response(&["wanted-image"], None)),
2939 );
2940
2941 let arn = plane
2942 .resolve_image_arn("wanted-image")
2943 .await
2944 .expect("found on page two");
2945 assert_eq!(
2946 arn,
2947 "arn:aws:lambda:us-east-1:123456789012:microvm-image:wanted-image"
2948 );
2949 assert_eq!(fake.call_count("ListMicrovmImages"), 2, "both pages read");
2950
2951 let paths = fake.paths();
2952 assert!(
2953 paths[1].contains("nextToken=page-2-token"),
2954 "the second request must carry the first page's token: {}",
2955 paths[1]
2956 );
2957 assert!(
2958 paths[0].contains("nameFilter=wanted-image") && !paths[0].contains("nextToken"),
2959 "the first request has the filter and no token: {}",
2960 paths[0]
2961 );
2962 }
2963
2964 // ── the four new operations ──────────────────────────────────────────────
2965
2966 /// **A real build failure carries no version-level reason, and the build's line is the
2967 /// whole diagnosis.**
2968 ///
2969 /// Measured 2026-08-16 against a deliberately failing build (`RUN … && exit 42`, image
2970 /// `microvm-cli-cpc-fail`): `GetMicrovmImageVersion` answered `state: FAILED, status:
2971 /// INACTIVE` with **no `stateReason` member at all**, while both of the version's builds
2972 /// carried `The container image build failed.` That confirms the entry in
2973 /// docs/PLATFORM.md rather than merely restating it, and it is the case that decides how
2974 /// the diagnosis has to be assembled: a message built only from the version's reason would
2975 /// say nothing on a real failure.
2976 ///
2977 /// The fake's version here therefore carries **no** reason, unlike the sibling test above
2978 /// — so the message must still name the cause, and it can only get it from the builds.
2979 ///
2980 /// **Falsification** — run 2026-08-16. Drop the build-level extension from
2981 /// `failure_reasons` (keep only the version's reason) and the `stated no cause` assertion
2982 /// goes red, because with no version reason there is nothing left.
2983 #[tokio::test]
2984 async fn a_failure_with_no_version_reason_still_names_the_cause_from_the_builds() {
2985 let (plane, fake, _) = planted();
2986 fake.answer(
2987 "GetMicrovmImage",
2988 Answer::ok(fake::get_image_response_failed(
2989 "img",
2990 "CREATE_FAILED",
2991 "1.0",
2992 )),
2993 )
2994 // `FAILED` / `INACTIVE` with no `stateReason` — the shape a real failure has.
2995 .answer(
2996 "ListMicrovmImageVersions",
2997 Answer::ok(format!(
2998 r#"{{"items": [{}]}}"#,
2999 fake::get_image_version_response("1.0", "FAILED", "INACTIVE")
3000 )),
3001 )
3002 // Both builds of the fan-out failed with the same reason, which is what a real one does.
3003 .answer(
3004 "ListMicrovmImageBuilds",
3005 Answer::ok(fake::list_builds_page_with_reasons(
3006 &[
3007 (
3008 "ad8dc894-df5e-499c-800c-89711db15f21",
3009 "FAILED",
3010 Some("The container image build failed."),
3011 ),
3012 (
3013 "fbf3cc24-baf7-4498-8f05-13de7c34f2a4",
3014 "FAILED",
3015 Some("The container image build failed."),
3016 ),
3017 ],
3018 None,
3019 )),
3020 )
3021 // And `GetMicrovmImageBuild` on a real *container-build* failure carries **no**
3022 // `snapshotBuild` at all — measured 2026-08-16. So the line has the reason and the
3023 // generation and no sizes, which the renderer must handle without a dangling clause.
3024 .answer(
3025 "GetMicrovmImageBuild",
3026 Answer::ok(fake::get_image_build_response(
3027 "ad8dc894-df5e-499c-800c-89711db15f21",
3028 "FAILED",
3029 "4",
3030 Some("The container image build failed."),
3031 None,
3032 )),
3033 )
3034 .answer(
3035 "GetMicrovmImageBuild",
3036 Answer::ok(fake::get_image_build_response(
3037 "fbf3cc24-baf7-4498-8f05-13de7c34f2a4",
3038 "FAILED",
3039 "3",
3040 Some("The container image build failed."),
3041 None,
3042 )),
3043 );
3044
3045 let error = plane
3046 .wait_for_image("arn:image", SizeClass::DEFAULT, WaitOpts::default())
3047 .await
3048 .expect_err("a failed build is a failure");
3049 let message = error.to_string();
3050 assert!(
3051 message.contains("The service stated the cause"),
3052 "the version carried no reason, so the builds have to supply it: {message}"
3053 );
3054 assert!(
3055 !message.contains("stated no cause"),
3056 "a message with build reasons must not claim there were none: {message}"
3057 );
3058 assert!(
3059 message.contains("The container image build failed."),
3060 "{message}"
3061 );
3062 // Both generations named, because one create fans out into one build per generation
3063 // and a report naming only one hides a partial failure.
3064 assert!(message.contains("chipset generation 4"), "{message}");
3065 assert!(message.contains("chipset generation 3"), "{message}");
3066 assert!(
3067 !message.contains("bytes"),
3068 "a container-build failure reports no snapshotBuild, so no size may be invented: \
3069 {message}"
3070 );
3071 assert_eq!(
3072 fake.call_count("GetMicrovmImageBuild"),
3073 2,
3074 "one per failed build, which is the fan-out's width"
3075 );
3076 }
3077
3078 /// A version-level reason, when the service does give one, still reaches the message —
3079 /// and the version's `status` is read alongside its `state`.
3080 ///
3081 /// The pair with the test above: this is the case docs/PLATFORM.md records as *not* what a
3082 /// real failure looks like, kept because a diagnosis that only worked when the version was
3083 /// silent would break the moment AWS started populating the member.
3084 #[tokio::test]
3085 async fn a_version_level_reason_is_used_when_the_service_does_give_one() {
3086 let (plane, fake, _) = planted();
3087 fake.answer(
3088 "GetMicrovmImage",
3089 Answer::ok(fake::get_image_response_failed(
3090 "img",
3091 "CREATE_FAILED",
3092 "2.0",
3093 )),
3094 )
3095 .answer(
3096 "ListMicrovmImageVersions",
3097 Answer::ok(format!(
3098 r#"{{"items": [{}]}}"#,
3099 fake::get_image_version_response_with_reason(
3100 "2.0",
3101 "FAILED",
3102 "INACTIVE",
3103 "one or more builds failed",
3104 )
3105 )),
3106 )
3107 .answer(
3108 "ListMicrovmImageBuilds",
3109 Answer::ok(fake::list_builds_page_with_reasons(
3110 &[("build-1", "FAILED", Some("no space left on device"))],
3111 None,
3112 )),
3113 )
3114 .answer(
3115 "GetMicrovmImageBuild",
3116 Answer::ok(fake::get_image_build_response(
3117 "build-1",
3118 "FAILED",
3119 "4",
3120 Some("no space left on device"),
3121 Some(r#"{"codeInstallSizeInBytes": 1724940288}"#),
3122 )),
3123 );
3124
3125 let error = plane
3126 .wait_for_image("arn:image", SizeClass::DEFAULT, WaitOpts::default())
3127 .await
3128 .expect_err("a failed build is a failure");
3129 let message = error.to_string();
3130 assert!(
3131 message.contains("version 2.0 is FAILED because one or more builds failed"),
3132 "the version's own reason has to survive: {message}"
3133 );
3134 assert!(
3135 message.contains("no space left on device"),
3136 "the build's reason is the specific one: {message}"
3137 );
3138 assert!(
3139 message.contains("code 1724940288 bytes"),
3140 "and the size only GetMicrovmImageBuild has: {message}"
3141 );
3142 }
3143
3144 /// `GetMicrovmImageBuild` lands on the model's path and method, and answers with the
3145 /// snapshot sizes.
3146 ///
3147 /// The path is asserted as a literal rather than built from the helper, because the whole
3148 /// content of the change is one extra segment and a helper shared with the code under test
3149 /// would agree with a wrong helper.
3150 ///
3151 /// **Falsification** — run 2026-08-16. Change `paths::image_build` to append `/build/`
3152 /// instead of `/builds/` and the path assertion goes red; the request would otherwise
3153 /// succeed against a fake that keys on the operation name.
3154 #[tokio::test]
3155 async fn getting_one_build_emits_the_models_path_and_reads_the_snapshot_sizes() {
3156 let (plane, fake, _) = planted();
3157 fake.answer(
3158 "GetMicrovmImageBuild",
3159 Answer::ok(fake::get_image_build_response(
3160 "build-abc",
3161 "SUCCESSFUL",
3162 "4",
3163 None,
3164 Some(
3165 r#"{"memorySnapshotSizeInBytes": 582238208,
3166 "codeInstallSizeInBytes": 2355486720,
3167 "diskSnapshotSizeInBytes": 23760896}"#,
3168 ),
3169 )),
3170 );
3171
3172 let build = plane
3173 .get_image_build("arn:image", "1.0", "build-abc")
3174 .await
3175 .expect("reads");
3176 assert_eq!(build.build_state, "SUCCESSFUL");
3177 assert_eq!(build.chipset_generation, "4");
3178 let sizes = build.snapshot_build.expect("the sizes are why we called");
3179 assert_eq!(sizes.memory_snapshot_size_in_bytes, Some(582_238_208));
3180
3181 let calls = fake.calls();
3182 assert_eq!(calls.len(), 1);
3183 assert_eq!(calls[0].method, super::super::transport::Method::Get);
3184 assert_eq!(
3185 calls[0].path,
3186 "/2025-09-09/microvm-images/arn%3Aimage/versions/1.0/builds/build-abc"
3187 );
3188 assert_eq!(calls[0].body, None, "a GET carries no body");
3189 }
3190
3191 /// `GetMicrovmImageVersion` lands on the version path with a `GET`, and reads the
3192 /// availability status.
3193 ///
3194 /// The same path a `DELETE` of the version uses, which is the model's own arrangement —
3195 /// so the assertion that matters is the **method**: a `DELETE` here would destroy the
3196 /// version this call exists to inspect.
3197 ///
3198 /// **Falsification** — run 2026-08-16. Build the call with `Call::delete` and the method
3199 /// assertion goes red while the path assertion still passes, which is the whole reason both
3200 /// are here.
3201 #[tokio::test]
3202 async fn getting_one_version_reads_it_with_a_get_on_the_delete_path() {
3203 let (plane, fake, _) = planted();
3204 fake.answer(
3205 "GetMicrovmImageVersion",
3206 Answer::ok(fake::get_image_version_response(
3207 "2.0",
3208 "SUCCESSFUL",
3209 "INACTIVE",
3210 )),
3211 );
3212
3213 let version = plane
3214 .get_image_version("arn:image", "2.0")
3215 .await
3216 .expect("reads");
3217 assert_eq!(version.image_version, "2.0");
3218 assert_eq!(version.status, "INACTIVE");
3219 assert!(!version.is_active(), "INACTIVE will not launch");
3220
3221 let calls = fake.calls();
3222 assert_eq!(
3223 calls[0].method,
3224 super::super::transport::Method::Get,
3225 "a DELETE on this path destroys the version this call inspects"
3226 );
3227 assert_eq!(
3228 calls[0].path,
3229 "/2025-09-09/microvm-images/arn%3Aimage/versions/2.0"
3230 );
3231 }
3232
3233 /// **`UpdateMicrovmImageVersion` is a `PATCH` whose body is one member.**
3234 ///
3235 /// The method, the path, and the body's exact key set, because each is a separate way to
3236 /// get the model's only non-destructive retire wrong: a `POST` reaches a route the service
3237 /// does not declare, a path built from the listing carries a cursor, and a body echoing the
3238 /// URI parameters sends members the shape does not have.
3239 ///
3240 /// **Falsification** — run 2026-08-16, three ways. (a) `Call::post_json` instead of
3241 /// `patch_json`: the method assertion goes red. (b) Add `imageVersion` to
3242 /// `UpdateImageVersionWire`: the exact-key-set assertion goes red. (c) Send
3243 /// `VersionStatus::Active` while asking for `Inactive`: the body assertion goes red *and*
3244 /// the readback check in `set_image_version_status` raises, which is the next test.
3245 #[tokio::test]
3246 async fn retiring_a_version_patches_one_member_onto_the_version_path() {
3247 let (plane, fake, _) = planted();
3248 fake.answer(
3249 "UpdateMicrovmImageVersion",
3250 Answer::ok(fake::get_image_version_response(
3251 "2.0",
3252 "SUCCESSFUL",
3253 "INACTIVE",
3254 )),
3255 );
3256
3257 let updated = plane
3258 .set_image_version_status("arn:image", "2.0", ops::VersionStatus::Inactive)
3259 .await
3260 .expect("the retire is accepted");
3261 assert_eq!(updated.status, "INACTIVE");
3262 assert!(!updated.is_active());
3263 assert_eq!(
3264 updated.state, "SUCCESSFUL",
3265 "a retire does not change the build state: the version still built fine, it is \
3266 just no longer launchable"
3267 );
3268
3269 let calls = fake.calls();
3270 assert_eq!(calls[0].method, super::super::transport::Method::Patch);
3271 assert_eq!(
3272 calls[0].path,
3273 "/2025-09-09/microvm-images/arn%3Aimage/versions/2.0"
3274 );
3275 assert!(
3276 !calls[0].path.contains('?'),
3277 "the version path must carry no query member: {}",
3278 calls[0].path
3279 );
3280
3281 let body = fake.first_body("UpdateMicrovmImageVersion");
3282 assert_eq!(body["status"], "INACTIVE");
3283 assert_eq!(
3284 body.as_object()
3285 .expect("an object")
3286 .keys()
3287 .collect::<Vec<_>>(),
3288 vec!["status"],
3289 "imageIdentifier and imageVersion are uri-located: {body}"
3290 );
3291 }
3292
3293 /// **A 2xx whose readback disagrees with the request is a failure.**
3294 ///
3295 /// The same argument `ops::DeleteImageResponseWire` makes: a request the service accepts
3296 /// and does not apply is indistinguishable from one it applied, and here the consequence is
3297 /// a version the caller believes is retired while `RunMicrovm` still launches it. The
3298 /// readback is the only thing that can tell the two apart.
3299 ///
3300 /// **Falsification** — run 2026-08-16. Drop the `updated.status != status.as_str()` check
3301 /// from `set_image_version_status` and this reports `Ok` with an `ACTIVE` version, which is
3302 /// exactly the silent failure it exists to prevent.
3303 #[tokio::test]
3304 async fn a_retire_that_reads_back_active_is_reported_as_a_failure() {
3305 let (plane, fake, _) = planted();
3306 fake.answer(
3307 "UpdateMicrovmImageVersion",
3308 // A 200 whose body still says ACTIVE.
3309 Answer::ok(fake::get_image_version_response(
3310 "2.0",
3311 "SUCCESSFUL",
3312 "ACTIVE",
3313 )),
3314 );
3315
3316 let error = plane
3317 .set_image_version_status("arn:image", "2.0", ops::VersionStatus::Inactive)
3318 .await
3319 .expect_err("a version that is still ACTIVE is one RunMicrovm will still launch");
3320 assert_eq!(error.kind(), ErrorKind::Platform);
3321 let message = error.to_string();
3322 assert!(message.contains("read back status ACTIVE"), "{message}");
3323 assert!(message.contains("INACTIVE"), "{message}");
3324 assert!(
3325 message.contains("RunMicrovm will still launch"),
3326 "the consequence has to be nameable: {message}"
3327 );
3328 assert_eq!(fake.call_count("UpdateMicrovmImageVersion"), 1);
3329 }
3330
3331 /// A blank or whitespace-bearing version is refused **before** the call, on both the
3332 /// retire path and the launch path.
3333 ///
3334 /// The `Version` shape is `min 1, max 2048, pattern [^\s]+`, and issue #24 lists
3335 /// `NonBlankString` as the model's most-reused unguarded shape. The refusal is local
3336 /// because a retire is what someone does while rolling back, and a `ValidationException`
3337 /// about the request rather than about the version is the least useful failure available at
3338 /// that moment.
3339 ///
3340 /// **Falsification** — run 2026-08-16. Delete the `require_valid_version` call from
3341 /// `set_image_version_status` and the zero-call assertion goes red: the fake records a
3342 /// `PATCH` to `/versions/` with an empty segment, which addresses nothing.
3343 #[tokio::test]
3344 async fn a_blank_or_whitespace_version_reaches_no_control_plane_call() {
3345 for bad in ["", " ", "2.0\n", "a b", "\t2.0"] {
3346 let (plane, fake, _) = planted();
3347 let error = plane
3348 .set_image_version_status("arn:image", bad, ops::VersionStatus::Inactive)
3349 .await
3350 .expect_err(&format!("{bad:?} is not a legal Version"));
3351 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{bad:?}: {error}");
3352 assert_eq!(
3353 fake.calls().len(),
3354 0,
3355 "{bad:?} must reach no control-plane call at all"
3356 );
3357 }
3358 }
3359
3360 /// The version guard's three cases each get their own message, and none reaches the wire.
3361 #[tokio::test]
3362 async fn each_invalid_version_is_refused_locally_with_its_own_message() {
3363 let (plane, fake, _) = planted();
3364
3365 let empty = plane
3366 .set_image_version_status("arn:image", "", ops::VersionStatus::Inactive)
3367 .await
3368 .expect_err("min is 1");
3369 assert_eq!(empty.kind(), ErrorKind::InvalidArg);
3370 assert!(
3371 empty.to_string().contains("Omit the member entirely"),
3372 "an absent version and a blank one are different requests: {empty}"
3373 );
3374
3375 let newline = plane
3376 .set_image_version_status("arn:image", "2.0\n", ops::VersionStatus::Inactive)
3377 .await
3378 .expect_err("the pattern forbids whitespace anywhere");
3379 let message = newline.to_string();
3380 assert!(message.contains("whitespace"), "{message}");
3381 assert!(
3382 message.contains("trailing newline"),
3383 "the plausible cause has to be named: {message}"
3384 );
3385
3386 let long = plane
3387 .set_image_version_status("arn:image", &"9".repeat(2049), ops::VersionStatus::Inactive)
3388 .await
3389 .expect_err("max is 2048");
3390 assert!(long.to_string().contains("2049 characters"), "{long}");
3391
3392 assert_eq!(
3393 fake.calls().len(),
3394 0,
3395 "no invalid version reaches the control plane"
3396 );
3397
3398 // And a legal one does reach it, so the guard is a comparison rather than a blanket
3399 // refusal.
3400 fake.answer(
3401 "UpdateMicrovmImageVersion",
3402 Answer::ok(fake::get_image_version_response(
3403 "2.0",
3404 "SUCCESSFUL",
3405 "INACTIVE",
3406 )),
3407 );
3408 plane
3409 .set_image_version_status("arn:image", "2.0", ops::VersionStatus::Inactive)
3410 .await
3411 .expect("2.0 is a legal Version");
3412 assert_eq!(fake.call_count("UpdateMicrovmImageVersion"), 1);
3413 }
3414
3415 /// **`ListManagedMicrovmImageVersions` reads every page**, and the second request carries
3416 /// the first page's cursor.
3417 ///
3418 /// Every page for the reason the other listings give: a caller pinning "the newest" from a
3419 /// truncated page pins the wrong one, and a base version is what a build's reproducibility
3420 /// rests on.
3421 ///
3422 /// **Falsification** — run 2026-08-16. Replace the `Some(token)` arm with
3423 /// `None => return Ok(items)` semantics (stop after page one) and this fails with 2 versions
3424 /// instead of 3, and the page-two assertion goes red.
3425 #[tokio::test]
3426 async fn the_managed_version_listing_follows_next_token_to_the_last_page() {
3427 let (plane, fake, _) = planted();
3428 fake.answer(
3429 "ListManagedMicrovmImageVersions",
3430 Answer::ok(fake::list_managed_versions_page(
3431 &["2", "1"],
3432 Some("managed-page-2"),
3433 )),
3434 )
3435 .answer(
3436 "ListManagedMicrovmImageVersions",
3437 Answer::ok(fake::list_managed_versions_page(&["0"], None)),
3438 );
3439
3440 let versions = plane
3441 .managed_base_versions("arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1")
3442 .await
3443 .expect("lists");
3444 assert_eq!(versions.len(), 3, "three versions across two pages");
3445 let ids: Vec<&str> = versions
3446 .iter()
3447 .map(|version| version.image_version.as_str())
3448 .collect();
3449 assert_eq!(ids, ["2", "1", "0"]);
3450 assert!(
3451 ids.contains(&"0"),
3452 "the page-two version is the oldest and would be the one a truncated read missed"
3453 );
3454
3455 let paths: Vec<String> = fake
3456 .calls()
3457 .into_iter()
3458 .filter(|call| call.operation == "ListManagedMicrovmImageVersions")
3459 .map(|call| call.path)
3460 .collect();
3461 assert_eq!(paths.len(), 2);
3462 assert!(
3463 paths[0].starts_with("/2025-09-09/managed-microvm-images/"),
3464 "the managed collection is its own route, not a filter on microvm-images: {}",
3465 paths[0]
3466 );
3467 assert!(!paths[0].contains('?'), "{}", paths[0]);
3468 assert!(
3469 paths[1].contains("nextToken=managed-page-2"),
3470 "the second request must carry the first page's token: {}",
3471 paths[1]
3472 );
3473 }
3474
3475 /// A bare base-image name is refused **before** the call, naming the ARN the service wants.
3476 ///
3477 /// Measured 2026-08-16: `ListManagedMicrovmImageVersions --image-identifier al2023-1`
3478 /// answers `ValidationException: Invalid ARN format: al2023-1`, which names the value
3479 /// without saying which member wanted an ARN or that `BaseImage::arn` produces one. The
3480 /// local refusal says both.
3481 ///
3482 /// **Falsification** — run 2026-08-16. Delete the `starts_with("arn:")` guard and the
3483 /// zero-call assertion goes red: the request goes out and the service answers the message
3484 /// above.
3485 #[tokio::test]
3486 async fn a_bare_managed_base_name_is_refused_before_the_call_naming_the_arn() {
3487 let (plane, fake, _) = planted();
3488 let error = plane
3489 .managed_base_versions("al2023-1")
3490 .await
3491 .expect_err("the service wants a full ARN");
3492 assert_eq!(error.kind(), ErrorKind::Precondition);
3493 let message = error.to_string();
3494 assert!(message.contains("Invalid ARN format"), "{message}");
3495 assert!(
3496 message.contains("arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"),
3497 "the remedy has to be the ARN itself: {message}"
3498 );
3499 assert!(message.contains("BaseImage::al2023().arn"), "{message}");
3500 assert_eq!(fake.calls().len(), 0, "nothing reached the control plane");
3501
3502 // And the ARN form does reach it.
3503 fake.answer(
3504 "ListManagedMicrovmImageVersions",
3505 Answer::ok(fake::list_managed_versions_page(&["1", "0"], None)),
3506 );
3507 let versions = plane
3508 .managed_base_versions(
3509 &super::super::BaseImage::al2023().arn(&crate::region::Region::UsEast1),
3510 )
3511 .await
3512 .expect("an ARN is accepted");
3513 assert_eq!(versions.len(), 2);
3514 }
3515
3516 /// `ListManagedMicrovmImages` reads every page too, and its items carry no registry
3517 /// reference — which is why they are informational only.
3518 ///
3519 /// The absence is asserted through [`super::super::BaseImage`]: a discovered base has an
3520 /// ARN and nothing that could fill `docker_ref` or `working_dir`, so
3521 /// `require_matching_from` and `require_workdir` would both have to be skipped for one.
3522 /// That is the comment in `ops::ManagedMicrovmImageSummaryWire`, made a test.
3523 #[tokio::test]
3524 async fn the_managed_image_listing_pages_and_its_items_cannot_build_a_base_image() {
3525 let (plane, fake, _) = planted();
3526 fake.answer(
3527 "ListManagedMicrovmImages",
3528 Answer::ok(fake::list_managed_images_page(
3529 &["al2023-1"],
3530 Some("managed-images-page-2"),
3531 )),
3532 )
3533 .answer(
3534 "ListManagedMicrovmImages",
3535 Answer::ok(fake::list_managed_images_page(&["al2024-1"], None)),
3536 );
3537
3538 let images = plane.managed_base_images().await.expect("lists");
3539 assert_eq!(images.len(), 2, "both pages were read");
3540 assert!(
3541 images[1].image_arn.ends_with("al2024-1"),
3542 "the page-two base is the one a caller checking for something new would want: {}",
3543 images[1].image_arn
3544 );
3545
3546 // No registry reference anywhere in what the service sent, so the pairing a
3547 // `BaseImage` needs is not derivable from a discovered base.
3548 let known = super::super::BaseImage::al2023();
3549 for image in &images {
3550 assert!(
3551 !image.image_arn.contains("public.ecr.aws"),
3552 "the ARN carries no registry ref: {}",
3553 image.image_arn
3554 );
3555 }
3556 assert_eq!(
3557 known.docker_ref, "public.ecr.aws/amazonlinux/amazonlinux:2023-minimal",
3558 "the paired ref is a compile-time constant precisely because discovery cannot \
3559 supply it"
3560 );
3561
3562 let paths = fake.paths();
3563 assert_eq!(paths[0], "/2025-09-09/managed-microvm-images");
3564 assert!(
3565 paths[1].contains("nextToken=managed-images-page-2"),
3566 "{}",
3567 paths[1]
3568 );
3569 }
3570
3571 /// **`CreateMicrovmImage.baseImageVersion` reaches the wire when pinned**, and is absent
3572 /// when it is not.
3573 ///
3574 /// Read off the emitted body rather than off the request struct, which is the assertion
3575 /// that matters: a field on `CreateImageRequest` proves nothing about what got sent, and
3576 /// this member had a field-shaped hole in the wire struct until now.
3577 ///
3578 /// **Falsification** — run 2026-08-16. Drop the assignment in `create_image` and the
3579 /// pinned assertion goes red with `baseImageVersion` absent from the body.
3580 #[tokio::test]
3581 async fn a_pinned_base_image_version_reaches_the_create_body() {
3582 let (plane, fake, _) = planted();
3583 fake.answer(
3584 "CreateMicrovmImage",
3585 Answer::created(fake::create_image_response("img")),
3586 );
3587 let mut request = a_request();
3588 request.base_image_version = Some("1".to_string());
3589 plane.create_image(request).await.expect("creates");
3590
3591 let body = fake.first_body("CreateMicrovmImage");
3592 assert_eq!(
3593 body["baseImageVersion"], "1",
3594 "the pinned base version has to reach the wire, or a build still floats: {body}"
3595 );
3596 // The ARN and the version are both sent: pinning does not replace the base.
3597 assert_eq!(
3598 body["baseImageArn"],
3599 "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"
3600 );
3601
3602 // Unpinned emits nothing, so a caller who never touches the field sends what this
3603 // client always sent.
3604 let (plane, fake, _) = planted();
3605 fake.answer(
3606 "CreateMicrovmImage",
3607 Answer::created(fake::create_image_response("img")),
3608 );
3609 plane.create_image(a_request()).await.expect("creates");
3610 assert!(
3611 fake.first_body("CreateMicrovmImage")
3612 .get("baseImageVersion")
3613 .is_none(),
3614 "an absent member takes the service default; a blank one is refused"
3615 );
3616 }
3617
3618 /// An invalid `baseImageVersion` is refused **before** the artifact reaches the wire.
3619 ///
3620 /// The same ordering argument `require_valid_image_name` makes and the reason this guard is
3621 /// local: the create call happens after the caller's artifact upload, so the service's
3622 /// rejection costs them the upload first.
3623 ///
3624 /// **Falsification** — run 2026-08-16. Delete the `require_valid_version` call from
3625 /// `create_image` and the zero-call assertion goes red.
3626 #[tokio::test]
3627 async fn an_invalid_base_image_version_is_refused_before_any_call() {
3628 let (plane, fake, _) = planted();
3629 let mut request = a_request();
3630 request.base_image_version = Some("1 ".to_string());
3631
3632 let error = plane
3633 .create_image(request)
3634 .await
3635 .expect_err("the Version pattern forbids whitespace");
3636 assert_eq!(error.kind(), ErrorKind::InvalidArg);
3637 assert!(error.to_string().contains("baseImageVersion"), "{error}");
3638 assert_eq!(
3639 fake.calls().len(),
3640 0,
3641 "nothing reached the control plane, so the caller did not pay for the upload first"
3642 );
3643 }
3644
3645 /// The reuse hash derives the same Dockerfile a build of the request would, so the
3646 /// two agree — and a request whose Dockerfile differs hashes differently.
3647 #[test]
3648 fn the_reuse_hash_matches_the_build_paths_own_dockerfile_derivation() {
3649 let (plane, fake, _) = planted();
3650 let request = a_request();
3651 let hash = plane.artifact_content_hash_for(&request);
3652 assert_eq!(hash.len(), 64);
3653 assert_eq!(
3654 hash,
3655 plane.artifact_content_hash_for(&request),
3656 "deterministic"
3657 );
3658
3659 let mut custom = a_request();
3660 custom.dockerfile = Some(artifact::default_dockerfile(
3661 9000,
3662 Some("/workspace"),
3663 &custom.base_image,
3664 None,
3665 ));
3666 assert_ne!(
3667 hash,
3668 plane.artifact_content_hash_for(&custom),
3669 "a different Dockerfile is a different image identity"
3670 );
3671 assert_eq!(fake.calls().len(), 0, "hashing is local");
3672 }
3673
3674 // ── issue #24's guards on the create path, proved by the call count ──────
3675
3676 /// **Every constrained member of `CreateMicrovmImage` is refused with zero calls.**
3677 ///
3678 /// One table rather than five tests, because the assertion is identical for each and the
3679 /// thing worth reading is the *list*: these are the members issue #24 named as reachable with
3680 /// no guard, and the create call is the one that happens after the caller's artifact upload.
3681 /// A row here is a member whose rejection no longer costs an upload.
3682 ///
3683 /// The zero-call assertion is the load-bearing one. `expect_err` alone would pass for a
3684 /// request the *service* refused, which is what was happening before; `fake.calls().len() ==
3685 /// 0` is what says the refusal was local.
3686 ///
3687 /// **Guard proof** — run 2026-08-16, one row at a time. Delete
3688 /// `require_valid_role_arn("buildRoleArn", …)` from `create_image` and the buildRoleArn rows
3689 /// go red on the call count (the fake answers `CreateMicrovmImage`, so the launch *succeeds*
3690 /// and the count is 1 rather than 0). Same for `require_non_blank` and the two URI rows,
3691 /// `require_valid_tags` and the four tag rows, and `require_valid_port` and the port row.
3692 #[tokio::test]
3693 async fn every_constrained_create_member_is_refused_with_zero_control_plane_calls() {
3694 /// What to break, and the substring the message must carry.
3695 type Mutate = fn(&mut CreateImageRequest);
3696 let rows: [(&str, Mutate, &str); 12] = [
3697 // `buildRoleArn` — the member issue #24 called out, because its rejection lands
3698 // after the upload.
3699 //
3700 // Two bare-name rows on either side of the 20-character minimum, which is where the
3701 // guard's two messages divide: a short name gets the "you probably meant this ARN"
3702 // one, and a *long* bare name — which the account's real role names are, at 26
3703 // characters — falls through to the pattern message instead. Both are the same
3704 // mistake, so both are covered.
3705 (
3706 "a short build role name",
3707 |request| {
3708 request.build_role_arn = "build-role".to_string();
3709 },
3710 "role *name*",
3711 ),
3712 (
3713 "a long build role name, past the 20-character floor",
3714 |request| {
3715 request.build_role_arn = "bonk-sandbox-microvm-build".to_string();
3716 },
3717 "a role name passed as an ARN",
3718 ),
3719 (
3720 "a build role with eleven account digits",
3721 |request| {
3722 request.build_role_arn = "arn:aws:iam::12345678901:role/build".to_string();
3723 },
3724 "exactly twelve digits",
3725 ),
3726 (
3727 "a build role that is a function ARN",
3728 |request| {
3729 request.build_role_arn =
3730 "arn:aws:lambda:us-east-1:123456789012:function:handler".to_string();
3731 },
3732 "RoleArn pattern",
3733 ),
3734 (
3735 "an empty build role",
3736 |request| {
3737 request.build_role_arn = String::new();
3738 },
3739 "RoleArn minimum",
3740 ),
3741 // `codeArtifact.uri` — `NonBlankString`.
3742 (
3743 "a blank artifact URI",
3744 |request| {
3745 request.code_artifact_uri = String::new();
3746 },
3747 "codeArtifact.uri is empty",
3748 ),
3749 (
3750 "an artifact URI with a trailing newline",
3751 |request| {
3752 request.code_artifact_uri = "s3://bucket/agentd.zip\n".to_string();
3753 },
3754 "contains whitespace",
3755 ),
3756 // `baseImageArn` — derived from `BaseImage` and the region, and `BaseImage`'s fields
3757 // are `pub`. Whitespace rather than an empty name, and the difference is the point:
3758 // an *empty* name still renders `arn:aws:lambda:us-east-1:aws:microvm-image:`, which
3759 // is non-blank, so `require_non_blank`'s min-1 branch is structurally unreachable for
3760 // this member. The whitespace branch is the one that fires, and it fires on the case
3761 // that actually happens — a base image name with a space in it, from a config file or
3762 // a copy-paste.
3763 (
3764 "a base image name with a space in it",
3765 |request| {
3766 request.base_image.name = "al2023 1".to_string();
3767 },
3768 "baseImageArn",
3769 ),
3770 // `tags` — sent since tags existed, checked by nothing.
3771 (
3772 "an empty tag key",
3773 |request| {
3774 request
3775 .tags
3776 .insert(String::new(), "conformance".to_string());
3777 },
3778 "TagKey requires at least 1 character",
3779 ),
3780 (
3781 "a 129-character tag key",
3782 |request| {
3783 request.tags.insert("k".repeat(129), "v".to_string());
3784 },
3785 "over the TagKey ceiling",
3786 ),
3787 (
3788 "a tag key with a comma",
3789 |request| {
3790 request
3791 .tags
3792 .insert("cost,centre".to_string(), "v".to_string());
3793 },
3794 "outside the TagKey pattern",
3795 ),
3796 (
3797 "a 257-character tag value",
3798 |request| {
3799 request.tags.insert("owner".to_string(), "v".repeat(257));
3800 },
3801 "over the TagValue ceiling",
3802 ),
3803 ];
3804
3805 for (label, mutate, expected) in rows {
3806 let (plane, fake, _) = planted();
3807 // Answered on purpose: if the guard were missing, the call would *succeed* and the
3808 // count would be 1. A fake with nothing queued would fail the call for the wrong
3809 // reason and the test would pass while proving nothing.
3810 fake.answer(
3811 "CreateMicrovmImage",
3812 Answer::created(fake::create_image_response("agentd-conformance")),
3813 );
3814
3815 let mut request = a_request();
3816 mutate(&mut request);
3817 let error = plane
3818 .create_image(request)
3819 .await
3820 .expect_err(&format!("{label} must be refused"));
3821 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{label}");
3822 assert!(
3823 error.to_string().contains(expected),
3824 "{label}: the message must contain {expected:?}, got {error}"
3825 );
3826 assert_eq!(
3827 fake.calls().len(),
3828 0,
3829 "{label}: the request was refused locally, so the caller did not pay for the \
3830 artifact upload first — and the fake had an answer queued, so a missing guard \
3831 would show as calls: 1 rather than as a different failure"
3832 );
3833 }
3834
3835 // The control case, and it is not decoration: every row above would also pass if
3836 // `create_image` refused *everything*, and a guard that refuses every request is a
3837 // guard nobody notices is wrong until a build fails.
3838 let (plane, fake, _) = planted();
3839 fake.answer(
3840 "CreateMicrovmImage",
3841 Answer::created(fake::create_image_response("agentd-conformance")),
3842 );
3843 let mut good = a_request();
3844 good.tags
3845 .insert("cost centre".to_string(), "team/agents".to_string());
3846 good.tags.insert("empty".to_string(), String::new());
3847 good.build_role_arn =
3848 "arn:aws:iam::392583147479:role/bonk-sandbox-microvm-build".to_string();
3849 plane
3850 .create_image(good)
3851 .await
3852 .expect("a realistic request with a space in a tag key and an empty tag value");
3853 assert_eq!(fake.call_count("CreateMicrovmImage"), 1);
3854 }
3855
3856 /// The `hooks.port` bound is enforced at [`ControlPlane::with_port`] and **nowhere on the
3857 /// create path**, and that is a deliberate absence rather than a gap.
3858 ///
3859 /// `port` is a private field and `with_port` is its only setter, so a `ControlPlane` whose
3860 /// port is 0 cannot exist: [`ControlPlane::from_ports`] takes the default. A
3861 /// `require_valid_port("hooks.port", self.port)` inside `create_image` would therefore be a
3862 /// branch no input can reach, which is worse than no branch: it reads as a guard, it appears
3863 /// in a coverage report as a guard, and no test can make it fire. The discipline this repo
3864 /// holds is that a guard must be falsifiable, so the check lives at the one place the value
3865 /// can be wrong.
3866 ///
3867 /// What this test asserts is the property that makes the absence safe: the port on the plane
3868 /// is legal by construction, so the `hooks.port` that reaches the wire is too.
3869 ///
3870 /// **Guard proof.** Make `with_port` infallible again — drop the `require_valid_port` call and
3871 /// return `Self` — and the first assertion here goes red, as does
3872 /// `the_port_guard_refuses_zero_and_says_what_zero_means` in `control/mod.rs`.
3873 #[tokio::test]
3874 async fn the_hooks_port_that_reaches_the_wire_is_legal_by_construction() {
3875 let (plane, fake, _) = planted();
3876 assert!(
3877 plane.with_port(0).is_err(),
3878 "with_port is the only setter for the field hooks.port is read from, so refusing 0 \
3879 here is what makes a zero hooks.port unrepresentable"
3880 );
3881
3882 let (plane, fake2, _) = planted();
3883 let _ = fake;
3884 fake2.answer(
3885 "CreateMicrovmImage",
3886 Answer::created(fake::create_image_response("agentd-conformance")),
3887 );
3888 plane
3889 .with_port(9000)
3890 .expect("9000 is legal")
3891 .create_image(a_request())
3892 .await
3893 .expect("a legal port builds");
3894 assert_eq!(
3895 fake2.first_body("CreateMicrovmImage")["hooks"]["port"],
3896 9000,
3897 "and the port that was set is the port on the wire"
3898 );
3899 }
3900
3901 /// **The identifier guard on every image operation, proved by the call count.**
3902 ///
3903 /// Ten of the twelve identifier members are URI parameters, and an empty one does not fail as
3904 /// a blank field — it collapses the path onto the collection. So `GetMicrovmImage` with an
3905 /// empty identifier is a request against the *listing*, and `DeleteMicrovmImage` with one is
3906 /// a delete against it. Those are the requests this proves are never sent.
3907 ///
3908 /// Every operation in one test, because the assertion is the same and the value is the
3909 /// coverage: issue #24 counted six implemented operations per identifier shape, and this is
3910 /// the enumeration.
3911 ///
3912 /// **Guard proof** — run 2026-08-16. Delete `require_valid_identifier` from any one of these
3913 /// and its assertion goes red with `calls: 1` (or, for `wait_for_image`, a poll loop against
3914 /// the listing).
3915 #[tokio::test]
3916 async fn no_image_operation_sends_an_empty_or_over_long_identifier() {
3917 for bad in ["", &"a".repeat(257)] {
3918 let (plane, fake, _) = planted();
3919
3920 plane
3921 .get_image_version(bad, "1.0")
3922 .await
3923 .expect_err("GetMicrovmImageVersion");
3924 plane
3925 .get_image_build(bad, "1.0", "build-1")
3926 .await
3927 .expect_err("GetMicrovmImageBuild");
3928 plane
3929 .set_image_version_status(bad, "1.0", ops::VersionStatus::Inactive)
3930 .await
3931 .expect_err("UpdateMicrovmImageVersion");
3932 plane
3933 .list_image_versions(bad)
3934 .await
3935 .expect_err("ListMicrovmImageVersions");
3936 plane
3937 .list_image_builds(bad, "1.0")
3938 .await
3939 .expect_err("ListMicrovmImageBuilds");
3940 plane
3941 .wait_for_image(bad, SizeClass::DEFAULT, WaitOpts::default())
3942 .await
3943 .expect_err("GetMicrovmImage, in a loop");
3944 plane
3945 .managed_base_versions(bad)
3946 .await
3947 .expect_err("ListManagedMicrovmImageVersions");
3948 assert!(
3949 !plane.delete_image(bad, 20, Duration::from_secs(15)).await,
3950 "delete_image answers false rather than raising, because it is a teardown path"
3951 );
3952
3953 assert_eq!(
3954 fake.calls().len(),
3955 0,
3956 "eight operations refused {bad:?} locally; an empty URI parameter would have \
3957 addressed the collection instead of the resource, and the service can answer \
3958 200 to that"
3959 );
3960 }
3961 }
3962
3963 /// The `NonBlankString` URI and querystring members on the image operations, same proof.
3964 ///
3965 /// `nameFilter` is the one that is not a URI parameter, and it is the one worth having: it
3966 /// goes out as `?nameFilter=` and either 400s or filters differently from what was meant,
3967 /// and `find_image_by_name` is the resolver a launch depends on.
3968 ///
3969 /// **Guard proof.** Delete `require_non_blank("nameFilter", name)` and the `find_image_by_name`
3970 /// row goes red with `calls: 1` — a listing was read with a blank filter.
3971 #[tokio::test]
3972 async fn no_image_operation_sends_a_blank_version_build_id_or_name_filter() {
3973 for bad in ["", " ", "1.0\n", &"9".repeat(2049)] {
3974 let (plane, fake, _) = planted();
3975
3976 plane
3977 .get_image_version("arn:image", bad)
3978 .await
3979 .expect_err("imageVersion");
3980 plane
3981 .get_image_build("arn:image", bad, "build-1")
3982 .await
3983 .expect_err("imageVersion");
3984 plane
3985 .get_image_build("arn:image", "1.0", bad)
3986 .await
3987 .expect_err("buildId");
3988 plane
3989 .list_image_builds("arn:image", bad)
3990 .await
3991 .expect_err("imageVersion");
3992 plane.find_image_by_name(bad).await.expect_err("nameFilter");
3993
3994 assert_eq!(
3995 fake.calls().len(),
3996 0,
3997 "five NonBlankString members refused {bad:?} locally"
3998 );
3999 }
4000 }
4001
4002 /// A lifecycle wait is the caller's deadline at core's poll interval with no stall probe,
4003 /// and the launch wait is one at core's default deadline (#266). Every surface's lifecycle
4004 /// wait is built from `for_lifecycle`, so this is where those three values are held.
4005 ///
4006 /// **Falsification**: `verify/guards/faults/core-defaults.toml` entry
4007 /// `app-lifecycle-wait-stall-probe` gives `for_lifecycle` the image build's stall grace,
4008 /// and this goes red on `stall_grace`.
4009 #[test]
4010 fn a_lifecycle_wait_is_the_callers_deadline_at_cores_poll_with_no_stall_probe() {
4011 let wait = WaitOpts::for_lifecycle(Duration::from_secs(42));
4012 assert_eq!(
4013 (wait.timeout, wait.poll_interval, wait.stall_grace),
4014 (
4015 Duration::from_secs(42),
4016 crate::sandbox::LIFECYCLE_POLL_INTERVAL,
4017 Duration::MAX
4018 ),
4019 "stall_grace, poll_interval or timeout"
4020 );
4021 let launch = WaitOpts::for_launch();
4022 assert_eq!(
4023 (launch.timeout, launch.poll_interval, launch.stall_grace),
4024 (
4025 crate::sandbox::DEFAULT_LIFECYCLE_TIMEOUT,
4026 crate::sandbox::LIFECYCLE_POLL_INTERVAL,
4027 Duration::MAX
4028 )
4029 );
4030 }
4031}