microvms_app/control/ops.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The wire shapes, transcribed member-for-member from the pinned service model.
3//!
4//! # The honest-fake rule
5//!
6//! Every field name here is copied from `service-2.json` for API version
7//! [`crate::constants::MODEL_API_VERSION`], and every deserializer test in this file
8//! parses **literal JSON in the model's spelling** rather than the output of this
9//! module's own serializer. That is not a style preference; it is the fix for a specific
10//! bug that shipped.
11//!
12//! `MicrovmImageBuildSummary` carries a member called `buildState`. It has no member
13//! called `state`. The Python client read `b.get("state")`, which returned `None` from
14//! every real response — so the stall probe that is the only thing separating a wedged
15//! image from a slow build was **dead against live AWS while passing its unit test**,
16//! because the test's fake returned `{"state": "PENDING"}`. The fake shared the client's
17//! own misreading, so the two agreed with each other and with nothing else. Found
18//! 2026-08-07 by diffing against the service model, after a ~15-hour wedge that this
19//! guard existed to catch and did not.
20//!
21//! A round-trip test through this module's `Serialize` would have exactly the same
22//! blind spot. So the tests below hold JSON.
23//!
24//! # What is `Option` and what is not
25//!
26//! The model's `required` list, not a guess about what the service usually sends. A
27//! member the model marks required is a bare field; everything else is `Option`. Two
28//! consequences worth stating:
29//!
30//! * `stateReason` is optional everywhere it appears, which is why TRAP-8's error says
31//! "no stateReason" rather than printing an empty string — the absence is information.
32//! * `RunMicrovmRequest` requires only `imageIdentifier`. `executionRoleArn` is
33//! optional *on the wire* even though every real launch needs one.
34//!
35//! # Unknown members are dropped, deliberately
36//!
37//! No `#[serde(deny_unknown_fields)]` and no catch-all map. A member AWS adds to a
38//! response must not fail a deserialization — that would turn an additive service change
39//! into a broken client — and this crate has no consumer for a field it does not know
40//! about. The drift gate (TRAP-12) is where a new member gets noticed.
41
42use serde::{Deserialize, Serialize};
43
44// ── requests ────────────────────────────────────────────────────────────────
45
46/// `CreateMicrovmImageRequest`.
47///
48/// `clientToken` is `String` rather than `Option<String>` because this client always
49/// sends one and it is always minted here (TRAP-1) — see [`crate::control::token`].
50#[derive(Clone, Debug, Serialize)]
51#[serde(rename_all = "camelCase")]
52pub struct CreateMicrovmImageWire {
53 pub name: String,
54 pub base_image_arn: String,
55 /// `Version`, absent unless the caller pinned one.
56 ///
57 /// Omitted rather than sent empty when nobody pinned, because that is the difference
58 /// between "whatever the service defaults to" and a `ValidationException` on a blank
59 /// `Version` (min 1, pattern `[^\s]+`). The default has already moved once — the managed
60 /// base carries versions `"0"` and `"1"` (docs/PLATFORM.md, 'The managed base image has
61 /// two versions') — so an unpinned build is not reproducible, which is what this member
62 /// exists to fix.
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub base_image_version: Option<String>,
65 pub build_role_arn: String,
66 pub code_artifact: CodeArtifact,
67 pub cpu_configurations: Vec<CpuConfiguration>,
68 pub resources: Vec<Resources>,
69 pub hooks: Hooks,
70 /// `CapabilityList`. Omitted entirely rather than sent empty when identity repair
71 /// was not asked for: the enum's only value is `ALL`, and an empty list is a
72 /// different request from an absent member.
73 #[serde(skip_serializing_if = "Option::is_none")]
74 pub additional_os_capabilities: Option<Vec<String>>,
75 /// `Logging`, absent unless the caller configured build logging.
76 ///
77 /// Omitted rather than sent as `null` or `{}` when nothing was configured: an absent
78 /// member takes the service default (a service-created log group under
79 /// `/aws/lambda-microvms/<image-name>` with random stream names), and the union's own
80 /// documentation says to specify exactly one member — an empty object is a malformed
81 /// union, not a default.
82 ///
83 /// The `logStream` this carries is never a caller's value verbatim; see
84 /// [`CloudWatchLogging::log_stream`] and the discriminator rule in
85 /// [`crate::control::ControlPlane::create_image`].
86 #[serde(skip_serializing_if = "Option::is_none")]
87 pub logging: Option<Logging>,
88 #[serde(skip_serializing_if = "Option::is_none")]
89 pub tags: Option<std::collections::BTreeMap<String, String>>,
90 /// The minted idempotency token.
91 ///
92 /// `pub(crate)` while every sibling field is `pub`, and that asymmetry is TRAP-1's last
93 /// mile. `CreateImageRequest` has no token field, but this type is the wire shape behind
94 /// it — and a `pub` field here would let a caller outside this module build the request
95 /// body directly with a token of their choosing, which is the wedge with one extra step.
96 /// Narrowing the visibility means the only way to populate it is
97 /// [`crate::control::token::create_token`], from inside the crate.
98 pub(crate) client_token: String,
99}
100
101/// `CodeArtifact`, a union whose only member this client uses is `uri`.
102#[derive(Clone, Debug, Deserialize, Serialize)]
103#[serde(rename_all = "camelCase")]
104pub struct CodeArtifact {
105 pub uri: String,
106}
107
108/// `Logging`, the model's tagged union: exactly one of `disabled` or `cloudWatch`.
109///
110/// The same wire shape as [`PortSpecification`] and modelled the same way: a Smithy union
111/// serialises as **one key** — `{"disabled": {}}` or `{"cloudWatch": {...}}` — not a
112/// discriminator field, so `#[serde(untagged)]` plus a `rename` per variant is what keeps
113/// serde's default `{"Disabled": ...}` spelling off the wire.
114///
115/// Both `CreateMicrovmImageRequest` and `RunMicrovmRequest` carry a `logging` member of
116/// this shape in the model, and this client binds both: the image-build side for issue #98
117/// (three build VMs, three streams, the exact-name collision) and the per-VM side for #201.
118#[derive(Clone, Debug, PartialEq, Serialize)]
119#[serde(untagged)]
120pub enum Logging {
121 /// `LoggingDisabled`: no logs at all. An empty struct rather than a unit variant for
122 /// [`AllPorts`]'s reason — the wire form is `{}` and a unit serialises to `null`,
123 /// which the service rejects as a malformed union member.
124 Disabled {
125 #[serde(rename = "disabled")]
126 disabled: LoggingDisabled,
127 },
128 /// `CloudWatchLogging`: a caller-named group and, optionally, stream.
129 CloudWatch {
130 #[serde(rename = "cloudWatch")]
131 cloud_watch: CloudWatchLogging,
132 },
133}
134
135impl Logging {
136 /// Logging off.
137 pub fn disabled() -> Self {
138 Self::Disabled {
139 disabled: LoggingDisabled {},
140 }
141 }
142
143 /// Logs to `log_group`, with the service naming the streams inside it.
144 pub fn cloud_watch(log_group: impl Into<String>, log_stream: Option<String>) -> Self {
145 Self::CloudWatch {
146 cloud_watch: CloudWatchLogging {
147 log_group: Some(log_group.into()),
148 log_stream,
149 },
150 }
151 }
152
153 /// A per-VM configuration from a launch surface's three arguments: a group, an exact
154 /// stream inside it, or `disabled`. `None` when none was given.
155 ///
156 /// One place for the refusal, so the CLI and both bindings word it identically.
157 pub fn from_parts(
158 log_group: Option<String>,
159 log_stream: Option<String>,
160 disabled: bool,
161 ) -> Result<Option<Self>, crate::Error> {
162 match (log_group, log_stream, disabled) {
163 (None, None, false) => Ok(None),
164 (None, None, true) => Ok(Some(Self::disabled())),
165 (Some(group), stream, false) => Ok(Some(Self::cloud_watch(group, stream))),
166 (None, Some(_), false) => Err(crate::Error::invalid_arg(
167 "log_stream names a stream inside log_group; pass log_group too",
168 )),
169 (_, _, true) => Err(crate::Error::invalid_arg(
170 "disabling logging cannot be combined with log_group or log_stream",
171 )),
172 }
173 }
174
175 /// The resolved `logStream` this configuration carries, when it carries one.
176 pub fn log_stream(&self) -> Option<&str> {
177 match self {
178 Logging::Disabled { .. } => None,
179 Logging::CloudWatch { cloud_watch } => cloud_watch.log_stream.as_deref(),
180 }
181 }
182}
183
184/// `LoggingDisabled`, which the model declares with no members. See [`AllPorts`] for why
185/// this is an empty struct rather than a unit one.
186#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
187pub struct LoggingDisabled {}
188
189/// `CloudWatchLogging`: the group and stream names, both optional in the model.
190///
191/// # `logStream` is an EXACT stream name, and the client never sends a caller's verbatim
192///
193/// Measured 2026-08 (docs/PLATFORM.md, 'An image build is three VMs and three log
194/// streams'): the member names one stream exactly — prefixes are unsupported — and one
195/// image build runs three VMs that each want their own stream, so a fixed configured name
196/// collapses all three (and every successive build's three) into one indistinguishable
197/// stream. [`crate::control::ControlPlane::create_image`] therefore appends `/<16 hex>`
198/// of fresh CSPRNG per create attempt before this struct reaches the wire, the same
199/// mechanism as the `clientToken` nonce (TRAP-1).
200#[derive(Clone, Debug, PartialEq, Serialize)]
201#[serde(rename_all = "camelCase")]
202pub struct CloudWatchLogging {
203 /// `CloudWatchLoggingLogGroupString`: 1..=512, pattern `[a-zA-Z0-9_\-/.#]+`.
204 #[serde(skip_serializing_if = "Option::is_none")]
205 pub log_group: Option<String>,
206 /// `CloudWatchLoggingLogStreamString`: 1..=512, pattern `[^:*]*`. Always carries the
207 /// per-build discriminator by the time it serialises — see the type docs.
208 #[serde(skip_serializing_if = "Option::is_none")]
209 pub log_stream: Option<String>,
210}
211
212/// `CpuConfiguration`. One required member, whose enum has one value (`ARM_64`).
213#[derive(Clone, Debug, Deserialize, Serialize)]
214#[serde(rename_all = "camelCase")]
215pub struct CpuConfiguration {
216 pub architecture: String,
217}
218
219/// `Resources` — note the plural. The model's `ResourcesList` member shape is
220/// `Resources`, not `Resource`; there is no shape called `Resource` at all.
221///
222/// `minimumMemoryInMiB` selects a size class, it does not size the VM (TRAP-10, and
223/// `crate::sizing`). The member name's `MiB` capitalisation is the model's.
224#[derive(Clone, Debug, Deserialize, Serialize)]
225pub struct Resources {
226 #[serde(rename = "minimumMemoryInMiB")]
227 pub minimum_memory_in_mib: u32,
228}
229
230/// `Hooks`.
231#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
232#[serde(rename_all = "camelCase")]
233pub struct Hooks {
234 /// `HooksPortInteger`, `min: 1`. Checked by [`crate::control::require_valid_port`] before the
235 /// block is built — a `hooks.port` of 0 is an image with no reachable hook endpoint.
236 pub port: u16,
237 pub microvm_hooks: MicrovmHooks,
238 pub microvm_image_hooks: MicrovmImageHooks,
239}
240
241/// `HookState`, the model's two values.
242///
243/// # A typed enum rather than a validated `String`, and why this one and not the response states
244///
245/// This is the same trade [`VersionStatus`] makes and the reasoning is the same shape. A
246/// response enum must stay a `String` — a third value AWS adds has to parse rather than fail,
247/// which is what [`MicrovmImageBuildSummaryWire::architecture`] documents. `HookState` on the
248/// request side is only ever **serialized**, so narrowing it costs nothing and buys the thing a
249/// two-value enum buys: `"ENABLE"`, `"Enabled"`, and `"ACTIVE"` become compile errors instead of
250/// a `ValidationException`.
251///
252/// It is worth more here than on any other member, because it appears **six times** on one
253/// request. Issue #24 measured what was there before: six `String` fields with `"ENABLED"`
254/// hardcoded as a `const &str` local to `hooks_block`, so no constant named either value and a
255/// typo in one of the six was a rejected `CreateMicrovmImage` — after the artifact upload.
256///
257/// # `Deserialize` too, unlike [`VersionStatus`]
258///
259/// Because a `MicrovmHooks` block is a **request** shape in this module and the tests parse
260/// model-spelled JSON into it (the honest-fake rule). Deriving `Deserialize` on a two-variant
261/// enum means an unknown state fails that parse, which is correct for a shape nothing reads off
262/// a real response — and `MicrovmImageVersionSummaryWire` deliberately does not read a hooks
263/// block at all, for measured reasons that type records.
264#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
265pub enum HookState {
266 /// The platform does not call this hook.
267 #[serde(rename = "DISABLED")]
268 Disabled,
269 /// The platform calls this hook and waits for it. What this client always sends.
270 #[serde(rename = "ENABLED")]
271 Enabled,
272}
273
274impl HookState {
275 /// The wire spelling, which is also what a diagnostic prints.
276 pub fn as_str(self) -> &'static str {
277 match self {
278 HookState::Disabled => "DISABLED",
279 HookState::Enabled => "ENABLED",
280 }
281 }
282}
283
284impl std::fmt::Display for HookState {
285 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286 f.write_str(self.as_str())
287 }
288}
289
290/// `MicrovmHooks` — the family that caps at 60 seconds.
291///
292/// The state members are [`HookState`], so neither value can be misspelled at a call site; the
293/// timeouts are built from [`crate::hooks::RunHookTimeout`] before they get here, which is where
294/// the ceiling is enforced.
295#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
296#[serde(rename_all = "camelCase")]
297pub struct MicrovmHooks {
298 pub run: HookState,
299 pub run_timeout_in_seconds: u32,
300 pub resume: HookState,
301 pub resume_timeout_in_seconds: u32,
302 pub suspend: HookState,
303 pub suspend_timeout_in_seconds: u32,
304 pub terminate: HookState,
305 pub terminate_timeout_in_seconds: u32,
306}
307
308/// `MicrovmImageHooks` — the build family, capping at 3600 seconds.
309#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
310#[serde(rename_all = "camelCase")]
311pub struct MicrovmImageHooks {
312 pub ready: HookState,
313 pub ready_timeout_in_seconds: u32,
314 pub validate: HookState,
315 pub validate_timeout_in_seconds: u32,
316}
317
318/// `RunMicrovmRequest`.
319///
320/// `runHookPayload` is the only per-VM secret channel the platform offers and is checked
321/// against the 4096-byte ceiling before this struct is built (TRAP-5).
322#[derive(Clone, Debug, Serialize)]
323#[serde(rename_all = "camelCase")]
324pub struct RunMicrovmWire {
325 pub image_identifier: String,
326 /// `Version`, absent unless the caller pinned one.
327 ///
328 /// Absent means "whatever the image's `latestActiveImageVersion` is", which is what this
329 /// client always sent. Pinning it is the launch half of the blue/green story: a canary
330 /// launches against exactly the version it means to test, and a rollback re-pins to the
331 /// previous one rather than hoping the image's notion of latest has moved back.
332 ///
333 /// A version set INACTIVE by `UpdateMicrovmImageVersion` refuses to launch when pinned
334 /// here — measured, see [`crate::control::ControlPlane::set_image_version_status`].
335 #[serde(skip_serializing_if = "Option::is_none")]
336 pub image_version: Option<String>,
337 #[serde(skip_serializing_if = "Option::is_none")]
338 pub execution_role_arn: Option<String>,
339 /// Derived ARNs, never caller strings (TRAP-4).
340 pub ingress_network_connectors: Vec<String>,
341 /// Managed internet or customer-managed VPC egress connector ARNs.
342 /// Absent when neither was requested; omission does not block internet access.
343 #[serde(skip_serializing_if = "Option::is_none")]
344 pub egress_network_connectors: Option<Vec<String>>,
345 pub idle_policy: IdlePolicy,
346 pub maximum_duration_in_seconds: u32,
347 pub run_hook_payload: String,
348 /// Per-VM `logging`, absent unless the caller configured it (#201). Absent leaves the
349 /// service's default destination in place.
350 #[serde(skip_serializing_if = "Option::is_none")]
351 pub logging: Option<Logging>,
352 /// The minted idempotency token. `pub(crate)` for the reason
353 /// [`CreateMicrovmImageWire::client_token`] gives.
354 pub(crate) client_token: String,
355}
356
357/// `IdlePolicy`. All three members are required by the model, in **both** directions.
358///
359/// # `suspendedDurationSeconds` comes back, measured
360///
361/// This comment used to say the member "exists only in the request". That was wrong twice
362/// over. The model has one `IdlePolicy` shape, used by `RunMicrovmRequest`,
363/// `RunMicrovmResponse`, and `GetMicrovmResponse` alike, and it marks all three members
364/// required — so the model says the opposite. And the service agrees with the model:
365/// `GetMicrovm` on a RUNNING VM answers
366/// `"idlePolicy": {"maxIdleDurationSeconds": 1800, "suspendedDurationSeconds": 600,
367/// "autoResumeEnabled": false}` (measured 2026-08-15, us-east-1, one read-only
368/// `GetMicrovm`).
369///
370/// The claim mattered because STATE-12 was resting on it: if only the client could name the
371/// suspended window, the client's own record is the only authority on it. The readback
372/// means there is a second one, and [`crate::control::Microvm::idle_policy`] carries it —
373/// so a suspended window that disagrees with what was asked for is now observable rather
374/// than assumed.
375#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
376#[serde(rename_all = "camelCase")]
377pub struct IdlePolicy {
378 /// `min: 60`, checked by [`crate::control::require_idle_duration`] before the launch.
379 ///
380 /// The comment here used to say botocore enforced this one locally, so no guard was needed.
381 /// Botocore does; this client does not use it. See that function for the whole account.
382 pub max_idle_duration_seconds: u32,
383 pub suspended_duration_seconds: u32,
384 pub auto_resume_enabled: bool,
385}
386
387/// `UpdateMicrovmImageVersionRequest`'s **one** body member.
388///
389/// `imageIdentifier` and `imageVersion` are both URI parameters, so the body is a single
390/// key. That is the whole request, and it is the model's only non-destructive retire
391/// primitive: setting a version `INACTIVE` makes `RunMicrovm` refuse to launch it while
392/// existing VMs keep running and the version stays readable through
393/// `GetMicrovmImageVersion`. `DeleteMicrovmImageVersion` is the alternative and it is
394/// irreversible.
395///
396/// `status` is a [`VersionStatus`] rather than a `String`, unlike the `HookState` members
397/// above. The difference is that this enum is the *entire* request: a typo in it is a
398/// `ValidationException` on the only field there is, spent on a call that was going to
399/// change a version's availability. `MicrovmImageVersionStatus` has exactly two values and
400/// naming them in the type means a caller cannot spell either wrong.
401#[derive(Clone, Debug, Serialize)]
402#[serde(rename_all = "camelCase")]
403pub struct UpdateImageVersionWire {
404 pub status: VersionStatus,
405}
406
407/// `MicrovmImageVersionStatus`, the model's two values.
408///
409/// # Why this one is an enum where `HookState` is a bare `String`
410///
411/// A response is not a request (see [`MicrovmImageBuildSummaryWire::architecture`]): a value
412/// AWS adds to a *response* enum must parse rather than fail, which is why the state fields
413/// on every wire struct in this module are `String`. This type is only ever **serialized** —
414/// the readback carries `status` as a `String` for exactly that reason — so narrowing it
415/// costs nothing and buys the one thing a two-value enum can buy: `"INACTIVATE"`,
416/// `"Inactive"`, and `"DISABLED"` are all compile errors rather than a rejected call.
417///
418/// The `Display`/`as_str` spelling is the model's own casing, asserted against a literal in
419/// the tests below rather than derived from the variant name.
420#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
421pub enum VersionStatus {
422 /// `RunMicrovm` may launch this version.
423 #[serde(rename = "ACTIVE")]
424 Active,
425 /// `RunMicrovm` refuses to launch this version. Running VMs are untouched.
426 #[serde(rename = "INACTIVE")]
427 Inactive,
428}
429
430impl VersionStatus {
431 /// The wire spelling, which is also what a diagnostic prints.
432 pub fn as_str(self) -> &'static str {
433 match self {
434 VersionStatus::Active => "ACTIVE",
435 VersionStatus::Inactive => "INACTIVE",
436 }
437 }
438}
439
440impl std::fmt::Display for VersionStatus {
441 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442 f.write_str(self.as_str())
443 }
444}
445
446impl std::str::FromStr for VersionStatus {
447 type Err = crate::Error;
448
449 /// The model's spelling and nothing else, so a binding or a flag that takes the status as
450 /// text refuses `"INACTIVATE"` or `"inactive"` here, with the core's message, before the
451 /// call rather than as a `ValidationException` in the middle of a rollback.
452 fn from_str(text: &str) -> Result<Self, Self::Err> {
453 [VersionStatus::Active, VersionStatus::Inactive]
454 .into_iter()
455 .find(|status| status.as_str() == text)
456 .ok_or_else(|| {
457 crate::Error::invalid_arg(format!(
458 "unknown image version status {text:?}: UpdateMicrovmImageVersion takes {}.",
459 crate::constants::IMAGE_VERSION_STATUSES.join(" or ")
460 ))
461 })
462 }
463}
464
465/// `CreateMicrovmAuthTokenRequest`'s body members. `microvmIdentifier` is a URI
466/// parameter and so is not in the body.
467#[derive(Clone, Debug, Serialize)]
468#[serde(rename_all = "camelCase")]
469pub struct CreateAuthTokenWire {
470 /// Maximum 60 minutes, the service ceiling. TRAP-9 refreshes below it.
471 pub expiration_in_minutes: u32,
472 pub allowed_ports: Vec<PortSpecification>,
473}
474
475/// `CreateMicrovmShellAuthTokenRequest`'s body members. `microvmIdentifier` is a URI
476/// parameter and so is not in the body.
477///
478/// # There is no `allowedPorts` here, and its absence is the model's
479///
480/// The request declares exactly two members and one of them is in the URI. The shell is
481/// not a port: the token it mints opens the endpoint's single PTY session, not a route to
482/// a listener, which is why nothing in this shape can name a port (`docs/PLATFORM.md`,
483/// measured 2026-08-15).
484#[derive(Clone, Debug, Serialize)]
485#[serde(rename_all = "camelCase")]
486pub struct CreateShellAuthTokenWire {
487 /// Maximum 60 minutes, the same service ceiling the ordinary proxy token has —
488 /// the two JWEs carry the identical protected header and differ only by payload.
489 pub expiration_in_minutes: u32,
490}
491
492/// `PortSpecification`, the model's tagged union: one port, a range, or all of them.
493///
494/// A union rather than the single-field struct this was, and the change is a defect fix
495/// rather than completeness for its own sake. `Session::connect_headers(port)` and
496/// `connect_subprotocols(port)` exist to reach *another* port on the same VM, and they were
497/// built over a token the control plane had minted with `allowedPorts: [{port: 9000}]` — so
498/// they returned a correct-looking port header behind a credential that did not authorize
499/// it. Measured 2026-08-15 on one VM with a listener on 8080, varying only the mint:
500///
501/// | `allowedPorts` | `GET :8080` through the endpoint |
502/// | --- | --- |
503/// | `[{port: 9000}]` | **403 `Access to port denied`** |
504/// | `[{port: 9000}, {port: 8080}]` | 200, the guest answered |
505/// | `[{allPorts: {}}]` | 200 |
506/// | `[{range: {startPort: 8000, endPort: 9100}}]` | 200 |
507///
508/// One variable, four outcomes, so the token's scope is the whole of it. On the WebSocket
509/// path the same rejection is close code 1006 with no reason, which is why this was
510/// invisible to a client-side test: the strings were right and the credential behind them
511/// was not.
512///
513/// `#[serde(untagged)]` because the wire form is the *member name* as the key —
514/// `{"port": 9000}`, `{"range": {..}}`, `{"allPorts": {}}` — not a discriminator field, and
515/// serde's default enum representation would emit `{"Port": 9000}`. Each variant names its
516/// own key through `rename`.
517#[derive(Clone, Copy, Debug, Serialize)]
518#[serde(untagged)]
519pub enum PortSpecification {
520 /// Exactly one port. What a session built for the agent port asks for.
521 One {
522 #[serde(rename = "port")]
523 port: u16,
524 },
525 /// An inclusive range. Both members are required by the model.
526 Range {
527 #[serde(rename = "range")]
528 range: PortRange,
529 },
530 /// Every port on the VM.
531 ///
532 /// Deliberately **not** what this client mints by default. A token good for every port
533 /// is one whose leak is worth more, and the ports a caller actually needs are knowable:
534 /// the agent port plus whatever it asked for. Present because the model has it and a
535 /// caller building a general proxy needs it, reached only through an explicit scope.
536 All {
537 #[serde(rename = "allPorts")]
538 all_ports: AllPorts,
539 },
540}
541
542impl PortSpecification {
543 /// One port.
544 pub fn port(port: u16) -> Self {
545 Self::One { port }
546 }
547
548 /// An inclusive range of ports.
549 pub fn range(start: u16, end: u16) -> Self {
550 Self::Range {
551 range: PortRange {
552 start_port: start,
553 end_port: end,
554 },
555 }
556 }
557
558 /// Every port. See [`PortSpecification::All`] for why this is not a default.
559 pub fn all() -> Self {
560 Self::All {
561 all_ports: AllPorts {},
562 }
563 }
564}
565
566/// `PortRange`. Inclusive at both ends, per the model's `min: 1, max: 65535` on each.
567#[derive(Clone, Copy, Debug, Serialize)]
568#[serde(rename_all = "camelCase")]
569pub struct PortRange {
570 pub start_port: u16,
571 pub end_port: u16,
572}
573
574/// `AllPorts`, which the model declares with no members.
575///
576/// An empty struct rather than a unit one, because the wire form is `{}` and a unit struct
577/// serialises to `null` — which the service rejects as a malformed union member.
578#[derive(Clone, Copy, Debug, Serialize)]
579pub struct AllPorts {}
580
581// ── responses ───────────────────────────────────────────────────────────────
582
583/// `CreateMicrovmImageResponse`, narrowed to the members this client reads.
584///
585/// The model marks eight members required; the four below are the ones anything
586/// downstream uses. Deserializing a subset is safe — serde ignores the rest — and
587/// listing all twenty would be twenty more chances to misspell one.
588#[derive(Clone, Debug, Deserialize)]
589#[serde(rename_all = "camelCase")]
590pub struct CreateMicrovmImageResponseWire {
591 pub image_arn: String,
592 pub name: String,
593 pub state: String,
594 pub image_version: String,
595}
596
597/// `GetMicrovmImageOutput`.
598///
599/// `tags` is here rather than left to a `ListTags` this client does not implement: the
600/// service already sends the map on every `GetMicrovmImage`, so reading it costs nothing
601/// and a separate operation would cost a call. `createdAt` is one of the model's four
602/// required members and was the only one missing.
603#[derive(Clone, Debug, Deserialize)]
604#[serde(rename_all = "camelCase")]
605pub struct GetMicrovmImageResponseWire {
606 pub image_arn: String,
607 pub name: String,
608 pub state: String,
609 pub latest_active_image_version: Option<String>,
610 pub latest_failed_image_version: Option<String>,
611 /// Required by the model. Epoch seconds, possibly fractional.
612 pub created_at: f64,
613 /// Optional: the model marks only `createdAt` required, so an image never updated
614 /// carries no `updatedAt` and the absence is not a parse failure.
615 pub updated_at: Option<f64>,
616 /// `Tags`, absent rather than empty when the image carries none — measured 2026-08-15
617 /// as `"tags": {}` on a real `GetMicrovmImage`, but `Option` because the model does not
618 /// require the member and an absent map must not fail the parse.
619 pub tags: Option<std::collections::BTreeMap<String, String>>,
620}
621
622/// `ListMicrovmImageVersionsOutput`.
623#[derive(Clone, Debug, Deserialize)]
624#[serde(rename_all = "camelCase")]
625pub struct ListImageVersionsResponseWire {
626 pub items: Vec<MicrovmImageVersionSummaryWire>,
627 pub next_token: Option<String>,
628}
629
630/// `MicrovmImageVersionSummary`, which is **also** `GetMicrovmImageVersionOutput` and
631/// `UpdateMicrovmImageVersionResponse` — the three shapes are member-for-member identical
632/// in the model, so one type serves all of them.
633///
634/// One type rather than three for the reason [`MicrovmResponseWire`] gives: a second copy
635/// is a second place to keep twenty member spellings right, and the model itself declares
636/// them as one set. Checked member-by-member against `service-2.json` on 2026-08-16 —
637/// `GetMicrovmImageVersionOutput`, `UpdateMicrovmImageVersionResponse`, and
638/// `MicrovmImageVersionSummary` list the same twenty members with the same eight required.
639///
640/// Note `state` here **is** the member's name — unlike the build summary below, and that
641/// asymmetry is the whole trap.
642///
643/// # All eight required members, not the four this crate reads
644///
645/// The same argument [`MicrovmImageBuildSummaryWire`] records: the model marking a member
646/// required is the strongest promise it makes about a response, and a required member absent
647/// from the struct is one no drift check can notice going missing. `status` in particular was
648/// `Option<String>` while the model requires it — so a service that stopped sending the
649/// availability status would have read as `None`, which is exactly how a version blocked from
650/// launching would look identical to one nobody had ever set. Confirmed present on all 22
651/// versions in the conformance account (2026-08-16), so requiring it is a measurement rather
652/// than a reading of the model alone.
653///
654/// # `hooks` is deliberately **not** here, and the reason is a measurement
655///
656/// The model marks every member of `Hooks`, `MicrovmHooks`, and `MicrovmImageHooks` optional,
657/// while this module's request-side [`Hooks`] declares them all as bare fields — correct for
658/// a request, since this client always sends all six. A real response is not so generous:
659/// `GetMicrovmImageVersion` on an image built by another tool answered
660/// `"microvmHooks": {"run": "ENABLED", "runTimeoutInSeconds": 30}` and nothing else
661/// (measured 2026-08-16, us-east-1, `omnigent-host-vpc` version 3.0), so five of
662/// `MicrovmHooks`'s eight members were absent. Reusing [`Hooks`] here would fail that parse
663/// and turn a readable version into a client error. A response-shaped hooks type is the fix
664/// if a caller ever needs it; until then the absence is the honest option, and the test
665/// `a_versions_hooks_block_is_not_read_because_a_real_one_omits_members` pins the reason.
666#[derive(Clone, Debug, Deserialize, Serialize)]
667#[serde(rename_all = "camelCase")]
668pub struct MicrovmImageVersionSummaryWire {
669 // ── the model's eight required members ────────────────────────────────────
670 pub base_image_arn: String,
671 pub build_role_arn: String,
672 pub code_artifact: CodeArtifact,
673 pub image_arn: String,
674 pub image_version: String,
675 pub state: String,
676 /// `MicrovmImageVersionStatus`: `ACTIVE` or `INACTIVE`.
677 ///
678 /// A `String` rather than a [`VersionStatus`], because this is a response and a third
679 /// value AWS adds must parse rather than fail — the same rule
680 /// [`MicrovmImageBuildSummaryWire::architecture`] follows. [`VersionStatus`] is for the
681 /// request, where narrowing turns a typo into a compile error.
682 pub status: String,
683 /// Epoch seconds, possibly fractional.
684 pub created_at: f64,
685
686 // ── the optional ones, which are the config readback ─────────────────────
687 /// The base version this version was pinned to, when one was.
688 ///
689 /// The readback for `CreateMicrovmImage.baseImageVersion`, and the reason pinning is
690 /// worth doing: an unpinned build still reports one here, and the value the service
691 /// echoes is spelled differently from anything the base's own listing offers
692 /// (`"1.0"` against the managed base's `"0"`/`"1"` — docs/PLATFORM.md). So this is the
693 /// record of what was built, not a value to feed back into a request.
694 pub base_image_version: Option<String>,
695 pub description: Option<String>,
696 /// `ResourcesList`, max 1. The only place a built image's size class is observable:
697 /// `GetMicrovm` carries no memory figure at all.
698 pub resources: Option<Vec<Resources>>,
699 pub cpu_configurations: Option<Vec<CpuConfiguration>>,
700 /// The image-level egress list. **Max 1** in the model, not the 10 the VM-level
701 /// `NetworkConnectorList` allows — see [`crate::constants::MAX_IMAGE_EGRESS_CONNECTORS`].
702 pub egress_network_connectors: Option<Vec<String>>,
703 pub additional_os_capabilities: Option<Vec<String>>,
704 pub environment_variables: Option<std::collections::BTreeMap<String, String>>,
705 pub updated_at: Option<f64>,
706 /// The version-level failure reason. Measured **null** on real failures while the
707 /// build-level one is populated — docs/PLATFORM.md, "A failed build's `stateReason`
708 /// lives on the build".
709 pub state_reason: Option<String>,
710 pub tags: Option<std::collections::BTreeMap<String, String>>,
711}
712
713impl MicrovmImageVersionSummaryWire {
714 /// Whether `RunMicrovm` will launch this version.
715 ///
716 /// A comparison against the model's spelling through [`VersionStatus`] rather than
717 /// against a literal here, so the two cannot drift: the request type and the readback
718 /// agree on what `"ACTIVE"` is spelled like or neither compiles.
719 pub fn is_active(&self) -> bool {
720 self.status == VersionStatus::Active.as_str()
721 }
722
723 /// The version, its state, its availability status, and the reason when the service gave
724 /// one — the line a retire or a rollback prints.
725 ///
726 /// An absent reason renders nothing rather than an empty parenthesis, for the reason
727 /// [`MicrovmImageBuildSummaryWire::describe`] gives.
728 pub fn describe(&self) -> String {
729 match self.state_reason.as_deref() {
730 Some(reason) => format!(
731 "{} {} / {} ({reason})",
732 self.image_version, self.state, self.status
733 ),
734 None => format!("{} {} / {}", self.image_version, self.state, self.status),
735 }
736 }
737}
738
739/// `ListMicrovmImageBuildsOutput`.
740#[derive(Clone, Debug, Deserialize)]
741#[serde(rename_all = "camelCase")]
742pub struct ListImageBuildsResponseWire {
743 pub items: Vec<MicrovmImageBuildSummaryWire>,
744 pub next_token: Option<String>,
745}
746
747/// `MicrovmImageBuildSummary`.
748///
749/// **`buildState`, not `state`.** The model has no `state` member on this shape. A
750/// `#[serde(rename)]` to `state` here, or a field named `state` relying on
751/// `rename_all`, reproduces the bug described in this module's docs: the stall probe
752/// reads `None` from every real response and TRAP-2 becomes unfalsifiable. The
753/// deserializer test for this shape uses literal model-spelled JSON for that reason,
754/// and asserts that `{"state": ...}` **fails** to deserialize.
755/// Every member the model marks required is a bare field here, plus the optional
756/// `stateReason`. All eight required ones rather than the four this crate reads today,
757/// because the model requiring a member is the strongest promise it makes about a
758/// response, and a required member absent from the struct is a member no drift check can
759/// notice going missing.
760#[derive(Clone, Debug, Deserialize, Serialize)]
761#[serde(rename_all = "camelCase")]
762pub struct MicrovmImageBuildSummaryWire {
763 pub image_arn: String,
764 pub image_version: String,
765 pub build_id: String,
766 pub build_state: String,
767 /// `ARM_64`, the enum's only value — carried as `String` rather than narrowed, because
768 /// a response is not a request and a second value AWS adds must parse rather than fail.
769 pub architecture: String,
770 pub chipset: String,
771 pub chipset_generation: String,
772 /// A `Timestamp`, which rest-json sends as epoch seconds — possibly fractional, hence
773 /// `f64` rather than `i64`.
774 pub created_at: f64,
775 pub state_reason: Option<String>,
776}
777
778impl MicrovmImageBuildSummaryWire {
779 /// The build, as a stall diagnosis wants to read it: the state, the build id, and the
780 /// reason when the service gave one.
781 ///
782 /// The `buildId` is in here because it is the identifier `GetMicrovmImageBuild` takes,
783 /// so a reader handed a wedge verdict can go ask about a named build rather than about
784 /// "one of the builds". The reason is included because the model documents it as "the
785 /// reason for the build state, **if applicable**" — so it is populated on states other
786 /// than a failure, and a probe that dropped it would be discarding the service's own
787 /// account of why nothing was scheduled.
788 ///
789 /// An absent reason renders nothing at all rather than an empty parenthesis, for the
790 /// reason [`MicrovmResponseWire::state_reason`] gives: "the service said nothing" and
791 /// "the service said nothing useful" are different diagnoses.
792 pub fn describe(&self) -> String {
793 match self.state_reason.as_deref() {
794 Some(reason) => format!("{} {} ({reason})", self.build_id, self.build_state),
795 None => format!("{} {}", self.build_id, self.build_state),
796 }
797 }
798}
799
800/// `GetMicrovmImageBuildOutput`, which is `MicrovmImageBuildSummary` plus one member.
801///
802/// # Why this is not the same type as the summary
803///
804/// It differs by exactly one member — `snapshotBuild` — and that member is the whole reason
805/// to make the call: it is the **only** place any API reports a size for anything this
806/// platform builds. Nothing on `GetMicrovmImage`, `GetMicrovm`, or either listing carries a
807/// byte count, and the three figures here are the quantities the snapshot read, write, and
808/// storage line items bill on (`crate::cost`). A separate type rather than an `Option` field
809/// on the summary, because the summary is a *listing* shape that never carries one, and an
810/// `Option` there would read as "the service sometimes omits the sizes" rather than "the
811/// listing does not have this member".
812///
813/// Every other member is required and identical to the summary's, so the same eight are bare
814/// fields here.
815#[derive(Clone, Debug, Deserialize, Serialize)]
816#[serde(rename_all = "camelCase")]
817pub struct GetImageBuildResponseWire {
818 pub image_arn: String,
819 pub image_version: String,
820 pub build_id: String,
821 pub build_state: String,
822 pub architecture: String,
823 pub chipset: String,
824 /// The Graviton generation this build targeted. One `CreateMicrovmImage` fans out into
825 /// one build per generation, so a version's builds differ only in this member — and a
826 /// partially failed image, one generation succeeding and the other not, is a state a
827 /// caller should expect (docs/PLATFORM.md).
828 pub chipset_generation: String,
829 pub created_at: f64,
830 pub state_reason: Option<String>,
831 /// The three snapshot sizes, when the service reports them.
832 ///
833 /// `Option` because the model does not mark it required, and because a **failed** build
834 /// answers a partial one: measured 2026-08-16 on a real `FAILED` build, `snapshotBuild`
835 /// carried `codeInstallSizeInBytes` alone with no memory and no disk snapshot — which is
836 /// exactly the shape of a build that installed the code and then never produced a
837 /// snapshot.
838 pub snapshot_build: Option<SnapshotBuild>,
839}
840
841impl GetImageBuildResponseWire {
842 /// The build as a diagnosis reads it: the generation, the state, the reason when there is
843 /// one, and the sizes when the service reported them.
844 ///
845 /// The generation is in the line because a version has one build per Graviton generation
846 /// and they can disagree — "the build failed" is ambiguous where "generation 4 failed" is
847 /// not. Sizes are appended only when present, for the reason the absent-reason rule
848 /// gives: a rendered `0 bytes` would claim a measurement the service did not make.
849 pub fn describe(&self) -> String {
850 let mut line = match self.state_reason.as_deref() {
851 Some(reason) => format!(
852 "{} {} (chipset generation {}) — {reason}",
853 self.build_id, self.build_state, self.chipset_generation
854 ),
855 None => format!(
856 "{} {} (chipset generation {})",
857 self.build_id, self.build_state, self.chipset_generation
858 ),
859 };
860 if let Some(sizes) = &self.snapshot_build
861 && let Some(rendered) = sizes.describe()
862 {
863 line.push_str(&format!(", {rendered}"));
864 }
865 line
866 }
867}
868
869/// `SnapshotBuild`: the three byte counts, each optional in the model.
870///
871/// `u64` from the model's `Long`, and every one `Option` — the model marks none required, and
872/// a failed build really does answer with a subset (see
873/// [`GetImageBuildResponseWire::snapshot_build`]). A defaulted `0` would be a size claim
874/// nobody made, which is the same distinction `stateReason`'s `None` carries.
875#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
876#[serde(rename_all = "camelCase")]
877pub struct SnapshotBuild {
878 pub memory_snapshot_size_in_bytes: Option<u64>,
879 pub code_install_size_in_bytes: Option<u64>,
880 pub disk_snapshot_size_in_bytes: Option<u64>,
881}
882
883impl SnapshotBuild {
884 /// The sizes the service reported, or `None` when it reported none of them.
885 ///
886 /// `None` rather than an empty string so a caller can tell "no sizes" from "sizes that
887 /// render blank", and so [`GetImageBuildResponseWire::describe`] does not append a
888 /// dangling comma.
889 pub fn describe(&self) -> Option<String> {
890 let parts: Vec<String> = [
891 ("memory", self.memory_snapshot_size_in_bytes),
892 ("code", self.code_install_size_in_bytes),
893 ("disk", self.disk_snapshot_size_in_bytes),
894 ]
895 .into_iter()
896 .filter_map(|(label, bytes)| bytes.map(|bytes| format!("{label} {bytes} bytes")))
897 .collect();
898 (!parts.is_empty()).then(|| parts.join(", "))
899 }
900}
901
902/// `ListManagedMicrovmImageVersionsOutput`.
903///
904/// The versions of an AWS-managed base image, which is what closes the reproducibility hole:
905/// every build this client made floated on whatever `baseImageVersion` the service defaulted
906/// to, and that default has already moved once (`al2023-1` carries `"0"` and `"1"`).
907#[derive(Clone, Debug, Deserialize)]
908#[serde(rename_all = "camelCase")]
909pub struct ListManagedVersionsResponseWire {
910 pub items: Vec<ManagedMicrovmImageVersionWire>,
911 pub next_token: Option<String>,
912}
913
914/// `ManagedMicrovmImageVersion`. Three required members and one optional.
915///
916/// Note how much thinner this is than [`MicrovmImageVersionSummaryWire`]: a managed base's
917/// version carries no state, no status, no config — just an ARN, a version string, and two
918/// timestamps. So there is nothing here to check before pinning one, which is why
919/// [`crate::control::ControlPlane::managed_base_versions`] hands back the strings and lets
920/// the caller choose.
921#[derive(Clone, Debug, Deserialize)]
922#[serde(rename_all = "camelCase")]
923pub struct ManagedMicrovmImageVersionWire {
924 pub image_arn: String,
925 /// A **bare integer** for the managed base (`"0"`, `"1"`), where a custom image's
926 /// versions are `"1.0"`. The two spellings are not comparable and code that parses one
927 /// will not parse the other (docs/PLATFORM.md).
928 pub image_version: String,
929 pub created_at: f64,
930 pub updated_at: Option<f64>,
931}
932
933/// `ListManagedMicrovmImagesOutput`.
934#[derive(Clone, Debug, Deserialize)]
935#[serde(rename_all = "camelCase")]
936pub struct ListManagedImagesResponseWire {
937 pub items: Vec<ManagedMicrovmImageSummaryWire>,
938 pub next_token: Option<String>,
939}
940
941/// `ManagedMicrovmImageSummary`: an ARN and two timestamps, and **that is all the model
942/// declares**.
943///
944/// # Why a discovered base cannot construct a [`crate::control::BaseImage`]
945///
946/// [`crate::control::BaseImage`] pairs three things that must agree: the `baseImageArn`, the
947/// Dockerfile `FROM` that goes with it, and whether the image declares a `WORKDIR`. This
948/// shape carries the first and says nothing about the other two — no registry reference, no
949/// architecture, no working directory. So `require_matching_from` would have no `FROM` to
950/// compare a caller's Dockerfile against, and `require_workdir` would have no answer to the
951/// question it exists to ask; both guards would have to be skipped for a discovered base,
952/// which is worse than not discovering one. The registry ref in particular is not derivable:
953/// `al2023-1` pairs with `public.ecr.aws/amazonlinux/amazonlinux:2023-minimal`, and nothing
954/// in the ARN says so.
955///
956/// So this is **informational only** — surfaced by `microvm doctor` so a caller can see
957/// whether AWS has published a base this client does not know about, and never fed into a
958/// create request. Measured 2026-08-16: the listing returns exactly one item, so a client
959/// hardcoding `al2023-1` is currently missing nothing.
960#[derive(Clone, Debug, Deserialize)]
961#[serde(rename_all = "camelCase")]
962pub struct ManagedMicrovmImageSummaryWire {
963 pub image_arn: String,
964 pub created_at: f64,
965 pub updated_at: Option<f64>,
966}
967
968/// `RunMicrovmResponse` and `GetMicrovmResponse` — identical in every member this client
969/// reads, so one type serves both.
970///
971/// One type rather than two because the two shapes agree on all seven required members
972/// and both carry `state`, `endpoint`, and `stateReason`; a second type would be a
973/// second place to keep the spelling right.
974#[derive(Clone, Debug, Deserialize)]
975#[serde(rename_all = "camelCase")]
976pub struct MicrovmResponseWire {
977 pub microvm_id: String,
978 pub state: String,
979 pub endpoint: String,
980 pub image_arn: String,
981 pub image_version: String,
982 /// Optional in the model, and the absence is information: TRAP-8's message says so
983 /// rather than printing an empty string.
984 pub state_reason: Option<String>,
985 pub idle_policy: Option<IdlePolicy>,
986 /// `maximumDurationInSeconds`. Not required by the model, so absence parses.
987 pub maximum_duration_in_seconds: Option<u32>,
988 /// `startedAt`, epoch seconds: when the VM first started. Absent on a launch reply.
989 pub started_at: Option<f64>,
990 /// `terminatedAt`, epoch seconds. Present once the VM has terminated.
991 pub terminated_at: Option<f64>,
992}
993
994/// `CreateMicrovmAuthTokenResponse`.
995///
996/// `authToken` is a `TokenParts` **map**, not a string (TRAP-7). Reading it as a string
997/// is a deserialization failure rather than a wrong value, which is the good direction —
998/// but the map's `X-aws-proxy-auth` key is what the endpoint header takes, and a caller
999/// who sends the map's `Debug` rendering gets a rejection that reads like a bad token.
1000#[derive(Clone, Debug, Deserialize)]
1001#[serde(rename_all = "camelCase")]
1002pub struct CreateAuthTokenResponseWire {
1003 pub auth_token: std::collections::BTreeMap<String, String>,
1004}
1005
1006/// `CreateMicrovmShellAuthTokenResponse`.
1007///
1008/// Its own transcription rather than a reuse of [`CreateAuthTokenResponseWire`], because
1009/// the model declares it as its own shape — the two happen to carry one identical member
1010/// (`authToken`, a `TokenParts` map whose `X-aws-proxy-auth` key is the credential), and a
1011/// shared struct would silently bind this client to the coincidence holding forever.
1012#[derive(Clone, Debug, Deserialize)]
1013#[serde(rename_all = "camelCase")]
1014pub struct CreateShellAuthTokenResponseWire {
1015 pub auth_token: std::collections::BTreeMap<String, String>,
1016}
1017
1018/// `ListMicrovmsResponse`.
1019#[derive(Clone, Debug, Deserialize)]
1020#[serde(rename_all = "camelCase")]
1021pub struct ListMicrovmsResponseWire {
1022 pub items: Vec<MicrovmItemWire>,
1023 pub next_token: Option<String>,
1024}
1025
1026/// `MicrovmItem` — the list shape, which is narrower than `GetMicrovmResponse`: it
1027/// carries no `endpoint` and no `stateReason`.
1028#[derive(Clone, Debug, Deserialize)]
1029#[serde(rename_all = "camelCase")]
1030pub struct MicrovmItemWire {
1031 pub microvm_id: String,
1032 pub state: String,
1033 pub image_arn: String,
1034 pub image_version: String,
1035}
1036
1037/// `DeleteMicrovmImageOutput`.
1038///
1039/// # Kept and read, rather than deleted as dead
1040///
1041/// This struct was parsed nowhere: `try_delete_image` discarded the reply, so the shape
1042/// existed and no code could observe drift in it. The choice was to delete it or to read
1043/// it, and reading it wins on one specific case — a 2xx whose `state` is a `*_FAILED`
1044/// spelling. That is the service accepting the delete request and refusing the work, and
1045/// without the readback it is indistinguishable from a successful delete: `delete_image`
1046/// answers `true`, teardown reports clean, and an image keeps billing. This project has
1047/// had exactly that failure once already, in `tools/verify-clean.py`, which is why the
1048/// account is now asked what leaked rather than trusted to have been cleaned.
1049///
1050/// **`DELETING` and `DELETED` are both success** and the call site treats them alike. The
1051/// deletion is asynchronous, so `DELETING` is the ordinary answer; treating it as
1052/// incomplete would make the retry loop re-issue a delete that is already in progress and
1053/// then report failure on the `ConflictException` that comes back.
1054#[derive(Clone, Debug, Deserialize)]
1055#[serde(rename_all = "camelCase")]
1056pub struct DeleteImageResponseWire {
1057 pub image_identifier: String,
1058 pub state: String,
1059}
1060
1061/// `ListMicrovmImagesResponse`.
1062///
1063/// `nextToken` is how the account's listing paginates, and the name resolver **must**
1064/// follow it: an image on page two of a paginated listing is still an image, and a
1065/// resolver that read only the first page would report "no image named X" for a name
1066/// that exists — the confident wrong answer, which is worse than a failure.
1067#[derive(Clone, Debug, Deserialize)]
1068#[serde(rename_all = "camelCase")]
1069pub struct ListImagesResponseWire {
1070 pub items: Vec<MicrovmImageSummaryWire>,
1071 pub next_token: Option<String>,
1072}
1073
1074/// `MicrovmImageSummary`, narrowed to the members name resolution reads.
1075///
1076/// The model marks `imageArn`, `name`, `state`, and `createdAt` required; the first
1077/// three are the ones anything downstream uses.
1078#[derive(Clone, Debug, Deserialize)]
1079#[serde(rename_all = "camelCase")]
1080pub struct MicrovmImageSummaryWire {
1081 pub image_arn: String,
1082 pub name: String,
1083 pub state: String,
1084}
1085
1086/// The modeled error shapes, which all carry a `message` and several add fields.
1087///
1088/// One type for all seven because every one has `message` as its only member this client
1089/// reads, and the status code is what distinguishes them.
1090///
1091/// `message` is `Option` for a reason that is itself a finding: an unsupported region
1092/// answers `AccessDeniedException` with the message field **null** (TRAP-6). A required
1093/// `String` here would fail to deserialize and report a parse error instead of the
1094/// denial, hiding the one detail that identifies the trap.
1095#[derive(Clone, Debug, Default, Deserialize)]
1096#[serde(rename_all = "camelCase")]
1097pub struct ServiceErrorWire {
1098 pub message: Option<String>,
1099 /// `ThrottlingException`/`ServiceQuotaExceededException`.
1100 pub quota_code: Option<String>,
1101 /// `ThrottlingException`/`ServiceQuotaExceededException`.
1102 pub service_code: Option<String>,
1103 /// `ConflictException`/`ResourceNotFoundException`/`ServiceQuotaExceededException`.
1104 pub resource_type: Option<String>,
1105 /// As above.
1106 pub resource_id: Option<String>,
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111 use super::*;
1112
1113 /// The build summary, from JSON spelled exactly as `MicrovmImageBuildSummary`
1114 /// declares it — every required member present, in the model's casing.
1115 ///
1116 /// **This is the honest-fake test.** It parses text, not this module's own output, so
1117 /// it cannot agree with a misreading the way the Python fake did.
1118 #[test]
1119 fn a_build_summary_deserialises_from_the_models_own_spelling() {
1120 let json = r#"{
1121 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1122 "imageVersion": "1",
1123 "buildId": "build-abc",
1124 "buildState": "PENDING",
1125 "architecture": "ARM_64",
1126 "chipset": "GRAVITON",
1127 "chipsetGeneration": "1",
1128 "createdAt": 1754524800
1129 }"#;
1130 let parsed: MicrovmImageBuildSummaryWire =
1131 serde_json::from_str(json).expect("the model's own spelling parses");
1132 assert_eq!(parsed.build_state, "PENDING");
1133 assert_eq!(parsed.build_id, "build-abc");
1134 assert_eq!(parsed.image_version, "1");
1135 assert_eq!(parsed.state_reason, None);
1136
1137 // The five members the struct used to drop, all of them model-required. A required
1138 // member absent from the struct is a member no drift check can notice going missing.
1139 assert_eq!(
1140 parsed.image_arn,
1141 "arn:aws:lambda:us-east-1:123456789012:microvm-image:img"
1142 );
1143 assert_eq!(parsed.architecture, "ARM_64");
1144 assert_eq!(parsed.chipset, "GRAVITON");
1145 assert_eq!(parsed.chipset_generation, "1");
1146 assert_eq!(parsed.created_at, 1_754_524_800.0);
1147 }
1148
1149 /// A summary missing a member the model marks **required** fails to deserialize, which
1150 /// is what makes the five added members load-bearing rather than decorative.
1151 ///
1152 /// One case per member, because a single omission would prove only that *some* member is
1153 /// required. `stateReason` is checked in the other direction: it is the one optional
1154 /// member, so omitting it must still parse.
1155 #[test]
1156 fn a_build_summary_missing_a_required_member_fails_to_deserialise() {
1157 let members = [
1158 (
1159 "imageArn",
1160 r#""arn:aws:lambda:us-east-1:1:microvm-image:i""#,
1161 ),
1162 ("imageVersion", r#""1""#),
1163 ("buildId", r#""build-abc""#),
1164 ("buildState", r#""PENDING""#),
1165 ("architecture", r#""ARM_64""#),
1166 ("chipset", r#""GRAVITON""#),
1167 ("chipsetGeneration", r#""1""#),
1168 ("createdAt", "1754524800"),
1169 ];
1170
1171 for omitted in members.iter().map(|(name, _)| *name) {
1172 let body: Vec<String> = members
1173 .iter()
1174 .filter(|(name, _)| *name != omitted)
1175 .map(|(name, value)| format!(r#""{name}": {value}"#))
1176 .collect();
1177 let json = format!("{{{}}}", body.join(", "));
1178 let error = serde_json::from_str::<MicrovmImageBuildSummaryWire>(&json)
1179 .expect_err(&format!("{omitted} is required by the model"));
1180 assert!(
1181 error.to_string().contains(omitted),
1182 "the error must name the member that is missing ({omitted}): {error}"
1183 );
1184 }
1185
1186 // The one optional member: omitting `stateReason` parses, and the absence is `None`
1187 // rather than an empty string.
1188 let all: Vec<String> = members
1189 .iter()
1190 .map(|(name, value)| format!(r#""{name}": {value}"#))
1191 .collect();
1192 let parsed: MicrovmImageBuildSummaryWire =
1193 serde_json::from_str(&format!("{{{}}}", all.join(", ")))
1194 .expect("stateReason is optional");
1195 assert_eq!(parsed.state_reason, None);
1196 }
1197
1198 /// `describe` names the build id, the state, and the reason when there is one — and
1199 /// renders **nothing** rather than an empty parenthesis when there is not.
1200 ///
1201 /// The build id is in there because it is what `GetMicrovmImageBuild` takes, so a reader
1202 /// handed a wedge verdict can ask about a named build rather than about "one of the
1203 /// builds".
1204 #[test]
1205 fn a_build_describes_itself_with_its_id_and_only_a_reason_it_has() {
1206 let with_reason: MicrovmImageBuildSummaryWire = serde_json::from_str(
1207 r#"{
1208 "imageArn": "arn:aws:lambda:us-east-1:1:microvm-image:i",
1209 "imageVersion": "1",
1210 "buildId": "build-abc",
1211 "buildState": "FAILED",
1212 "architecture": "ARM_64",
1213 "chipset": "GRAVITON",
1214 "chipsetGeneration": "1",
1215 "createdAt": 1754524800,
1216 "stateReason": "no space left on device"
1217 }"#,
1218 )
1219 .expect("parses");
1220 assert_eq!(
1221 with_reason.describe(),
1222 "build-abc FAILED (no space left on device)"
1223 );
1224
1225 let without: MicrovmImageBuildSummaryWire = serde_json::from_str(
1226 r#"{
1227 "imageArn": "arn:aws:lambda:us-east-1:1:microvm-image:i",
1228 "imageVersion": "1",
1229 "buildId": "build-abc",
1230 "buildState": "PENDING",
1231 "architecture": "ARM_64",
1232 "chipset": "GRAVITON",
1233 "chipsetGeneration": "1",
1234 "createdAt": 1754524800
1235 }"#,
1236 )
1237 .expect("parses");
1238 assert_eq!(without.describe(), "build-abc PENDING");
1239 assert!(
1240 !without.describe().contains("()"),
1241 "an absent reason renders nothing, not an empty parenthesis: {}",
1242 without.describe()
1243 );
1244 }
1245
1246 /// The bug, made a compile-and-test-time fact: a response carrying `state` instead of
1247 /// `buildState` **fails to deserialize** rather than yielding a summary whose state is
1248 /// silently absent.
1249 ///
1250 /// This is the falsification for the whole `buildState` discipline. Rename the field
1251 /// to `state` (or add a `#[serde(alias = "state")]` "for compatibility") and this
1252 /// test goes red — which is what the Python client had no equivalent of, and why its
1253 /// dead guard passed for a review round.
1254 #[test]
1255 fn a_summary_spelled_state_instead_of_build_state_fails_to_deserialise() {
1256 let json = r#"{
1257 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1258 "imageVersion": "1",
1259 "buildId": "build-abc",
1260 "state": "PENDING",
1261 "architecture": "ARM_64",
1262 "chipset": "GRAVITON",
1263 "chipsetGeneration": "1",
1264 "createdAt": 1754524800
1265 }"#;
1266 let parsed: Result<MicrovmImageBuildSummaryWire, _> = serde_json::from_str(json);
1267 let error = parsed.expect_err("MicrovmImageBuildSummary has no member called state");
1268 assert!(
1269 error.to_string().contains("buildState"),
1270 "the error must name the member that is actually missing: {error}"
1271 );
1272 }
1273
1274 /// The asymmetry that makes the trap a trap: the *version* summary really does have a
1275 /// member called `state`, so "these shapes use `state`" is true of one and false of
1276 /// its neighbour. Both spellings are asserted here, together, so a reader sees why
1277 /// the two cannot be handled by one habit.
1278 #[test]
1279 fn a_version_summary_does_use_state_which_is_why_the_build_one_confuses() {
1280 let json = r#"{
1281 "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
1282 "buildRoleArn": "arn:aws:iam::123456789012:role/build",
1283 "codeArtifact": {"uri": "s3://bucket/img.zip"},
1284 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1285 "imageVersion": "1",
1286 "state": "SUCCESSFUL",
1287 "status": "ACTIVE",
1288 "createdAt": 1754524800
1289 }"#;
1290 let parsed: MicrovmImageVersionSummaryWire =
1291 serde_json::from_str(json).expect("the version summary's member is state");
1292 assert_eq!(parsed.state, "SUCCESSFUL");
1293 assert_eq!(parsed.status, "ACTIVE");
1294 assert!(parsed.is_active(), "ACTIVE is what RunMicrovm will launch");
1295 }
1296
1297 /// The version summary's `stateReason`, which is the **version-level** failure reason
1298 /// `GetMicrovmImage` structurally cannot provide — that shape has no such member.
1299 ///
1300 /// It was parsed and never read, so a build failure could only be reported with a log
1301 /// group and a guess while the service's own account of the cause sat in hand.
1302 #[test]
1303 fn a_version_summary_carries_the_state_reason_get_image_cannot() {
1304 let json = r#"{
1305 "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
1306 "buildRoleArn": "arn:aws:iam::123456789012:role/build",
1307 "codeArtifact": {"uri": "s3://bucket/img.zip"},
1308 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1309 "imageVersion": "2",
1310 "state": "FAILED",
1311 "status": "INACTIVE",
1312 "createdAt": 1754524800,
1313 "stateReason": "one or more builds failed"
1314 }"#;
1315 let parsed: MicrovmImageVersionSummaryWire = serde_json::from_str(json).expect("parses");
1316 assert_eq!(parsed.state, "FAILED");
1317 assert_eq!(
1318 parsed.state_reason.as_deref(),
1319 Some("one or more builds failed")
1320 );
1321
1322 // `GetMicrovmImageOutput` has no `stateReason` member at all, which is the whole
1323 // reason the version-level one is worth reading. A response carrying one parses and
1324 // the member is simply dropped, so this is asserted by there being no field to read
1325 // rather than by a failure.
1326 let image: GetMicrovmImageResponseWire = serde_json::from_str(
1327 r#"{"imageArn": "a", "name": "n", "state": "CREATE_FAILED",
1328 "createdAt": 1754524800, "stateReason": "ignored"}"#,
1329 )
1330 .expect("an unknown member is dropped");
1331 assert_eq!(image.state, "CREATE_FAILED");
1332 }
1333
1334 /// `GetMicrovmImageOutput` carries `tags`, `createdAt`, and `updatedAt`.
1335 ///
1336 /// Reading `tags` here is a cheaper answer to "what are this image's tags" than
1337 /// implementing `ListTags`: the service already sends the map on every call. The literal
1338 /// below is the shape a real response has — measured 2026-08-15 against a live
1339 /// `GetMicrovmImage`, which answered `"tags": {}` and an `updatedAt` on an untagged image.
1340 #[test]
1341 fn a_get_image_response_carries_its_tags_and_timestamps() {
1342 let json = r#"{
1343 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1344 "name": "img",
1345 "state": "CREATED",
1346 "latestActiveImageVersion": "1.0",
1347 "createdAt": 1754524800,
1348 "updatedAt": 1754528400,
1349 "tags": {"owner": "conformance", "cost-centre": "agents"}
1350 }"#;
1351 let parsed: GetMicrovmImageResponseWire = serde_json::from_str(json).expect("parses");
1352 assert_eq!(parsed.created_at, 1_754_524_800.0);
1353 assert_eq!(parsed.updated_at, Some(1_754_528_400.0));
1354 let tags = parsed.tags.expect("the map was sent");
1355 assert_eq!(tags.get("owner").map(String::as_str), Some("conformance"));
1356 assert_eq!(tags.len(), 2);
1357
1358 // An untagged image answers with an empty map, which is different from an absent
1359 // one: `Some({})` says the service answered and the image has no tags.
1360 let empty: GetMicrovmImageResponseWire = serde_json::from_str(
1361 r#"{"imageArn": "a", "name": "n", "state": "CREATED",
1362 "createdAt": 1754524800, "updatedAt": 1754528400, "tags": {}}"#,
1363 )
1364 .expect("parses");
1365 assert_eq!(empty.tags, Some(std::collections::BTreeMap::new()));
1366
1367 // And an absent map is `None` rather than a parse failure, since the model does not
1368 // mark `tags` required.
1369 let absent: GetMicrovmImageResponseWire = serde_json::from_str(
1370 r#"{"imageArn": "a", "name": "n", "state": "CREATED", "createdAt": 1754524800}"#,
1371 )
1372 .expect("tags is optional");
1373 assert_eq!(absent.tags, None);
1374 assert_eq!(absent.updated_at, None);
1375 }
1376
1377 /// `createdAt` is required by the model, so a `GetMicrovmImage` response without it
1378 /// fails rather than yielding an image whose creation time is silently zero.
1379 #[test]
1380 fn a_get_image_response_without_created_at_fails_to_deserialise() {
1381 let error = serde_json::from_str::<GetMicrovmImageResponseWire>(
1382 r#"{"imageArn": "a", "name": "n", "state": "CREATED"}"#,
1383 )
1384 .expect_err("createdAt is one of the model's four required members");
1385 assert!(error.to_string().contains("createdAt"), "{error}");
1386 }
1387
1388 /// `IdlePolicy` round-trips through a **response** body, all three members present.
1389 ///
1390 /// The comment on the shape used to say `suspendedDurationSeconds` "exists only in the
1391 /// request". The JSON below is what a live `GetMicrovm` answered on 2026-08-15, so this
1392 /// test is the measurement rather than a restatement of the model.
1393 #[test]
1394 fn an_idle_policy_comes_back_on_a_response_with_all_three_members() {
1395 let json = r#"{
1396 "microvmId": "mvm-1",
1397 "state": "RUNNING",
1398 "endpoint": "https://e",
1399 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1400 "imageVersion": "1.0",
1401 "idlePolicy": {
1402 "maxIdleDurationSeconds": 1800,
1403 "suspendedDurationSeconds": 600,
1404 "autoResumeEnabled": false
1405 },
1406 "maximumDurationInSeconds": 10800
1407 }"#;
1408 let parsed: MicrovmResponseWire = serde_json::from_str(json).expect("parses");
1409 let policy = parsed.idle_policy.expect("the service sent one");
1410 assert_eq!(policy.max_idle_duration_seconds, 1800);
1411 assert_eq!(
1412 policy.suspended_duration_seconds, 600,
1413 "the member the comment claimed the response omits"
1414 );
1415 assert!(!policy.auto_resume_enabled);
1416 }
1417
1418 /// A `DeleteMicrovmImage` readback parses, and the failure spelling is distinguishable
1419 /// from the two success ones — which is the whole reason this shape is read rather than
1420 /// deleted as dead.
1421 #[test]
1422 fn a_delete_readback_distinguishes_failure_from_deleting_and_deleted() {
1423 for state in ["DELETING", "DELETED", "DELETE_FAILED"] {
1424 let json = format!(
1425 r#"{{"imageIdentifier": "arn:aws:lambda:us-east-1:1:microvm-image:img",
1426 "state": "{state}"}}"#
1427 );
1428 let parsed: DeleteImageResponseWire = serde_json::from_str(&json).expect("parses");
1429 assert_eq!(parsed.state, state);
1430 assert_eq!(
1431 parsed.image_identifier,
1432 "arn:aws:lambda:us-east-1:1:microvm-image:img"
1433 );
1434 }
1435 }
1436
1437 /// `ListMicrovmImagesResponse` from the model's own spelling, `nextToken` included.
1438 ///
1439 /// The honest-fake rule again: this JSON is text transcribed from `service-2.json`,
1440 /// not a round trip through this module's serializer, so a misspelled member here
1441 /// cannot agree with a misspelled member in the struct.
1442 #[test]
1443 fn an_image_listing_deserialises_from_the_models_own_spelling() {
1444 let json = r#"{
1445 "items": [{
1446 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1447 "name": "img",
1448 "state": "ACTIVE",
1449 "latestActiveImageVersion": "1",
1450 "createdAt": 1754524800
1451 }],
1452 "nextToken": "opaque-page-2-token"
1453 }"#;
1454 let parsed: ListImagesResponseWire =
1455 serde_json::from_str(json).expect("the model's own spelling parses");
1456 assert_eq!(parsed.items.len(), 1);
1457 assert_eq!(parsed.items[0].name, "img");
1458 assert_eq!(
1459 parsed.items[0].image_arn,
1460 "arn:aws:lambda:us-east-1:123456789012:microvm-image:img"
1461 );
1462 assert_eq!(parsed.items[0].state, "ACTIVE");
1463 assert_eq!(parsed.next_token.as_deref(), Some("opaque-page-2-token"));
1464
1465 // The final page: nextToken absent means None, which is what stops the loop.
1466 let last: ListImagesResponseWire =
1467 serde_json::from_str(r#"{"items": []}"#).expect("an absent nextToken parses");
1468 assert!(last.items.is_empty());
1469 assert_eq!(last.next_token, None);
1470 }
1471
1472 /// `RunMicrovmResponse` from the model's spelling, including the optional
1473 /// `stateReason` that TRAP-8 reports.
1474 #[test]
1475 fn a_run_response_deserialises_with_its_state_reason() {
1476 let json = r#"{
1477 "microvmId": "mvm-123",
1478 "state": "TERMINATED",
1479 "endpoint": "https://mvm-123.microvm.amazonaws.com",
1480 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1481 "imageVersion": "1",
1482 "maximumDurationInSeconds": 3600,
1483 "startedAt": 1754524800,
1484 "stateReason": "run hook returned 500"
1485 }"#;
1486 let parsed: MicrovmResponseWire = serde_json::from_str(json).expect("parses");
1487 assert_eq!(parsed.state, "TERMINATED");
1488 assert_eq!(
1489 parsed.state_reason.as_deref(),
1490 Some("run hook returned 500")
1491 );
1492 assert_eq!(parsed.microvm_id, "mvm-123");
1493 }
1494
1495 /// The same shape without `stateReason`, which the model permits. The field must be
1496 /// `None` rather than an empty string, because "the service said nothing" and "the
1497 /// service said nothing useful" are different diagnoses.
1498 #[test]
1499 fn an_absent_state_reason_is_none_rather_than_an_empty_string() {
1500 let json = r#"{
1501 "microvmId": "mvm-123",
1502 "state": "RUNNING",
1503 "endpoint": "https://mvm-123.microvm.amazonaws.com",
1504 "imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
1505 "imageVersion": "1",
1506 "maximumDurationInSeconds": 3600,
1507 "startedAt": 1754524800
1508 }"#;
1509 let parsed: MicrovmResponseWire = serde_json::from_str(json).expect("parses");
1510 assert_eq!(parsed.state_reason, None);
1511 }
1512
1513 /// `authToken` is a map (TRAP-7). The key is the header name, and reading the map's
1514 /// one interesting key is what the proxy needs.
1515 #[test]
1516 fn an_auth_token_response_is_a_header_map_not_a_string() {
1517 let json = r#"{"authToken": {"X-aws-proxy-auth": "opaque-token-value"}}"#;
1518 let parsed: CreateAuthTokenResponseWire = serde_json::from_str(json).expect("parses");
1519 assert_eq!(
1520 parsed
1521 .auth_token
1522 .get("X-aws-proxy-auth")
1523 .map(String::as_str),
1524 Some("opaque-token-value")
1525 );
1526 }
1527
1528 /// A string `authToken` fails rather than being coerced. The failure is the good
1529 /// direction: a client that accepted both would send a stringified map as a header
1530 /// value and get a rejection that reads like a bad token.
1531 #[test]
1532 fn a_string_auth_token_fails_to_deserialise() {
1533 let json = r#"{"authToken": "opaque-token-value"}"#;
1534 let parsed: Result<CreateAuthTokenResponseWire, _> = serde_json::from_str(json);
1535 assert!(parsed.is_err(), "TokenParts is a map shape");
1536 }
1537
1538 /// TRAP-6's null message survives deserialization. A required `String` here would
1539 /// fail to parse and report a parse error, which hides the one detail — the null —
1540 /// that tells an unsupported region apart from a real IAM denial.
1541 #[test]
1542 fn an_access_denied_with_a_null_message_still_deserialises() {
1543 let parsed: ServiceErrorWire =
1544 serde_json::from_str(r#"{"message": null}"#).expect("a null message must parse");
1545 assert_eq!(parsed.message, None);
1546
1547 let empty: ServiceErrorWire = serde_json::from_str("{}").expect("an absent message parses");
1548 assert_eq!(empty.message, None);
1549 }
1550
1551 /// An unknown member is dropped rather than failing, so a member AWS adds does not
1552 /// break the client. This is the deliberate absence of `deny_unknown_fields`.
1553 #[test]
1554 fn an_unknown_response_member_is_ignored() {
1555 let json = r#"{
1556 "microvmId": "mvm-123",
1557 "state": "RUNNING",
1558 "endpoint": "https://e",
1559 "imageArn": "arn",
1560 "imageVersion": "1",
1561 "somethingAwsAddedLater": {"nested": [1, 2, 3]}
1562 }"#;
1563 let parsed: MicrovmResponseWire =
1564 serde_json::from_str(json).expect("additive change is safe");
1565 assert_eq!(parsed.microvm_id, "mvm-123");
1566 }
1567
1568 /// The create-image request serialises to the model's member names. Asserted against
1569 /// literal keys rather than a round trip, for the same reason the response tests hold
1570 /// JSON: `minimumMemoryInMiB` in particular is a casing `rename_all = "camelCase"`
1571 /// gets wrong on its own (it produces `minimumMemoryInMib`).
1572 #[test]
1573 fn the_create_request_serialises_to_the_models_member_names() {
1574 let wire = CreateMicrovmImageWire {
1575 name: "img".to_string(),
1576 base_image_arn: "arn:base".to_string(),
1577 base_image_version: None,
1578 build_role_arn: "arn:role".to_string(),
1579 code_artifact: CodeArtifact {
1580 uri: "s3://bucket/img.zip".to_string(),
1581 },
1582 cpu_configurations: vec![CpuConfiguration {
1583 architecture: "ARM_64".to_string(),
1584 }],
1585 resources: vec![Resources {
1586 minimum_memory_in_mib: 2048,
1587 }],
1588 hooks: Hooks {
1589 port: 9000,
1590 microvm_hooks: MicrovmHooks {
1591 run: HookState::Enabled,
1592 run_timeout_in_seconds: 30,
1593 resume: HookState::Enabled,
1594 resume_timeout_in_seconds: 30,
1595 suspend: HookState::Enabled,
1596 suspend_timeout_in_seconds: 30,
1597 terminate: HookState::Enabled,
1598 terminate_timeout_in_seconds: 30,
1599 },
1600 microvm_image_hooks: MicrovmImageHooks {
1601 ready: HookState::Enabled,
1602 ready_timeout_in_seconds: 300,
1603 validate: HookState::Enabled,
1604 validate_timeout_in_seconds: 300,
1605 },
1606 },
1607 additional_os_capabilities: Some(vec!["ALL".to_string()]),
1608 logging: None,
1609 tags: None,
1610 client_token: "create-img-0011223344556677".to_string(),
1611 };
1612
1613 let value = serde_json::to_value(&wire).expect("serialises");
1614 let object = value.as_object().expect("an object");
1615
1616 // The exact member names, from the model. `minimumMemoryInMiB` is the one
1617 // camelCase alone would misspell.
1618 assert_eq!(value["resources"][0]["minimumMemoryInMiB"], 2048);
1619 assert_eq!(value["baseImageArn"], "arn:base");
1620 assert_eq!(value["buildRoleArn"], "arn:role");
1621 assert_eq!(value["codeArtifact"]["uri"], "s3://bucket/img.zip");
1622 assert_eq!(value["cpuConfigurations"][0]["architecture"], "ARM_64");
1623 assert_eq!(
1624 value["hooks"]["microvmImageHooks"]["readyTimeoutInSeconds"],
1625 300
1626 );
1627 assert_eq!(value["hooks"]["microvmHooks"]["runTimeoutInSeconds"], 30);
1628 assert_eq!(value["additionalOsCapabilities"][0], "ALL");
1629 assert_eq!(value["clientToken"], "create-img-0011223344556677");
1630 assert!(!object.contains_key("tags"), "an absent tag map is omitted");
1631
1632 // **Issue #24's wrong-by-10x hazard is closed by absence on this shape.** The model gives
1633 // `CreateMicrovmImageRequest` an `egressNetworkConnectors` with `max: 1` — a tenth of the
1634 // VM-level list's — and this wire type has no such field, so the client cannot send one at
1635 // all. That is why `MAX_IMAGE_EGRESS_CONNECTORS` guards nothing: there is nothing to guard.
1636 //
1637 // Asserted here, on the serialized object, rather than left as a comment. The hazard is a
1638 // future edit that adds the member and reuses `MAX_NETWORK_CONNECTORS` — permissive by an
1639 // order of magnitude, in a request whose rejection lands after the artifact upload. This
1640 // line is what makes adding the member a visible diff against a test that says the bound is
1641 // 1: whoever adds it has to delete this assertion and will read why while doing it.
1642 assert!(
1643 !object.contains_key("egressNetworkConnectors"),
1644 "the client sends no image-level egress list. If you are adding one, the ceiling is \
1645 MAX_IMAGE_EGRESS_CONNECTORS (1), NOT MAX_NETWORK_CONNECTORS (10) — the two differ by \
1646 10x and the permissive direction is the one that reaches the wire."
1647 );
1648 }
1649
1650 /// `additionalOsCapabilities` is **absent** rather than `[]` when identity repair was
1651 /// not requested. An empty list is a different request, and the model's `CapabilityList`
1652 /// has no documented meaning for one.
1653 #[test]
1654 fn an_unrequested_capability_list_is_omitted_not_empty() {
1655 let mut wire = minimal_create_wire();
1656 wire.additional_os_capabilities = None;
1657 let value = serde_json::to_value(&wire).expect("serialises");
1658 assert!(
1659 !value
1660 .as_object()
1661 .expect("object")
1662 .contains_key("additionalOsCapabilities"),
1663 "omitted, not empty: {value}"
1664 );
1665 }
1666
1667 /// The run request's member names, including the two connector lists and the payload.
1668 #[test]
1669 fn the_run_request_serialises_to_the_models_member_names() {
1670 let wire = RunMicrovmWire {
1671 image_identifier: "arn:image".to_string(),
1672 image_version: None,
1673 execution_role_arn: Some("arn:aws:iam::123456789012:role/exec".to_string()),
1674 ingress_network_connectors: vec!["arn:connector:ALL_INGRESS".to_string()],
1675 egress_network_connectors: None,
1676 idle_policy: IdlePolicy {
1677 max_idle_duration_seconds: 600,
1678 suspended_duration_seconds: 600,
1679 auto_resume_enabled: false,
1680 },
1681 maximum_duration_in_seconds: 3600,
1682 run_hook_payload: r#"{"agent_token":"t"}"#.to_string(),
1683 logging: None,
1684 client_token: "run-arn-0011223344556677".to_string(),
1685 };
1686
1687 let value = serde_json::to_value(&wire).expect("serialises");
1688 assert_eq!(value["imageIdentifier"], "arn:image");
1689 assert_eq!(
1690 value["ingressNetworkConnectors"][0],
1691 "arn:connector:ALL_INGRESS"
1692 );
1693 assert_eq!(value["idlePolicy"]["maxIdleDurationSeconds"], 600);
1694 assert_eq!(value["idlePolicy"]["suspendedDurationSeconds"], 600);
1695 assert_eq!(value["idlePolicy"]["autoResumeEnabled"], false);
1696 assert_eq!(value["maximumDurationInSeconds"], 3600);
1697 assert_eq!(value["runHookPayload"], r#"{"agent_token":"t"}"#);
1698 assert!(
1699 !value
1700 .as_object()
1701 .expect("object")
1702 .contains_key("egressNetworkConnectors"),
1703 "omitting egress must omit the connector list, not send an empty one"
1704 );
1705 }
1706
1707 /// The auth-token request's body. `microvmIdentifier` is a **URI** parameter and must
1708 /// not appear in the body — a serialized copy of it there is a member the shape does
1709 /// not declare.
1710 #[test]
1711 fn the_auth_token_request_body_carries_no_uri_parameter() {
1712 let wire = CreateAuthTokenWire {
1713 expiration_in_minutes: 60,
1714 allowed_ports: vec![PortSpecification::port(9000)],
1715 };
1716 let value = serde_json::to_value(&wire).expect("serialises");
1717 assert_eq!(value["expirationInMinutes"], 60);
1718 assert_eq!(value["allowedPorts"][0]["port"], 9000);
1719 assert!(
1720 !value
1721 .as_object()
1722 .expect("object")
1723 .contains_key("microvmIdentifier"),
1724 "it is a uri-located member: {value}"
1725 );
1726 }
1727
1728 /// **Each union variant serialises as the member name the model declares, with nothing
1729 /// else alongside it.**
1730 ///
1731 /// The wire form of a Smithy union is one key, and serde's default enum representation is
1732 /// `{"One": {"port": 9000}}` — a shape the service rejects as an undeclared member. So
1733 /// `untagged` plus a `rename` per field is not a style choice, and this test is what says
1734 /// so: it asserts the *exact* key set, because a variant that serialised as two keys or as
1735 /// the wrong one would still be valid JSON and would fail only against real AWS.
1736 ///
1737 /// The three variants together are what the port-scope fix rests on. Measured 2026-08-15:
1738 /// a token minted with only `{"port": 9000}` answers 403 `Access to port denied` for a
1739 /// `GET :8080`, and all three of the forms below answer 200.
1740 ///
1741 /// **Guard proof.** Dropping `#[serde(untagged)]` makes every case fail with the variant
1742 /// name as the key (`{"One": ..}`). Renaming `all_ports`'s field to snake_case makes the
1743 /// `allPorts` case fail. Making `AllPorts` a unit struct serialises it as `null` and the
1744 /// object assertion fails. Each applied and observed.
1745 #[test]
1746 fn each_port_specification_variant_serialises_as_its_model_member() {
1747 let cases = [
1748 (
1749 PortSpecification::port(8080),
1750 "port",
1751 serde_json::json!(8080),
1752 ),
1753 (
1754 PortSpecification::range(8000, 9100),
1755 "range",
1756 serde_json::json!({ "startPort": 8000, "endPort": 9100 }),
1757 ),
1758 (PortSpecification::all(), "allPorts", serde_json::json!({})),
1759 ];
1760 for (spec, key, expected) in cases {
1761 let value = serde_json::to_value(spec).expect("serialises");
1762 let object = value.as_object().expect("a union member is an object");
1763 assert_eq!(
1764 object.keys().collect::<Vec<_>>(),
1765 vec![key],
1766 "a union serialises as exactly one member named by the model: {value}"
1767 );
1768 assert_eq!(object[key], expected, "{key} carries the model's shape");
1769 }
1770 }
1771
1772 // ── GetMicrovmImageBuild ─────────────────────────────────────────────────
1773
1774 /// `GetMicrovmImageBuildOutput` from the model's own spelling, `snapshotBuild` included.
1775 ///
1776 /// The literal is a **real response**, copied from a live `GetMicrovmImageBuild` on
1777 /// 2026-08-16 against `coding-agents-on-bedrock` version 1.0 — so the three byte counts
1778 /// and the `chipsetGeneration: "4"` are measurements rather than plausible numbers. That
1779 /// matters for `chipsetGeneration` in particular: it is a `NonBlankString` in the model,
1780 /// so it comes back as `"4"` and not `4`, and a struct typing it `u32` would fail to parse
1781 /// every real response.
1782 ///
1783 /// **Guard proof.** Type `chipset_generation` as `u32` and this fails with "invalid type:
1784 /// string". Drop `snapshot_build` and the size assertions do not compile — which is the
1785 /// point, since those sizes are the only reason this call exists.
1786 #[test]
1787 fn a_build_get_response_carries_the_snapshot_sizes_the_listing_has_no_member_for() {
1788 let json = r#"{
1789 "imageArn": "arn:aws:lambda:us-east-1:392583147479:microvm-image:coding-agents-on-bedrock",
1790 "imageVersion": "1.0",
1791 "buildId": "d39847fa-4c6b-43c6-ba69-e25e3b55197b",
1792 "buildState": "SUCCESSFUL",
1793 "architecture": "ARM_64",
1794 "chipset": "GRAVITON",
1795 "chipsetGeneration": "4",
1796 "createdAt": 1755150457.035,
1797 "snapshotBuild": {
1798 "memorySnapshotSizeInBytes": 582238208,
1799 "codeInstallSizeInBytes": 2355486720,
1800 "diskSnapshotSizeInBytes": 23760896
1801 }
1802 }"#;
1803 let parsed: GetImageBuildResponseWire =
1804 serde_json::from_str(json).expect("the model's own spelling parses");
1805 assert_eq!(parsed.build_state, "SUCCESSFUL");
1806 assert_eq!(parsed.build_id, "d39847fa-4c6b-43c6-ba69-e25e3b55197b");
1807 // A string, because the model types it NonBlankString. A `u32` field here would fail
1808 // on every real response.
1809 assert_eq!(parsed.chipset_generation, "4");
1810 assert_eq!(parsed.state_reason, None);
1811
1812 let sizes = parsed.snapshot_build.expect("a successful build has sizes");
1813 assert_eq!(sizes.memory_snapshot_size_in_bytes, Some(582_238_208));
1814 assert_eq!(sizes.code_install_size_in_bytes, Some(2_355_486_720));
1815 assert_eq!(sizes.disk_snapshot_size_in_bytes, Some(23_760_896));
1816 assert_eq!(
1817 sizes.describe().as_deref(),
1818 Some("memory 582238208 bytes, code 2355486720 bytes, disk 23760896 bytes")
1819 );
1820 }
1821
1822 /// **A failed build's `snapshotBuild` is partial, and the partial shape is the diagnosis.**
1823 ///
1824 /// Measured 2026-08-16 against a real `FAILED` build (`bonk-sandbox-v4`, ready hook timed
1825 /// out): `snapshotBuild` carried `codeInstallSizeInBytes` alone, with no memory and no disk
1826 /// snapshot. That is a build which installed 1.7 GB of code and then never produced a
1827 /// snapshot, which is a different failure from a Dockerfile that broke before installing
1828 /// anything — so the two absent members carry information and a defaulted `0` would erase
1829 /// it.
1830 ///
1831 /// **Guard proof.** Change the three `Option<u64>` fields to bare `u64` and this fails to
1832 /// deserialize on the two missing members. Make `describe` render absent sizes as `0
1833 /// bytes` and the assertion that the line names only `code` goes red.
1834 #[test]
1835 fn a_failed_builds_snapshot_sizes_are_partial_rather_than_zeroed() {
1836 let json = r#"{
1837 "imageArn": "arn:aws:lambda:us-east-1:392583147479:microvm-image:bonk-sandbox-v4",
1838 "imageVersion": "1.0",
1839 "buildId": "4a4c5e30-811f-47fa-9893-260ea6a37a8f",
1840 "buildState": "FAILED",
1841 "architecture": "ARM_64",
1842 "chipset": "GRAVITON",
1843 "chipsetGeneration": "4",
1844 "stateReason": "Ready hook invocation timed out after PT5M",
1845 "createdAt": 1751042593.476,
1846 "snapshotBuild": {"codeInstallSizeInBytes": 1724940288}
1847 }"#;
1848 let parsed: GetImageBuildResponseWire = serde_json::from_str(json).expect("parses");
1849 let sizes = parsed
1850 .snapshot_build
1851 .expect("the service sent a partial breakdown");
1852 assert_eq!(sizes.code_install_size_in_bytes, Some(1_724_940_288));
1853 assert_eq!(
1854 sizes.memory_snapshot_size_in_bytes, None,
1855 "no memory snapshot was produced, which is the finding — not a size of zero"
1856 );
1857 assert_eq!(sizes.disk_snapshot_size_in_bytes, None);
1858
1859 let described = parsed.describe();
1860 assert!(
1861 described.contains("Ready hook invocation timed out"),
1862 "{described}"
1863 );
1864 assert!(
1865 described.contains("chipset generation 4"),
1866 "one CreateMicrovmImage fans out per generation, so the line has to name which: \
1867 {described}"
1868 );
1869 assert!(described.contains("code 1724940288 bytes"), "{described}");
1870 assert!(
1871 !described.contains("memory"),
1872 "an absent size must not render at all: {described}"
1873 );
1874 }
1875
1876 /// A build the service reports with **no** `snapshotBuild` at all renders no sizes and no
1877 /// dangling comma.
1878 ///
1879 /// The model marks the member optional, and a `PENDING` build has nothing to report — so
1880 /// `None` has to render as absence rather than as an empty clause.
1881 #[test]
1882 fn a_build_with_no_snapshot_block_renders_no_size_clause() {
1883 let json = r#"{
1884 "imageArn": "arn:aws:lambda:us-east-1:1:microvm-image:img",
1885 "imageVersion": "1",
1886 "buildId": "build-abc",
1887 "buildState": "PENDING",
1888 "architecture": "ARM_64",
1889 "chipset": "GRAVITON",
1890 "chipsetGeneration": "3",
1891 "createdAt": 1754524800
1892 }"#;
1893 let parsed: GetImageBuildResponseWire = serde_json::from_str(json).expect("parses");
1894 assert_eq!(parsed.snapshot_build, None);
1895 assert_eq!(
1896 parsed.describe(),
1897 "build-abc PENDING (chipset generation 3)"
1898 );
1899 assert!(!parsed.describe().ends_with(", "), "{}", parsed.describe());
1900
1901 // And an *empty* snapshot block is `Some` with three `None`s, which is different from
1902 // an absent one: the service answered and reported nothing.
1903 let empty: GetImageBuildResponseWire = serde_json::from_str(
1904 r#"{"imageArn": "a", "imageVersion": "1", "buildId": "b", "buildState": "PENDING",
1905 "architecture": "ARM_64", "chipset": "GRAVITON", "chipsetGeneration": "3",
1906 "createdAt": 1754524800, "snapshotBuild": {}}"#,
1907 )
1908 .expect("an empty block parses");
1909 assert_eq!(empty.snapshot_build.expect("Some").describe(), None);
1910 assert!(!empty.describe().contains("bytes"), "{}", empty.describe());
1911 }
1912
1913 /// The build get response requires the same eight members the summary does.
1914 ///
1915 /// One case per member, for the reason the summary's own test gives: a single omission
1916 /// would prove only that *some* member is required.
1917 #[test]
1918 fn a_build_get_response_missing_a_required_member_fails_to_deserialise() {
1919 let members = [
1920 (
1921 "imageArn",
1922 r#""arn:aws:lambda:us-east-1:1:microvm-image:i""#,
1923 ),
1924 ("imageVersion", r#""1""#),
1925 ("buildId", r#""build-abc""#),
1926 ("buildState", r#""SUCCESSFUL""#),
1927 ("architecture", r#""ARM_64""#),
1928 ("chipset", r#""GRAVITON""#),
1929 ("chipsetGeneration", r#""4""#),
1930 ("createdAt", "1754524800"),
1931 ];
1932 for omitted in members.iter().map(|(name, _)| *name) {
1933 let body: Vec<String> = members
1934 .iter()
1935 .filter(|(name, _)| *name != omitted)
1936 .map(|(name, value)| format!(r#""{name}": {value}"#))
1937 .collect();
1938 let error = serde_json::from_str::<GetImageBuildResponseWire>(&format!(
1939 "{{{}}}",
1940 body.join(", ")
1941 ))
1942 .expect_err(&format!("{omitted} is required by the model"));
1943 assert!(error.to_string().contains(omitted), "{omitted}: {error}");
1944 }
1945 }
1946
1947 // ── GetMicrovmImageVersion / UpdateMicrovmImageVersion ───────────────────
1948
1949 /// **One struct for three shapes.** A real `GetMicrovmImageVersion` response parses as
1950 /// `MicrovmImageVersionSummaryWire`, config readback and all.
1951 ///
1952 /// The literal is a real response, copied from a live call on 2026-08-16 against
1953 /// `coding-agents-on-bedrock` version 1.0 — including the detail that
1954 /// `baseImageVersion` reads `"1.0"` while the managed base's own listing offers `"0"` and
1955 /// `"1"`. The two spellings are not comparable and this test records that they are not.
1956 ///
1957 /// `hooks` is present in the JSON and **not** read, deliberately: see the type's docs and
1958 /// the sibling test below.
1959 ///
1960 /// **Guard proof.** Make `status` an `Option<String>` and the `is_active` assertion still
1961 /// passes, which is why the *requiredness* test below exists instead. Remove `resources`
1962 /// and the size-class assertion does not compile.
1963 #[test]
1964 fn a_get_image_version_response_parses_as_the_summary_with_its_whole_config() {
1965 let json = r#"{
1966 "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
1967 "baseImageVersion": "1.0",
1968 "buildRoleArn": "arn:aws:iam::392583147479:role/agentd-conformance-build-b2111c56",
1969 "codeArtifact": {"uri": "s3://agentd-conformance-392583147479-b2111c56/coding-agents-on-bedrock.zip"},
1970 "egressNetworkConnectors": [
1971 "arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS"
1972 ],
1973 "cpuConfigurations": [{"architecture": "ARM_64"}],
1974 "resources": [{"minimumMemoryInMiB": 2048}],
1975 "hooks": {
1976 "port": 9000,
1977 "microvmHooks": {
1978 "run": "ENABLED", "runTimeoutInSeconds": 30,
1979 "resume": "ENABLED", "resumeTimeoutInSeconds": 30,
1980 "suspend": "ENABLED", "suspendTimeoutInSeconds": 30,
1981 "terminate": "ENABLED", "terminateTimeoutInSeconds": 30
1982 },
1983 "microvmImageHooks": {
1984 "ready": "ENABLED", "readyTimeoutInSeconds": 30,
1985 "validate": "ENABLED", "validateTimeoutInSeconds": 30
1986 }
1987 },
1988 "imageArn": "arn:aws:lambda:us-east-1:392583147479:microvm-image:coding-agents-on-bedrock",
1989 "imageVersion": "1.0",
1990 "state": "SUCCESSFUL",
1991 "status": "ACTIVE",
1992 "createdAt": 1755150457.035,
1993 "updatedAt": 1755150629.117
1994 }"#;
1995 let parsed: MicrovmImageVersionSummaryWire =
1996 serde_json::from_str(json).expect("a real GetMicrovmImageVersion response parses");
1997
1998 assert_eq!(parsed.image_version, "1.0");
1999 assert_eq!(parsed.state, "SUCCESSFUL");
2000 assert_eq!(parsed.status, "ACTIVE");
2001 assert!(parsed.is_active());
2002 assert_eq!(
2003 parsed.base_image_arn,
2004 "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"
2005 );
2006 // The spelling that is not comparable with the base's own listing: `"1.0"` here,
2007 // against `"0"` and `"1"` from ListManagedMicrovmImageVersions.
2008 assert_eq!(parsed.base_image_version.as_deref(), Some("1.0"));
2009 assert!(
2010 parsed
2011 .code_artifact
2012 .uri
2013 .ends_with("coding-agents-on-bedrock.zip")
2014 );
2015
2016 // `resources` is the only place a built image's size class is observable — GetMicrovm
2017 // reports no memory figure at all.
2018 let resources = parsed
2019 .resources
2020 .as_ref()
2021 .expect("the readback carries the resources");
2022 assert_eq!(resources.len(), 1);
2023 assert_eq!(resources[0].minimum_memory_in_mib, 2048);
2024
2025 // The image-level egress list, whose ceiling is 1 and not the VM-level 10.
2026 let egress = parsed
2027 .egress_network_connectors
2028 .as_ref()
2029 .expect("one connector");
2030 assert_eq!(egress.len(), 1);
2031 assert!(egress.len() <= crate::constants::MAX_IMAGE_EGRESS_CONNECTORS);
2032 assert!(
2033 egress.len() < crate::constants::MAX_NETWORK_CONNECTORS,
2034 "the two ceilings are different numbers; see the constants test that holds the \
2035 inequality"
2036 );
2037
2038 assert_eq!(parsed.state_reason, None, "a successful version has none");
2039 assert_eq!(parsed.updated_at, Some(1_755_150_629.117));
2040 assert_eq!(parsed.describe(), "1.0 SUCCESSFUL / ACTIVE");
2041 }
2042
2043 /// The version summary requires all eight members the model marks required, `status`
2044 /// included.
2045 ///
2046 /// `status` is the one worth the test. It was `Option<String>` while the model requires it,
2047 /// so a service that stopped sending it would have read as `None` — and a version blocked
2048 /// from launching would have looked identical to one nobody had ever set. Confirmed present
2049 /// on all 22 versions in the conformance account (2026-08-16).
2050 ///
2051 /// **Guard proof.** Restore `pub status: Option<String>` and the `status` case here passes
2052 /// where it should fail; `is_active` then cannot be written at all without a default, which
2053 /// is the second half of why the field is bare.
2054 #[test]
2055 fn a_version_summary_missing_a_required_member_fails_to_deserialise() {
2056 let members = [
2057 (
2058 "baseImageArn",
2059 r#""arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1""#,
2060 ),
2061 ("buildRoleArn", r#""arn:aws:iam::1:role/build""#),
2062 ("codeArtifact", r#"{"uri": "s3://b/k"}"#),
2063 (
2064 "imageArn",
2065 r#""arn:aws:lambda:us-east-1:1:microvm-image:i""#,
2066 ),
2067 ("imageVersion", r#""1.0""#),
2068 ("state", r#""SUCCESSFUL""#),
2069 ("status", r#""ACTIVE""#),
2070 ("createdAt", "1754524800"),
2071 ];
2072 for omitted in members.iter().map(|(name, _)| *name) {
2073 let body: Vec<String> = members
2074 .iter()
2075 .filter(|(name, _)| *name != omitted)
2076 .map(|(name, value)| format!(r#""{name}": {value}"#))
2077 .collect();
2078 let error = serde_json::from_str::<MicrovmImageVersionSummaryWire>(&format!(
2079 "{{{}}}",
2080 body.join(", ")
2081 ))
2082 .expect_err(&format!("{omitted} is required by the model"));
2083 assert!(error.to_string().contains(omitted), "{omitted}: {error}");
2084 }
2085 }
2086
2087 /// **`hooks` is not read, and a real response is why.**
2088 ///
2089 /// The model marks every member of `MicrovmHooks` optional, and a real
2090 /// `GetMicrovmImageVersion` on an image built by another tool answered
2091 /// `"microvmHooks": {"run": "ENABLED", "runTimeoutInSeconds": 30}` and nothing else —
2092 /// measured 2026-08-16 against `omnigent-host-vpc` version 3.0, five of eight members
2093 /// absent. This module's request-side [`Hooks`] declares all of them as bare fields, which
2094 /// is correct for a request this client always fills, so reusing it on the response would
2095 /// fail that parse and turn a readable version into a client error.
2096 ///
2097 /// So this test is the record of a deliberate omission: the sparse block parses fine
2098 /// *because* nothing reads it, and reusing `Hooks` here is the change that breaks it.
2099 ///
2100 /// **Guard proof.** Add `pub hooks: Option<Hooks>` to the summary and this test fails with
2101 /// "missing field `resume`".
2102 #[test]
2103 fn a_versions_hooks_block_is_not_read_because_a_real_one_omits_members() {
2104 let json = r#"{
2105 "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
2106 "baseImageVersion": "0.0",
2107 "buildRoleArn": "arn:aws:iam::392583147479:role/bonk-sandbox-microvm-build",
2108 "codeArtifact": {"uri": "s3://bucket/omnigent-host-overlay.zip"},
2109 "resources": [{"minimumMemoryInMiB": 2048}],
2110 "hooks": {
2111 "port": 9000,
2112 "microvmHooks": {"run": "ENABLED", "runTimeoutInSeconds": 30},
2113 "microvmImageHooks": {"ready": "ENABLED", "readyTimeoutInSeconds": 120}
2114 },
2115 "imageArn": "arn:aws:lambda:us-east-1:392583147479:microvm-image:omnigent-host-vpc",
2116 "imageVersion": "3.0",
2117 "state": "SUCCESSFUL",
2118 "status": "ACTIVE",
2119 "createdAt": 1752205430.83
2120 }"#;
2121 let parsed: MicrovmImageVersionSummaryWire = serde_json::from_str(json)
2122 .expect("a sparse hooks block parses precisely because nothing reads it");
2123 assert_eq!(parsed.image_version, "3.0");
2124
2125 // And the request-side type really would refuse that block, which is the fact this
2126 // test exists to hold: the two directions need two shapes.
2127 let refused = serde_json::from_str::<Hooks>(
2128 r#"{"port": 9000,
2129 "microvmHooks": {"run": "ENABLED", "runTimeoutInSeconds": 30},
2130 "microvmImageHooks": {"ready": "ENABLED", "readyTimeoutInSeconds": 120}}"#,
2131 )
2132 .expect_err("the request-side Hooks declares all six enabled flags as required");
2133 assert!(refused.to_string().contains("resume"), "{refused}");
2134 }
2135
2136 /// An `INACTIVE` version reads back as not launchable, and `describe` says so.
2137 ///
2138 /// The pair with the `ACTIVE` case above, so `is_active` is a comparison rather than a
2139 /// function that returns true.
2140 ///
2141 /// **Guard proof.** Invert `is_active` and this fails; compare against a bare `"Active"`
2142 /// literal instead of `VersionStatus::Active.as_str()` and it fails too.
2143 #[test]
2144 fn an_inactive_version_reads_back_as_not_launchable() {
2145 let json = r#"{
2146 "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
2147 "buildRoleArn": "arn:aws:iam::1:role/build",
2148 "codeArtifact": {"uri": "s3://b/k"},
2149 "imageArn": "arn:aws:lambda:us-east-1:1:microvm-image:img",
2150 "imageVersion": "2.0",
2151 "state": "SUCCESSFUL",
2152 "status": "INACTIVE",
2153 "createdAt": 1754524800,
2154 "updatedAt": 1754528400
2155 }"#;
2156 let parsed: MicrovmImageVersionSummaryWire = serde_json::from_str(json).expect("parses");
2157 assert!(
2158 !parsed.is_active(),
2159 "INACTIVE is the version RunMicrovm refuses to launch"
2160 );
2161 assert_eq!(parsed.describe(), "2.0 SUCCESSFUL / INACTIVE");
2162 assert_eq!(
2163 parsed.state, "SUCCESSFUL",
2164 "the state and the status are different questions: a SUCCESSFUL build can be \
2165 retired, which is the whole point of the status member"
2166 );
2167 }
2168
2169 /// The version summary's `describe` carries a reason when there is one, and nothing when
2170 /// there is not.
2171 #[test]
2172 fn a_version_describes_itself_with_only_a_reason_it_has() {
2173 let json = r#"{
2174 "baseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
2175 "buildRoleArn": "arn:aws:iam::1:role/build",
2176 "codeArtifact": {"uri": "s3://b/k"},
2177 "imageArn": "arn:aws:lambda:us-east-1:1:microvm-image:img",
2178 "imageVersion": "2.0",
2179 "state": "FAILED",
2180 "status": "INACTIVE",
2181 "createdAt": 1754524800,
2182 "stateReason": "one or more builds failed"
2183 }"#;
2184 let parsed: MicrovmImageVersionSummaryWire = serde_json::from_str(json).expect("parses");
2185 assert_eq!(
2186 parsed.describe(),
2187 "2.0 FAILED / INACTIVE (one or more builds failed)"
2188 );
2189 assert!(!parsed.describe().contains("()"), "{}", parsed.describe());
2190 }
2191
2192 /// The update request serialises to **one** member, `status`, spelled as the model spells
2193 /// it — and both enum values are asserted.
2194 ///
2195 /// The key set is asserted exactly, because `imageIdentifier` and `imageVersion` are URI
2196 /// parameters and a serialized copy of either in the body is a member the shape does not
2197 /// declare.
2198 ///
2199 /// **Guard proof.** Drop the `#[serde(rename = "ACTIVE")]` attributes and the values
2200 /// serialise as `"Active"`/`"Inactive"`, which the service refuses as an enum violation —
2201 /// both assertions go red.
2202 #[test]
2203 fn the_update_version_request_is_one_member_spelled_as_the_model_spells_it() {
2204 for (status, expected) in [
2205 (VersionStatus::Active, "ACTIVE"),
2206 (VersionStatus::Inactive, "INACTIVE"),
2207 ] {
2208 let value =
2209 serde_json::to_value(UpdateImageVersionWire { status }).expect("serialises");
2210 let object = value.as_object().expect("an object");
2211 assert_eq!(
2212 object.keys().collect::<Vec<_>>(),
2213 vec!["status"],
2214 "imageIdentifier and imageVersion are uri-located: {value}"
2215 );
2216 assert_eq!(object["status"], expected);
2217 assert_eq!(status.as_str(), expected);
2218 assert_eq!(status.to_string(), expected);
2219 }
2220 }
2221
2222 /// The typed request spelling and the drift gate's published array are the same two
2223 /// values.
2224 ///
2225 /// The coupling worth pinning: `constants::IMAGE_VERSION_STATUSES` is what the gate holds
2226 /// against the model's shape, and [`VersionStatus`] is what a call site can construct. If
2227 /// they disagree the gate passes while the client sends a value the model does not declare.
2228 #[test]
2229 fn the_typed_statuses_are_exactly_the_published_ones() {
2230 let typed: Vec<&str> = [VersionStatus::Active, VersionStatus::Inactive]
2231 .iter()
2232 .map(|status| status.as_str())
2233 .collect();
2234 assert_eq!(typed, crate::constants::IMAGE_VERSION_STATUSES);
2235 }
2236
2237 /// A status given as text parses from the model's spelling alone (#264): the bindings and
2238 /// the CLI take it as a string, and a near miss is refused before the call, naming both
2239 /// legal values.
2240 #[test]
2241 fn a_status_parses_from_the_models_spelling_only() {
2242 for status in [VersionStatus::Active, VersionStatus::Inactive] {
2243 assert_eq!(status.as_str().parse::<VersionStatus>().ok(), Some(status));
2244 }
2245 for text in ["INACTIVATE", "inactive", "Active", " ACTIVE", ""] {
2246 let error = text.parse::<VersionStatus>().expect_err(text);
2247 assert_eq!(
2248 error.kind(),
2249 crate::error::ErrorKind::InvalidArg,
2250 "{text:?}"
2251 );
2252 assert!(
2253 error.to_string().contains("ACTIVE or INACTIVE"),
2254 "{text:?}: {error}"
2255 );
2256 }
2257 }
2258
2259 // ── the managed listings ─────────────────────────────────────────────────
2260
2261 /// `ListManagedMicrovmImageVersionsOutput` from a **real** response.
2262 ///
2263 /// Copied from a live call on 2026-08-16: `al2023-1` answers two versions, `"1"` and
2264 /// `"0"`, newest first. The bare-integer spelling is the finding — a custom image's
2265 /// versions are `"1.0"` — and it is why a version string cannot be parsed by one rule.
2266 #[test]
2267 fn a_managed_version_listing_carries_bare_integer_versions_newest_first() {
2268 let json = r#"{
2269 "items": [
2270 {
2271 "imageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
2272 "imageVersion": "1",
2273 "createdAt": 1753119464.231,
2274 "updatedAt": 1753119644.78
2275 },
2276 {
2277 "imageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
2278 "imageVersion": "0",
2279 "createdAt": 1750180266.531,
2280 "updatedAt": 1750180537.679
2281 }
2282 ]
2283 }"#;
2284 let parsed: ListManagedVersionsResponseWire =
2285 serde_json::from_str(json).expect("the model's own spelling parses");
2286 assert_eq!(parsed.items.len(), 2);
2287 assert_eq!(parsed.items[0].image_version, "1");
2288 assert_eq!(parsed.items[1].image_version, "0");
2289 assert_eq!(parsed.next_token, None, "one page, so the loop stops");
2290 assert_eq!(
2291 parsed.items[0].image_arn,
2292 "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"
2293 );
2294 assert_eq!(parsed.items[0].updated_at, Some(1_753_119_644.78));
2295
2296 // Bare integers, not the `major.minor` a custom image uses. A client that parsed one
2297 // format would not parse the other, and neither can be compared with the `"1.0"` that
2298 // GetMicrovmImageVersion echoes as `baseImageVersion`.
2299 for item in &parsed.items {
2300 assert!(
2301 !item.image_version.contains('.'),
2302 "a managed base's versions are bare integers: {}",
2303 item.image_version
2304 );
2305 }
2306 }
2307
2308 /// `ManagedMicrovmImageSummary` is an ARN and two timestamps, and **that is all**.
2309 ///
2310 /// Asserted as an absence, which is the reason this shape cannot construct a
2311 /// [`crate::control::BaseImage`]: no registry reference for `require_matching_from` to
2312 /// compare a Dockerfile against, and no working directory for `require_workdir` to check.
2313 /// The absence is checked by deserializing a response that *does* carry extra members and
2314 /// showing there is no field to read them into — the same technique
2315 /// `a_version_summary_carries_the_state_reason_get_image_cannot` uses.
2316 #[test]
2317 fn a_managed_image_summary_carries_no_registry_ref_so_it_cannot_build_a_base_image() {
2318 let json = r#"{
2319 "items": [{
2320 "imageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
2321 "createdAt": 1750180266.531,
2322 "updatedAt": 1753119644.78
2323 }]
2324 }"#;
2325 let parsed: ListManagedImagesResponseWire =
2326 serde_json::from_str(json).expect("the model's own spelling parses");
2327 assert_eq!(parsed.items.len(), 1, "measured 2026-08-16: exactly one");
2328 assert_eq!(
2329 parsed.items[0].image_arn,
2330 "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"
2331 );
2332
2333 // The whole struct, as JSON, is three keys. There is nothing here a BaseImage's
2334 // `docker_ref` or `working_dir` could come from, and the ARN does not imply either:
2335 // `al2023-1` pairs with public.ecr.aws/amazonlinux/amazonlinux:2023-minimal, and
2336 // nothing in the ARN says so.
2337 let base = crate::control::BaseImage::al2023();
2338 assert_eq!(
2339 base.docker_ref, "public.ecr.aws/amazonlinux/amazonlinux:2023-minimal",
2340 "the pairing a discovered base cannot supply"
2341 );
2342 assert!(
2343 !parsed.items[0].image_arn.contains(&base.docker_ref),
2344 "the ARN does not carry the registry ref, so discovery cannot derive it"
2345 );
2346
2347 // A required member missing still fails, so the three that *are* there are load-bearing.
2348 let error = serde_json::from_str::<ManagedMicrovmImageSummaryWire>(
2349 r#"{"createdAt": 1750180266.531}"#,
2350 )
2351 .expect_err("imageArn is required");
2352 assert!(error.to_string().contains("imageArn"), "{error}");
2353 }
2354
2355 // ── the two unsent request members ───────────────────────────────────────
2356
2357 /// `CreateMicrovmImage.baseImageVersion` reaches the wire when pinned and is **absent**
2358 /// when it is not.
2359 ///
2360 /// Absent rather than null or empty, because an absent member means "whatever the service
2361 /// defaults to" while a blank one is a `ValidationException` on the `Version` shape's
2362 /// `min: 1`. The two are different requests and only one of them is legal.
2363 ///
2364 /// **Guard proof.** Remove `skip_serializing_if` and the absence assertion fails with a
2365 /// `"baseImageVersion": null` on every unpinned build — which the service rejects.
2366 #[test]
2367 fn a_pinned_base_image_version_reaches_the_wire_and_an_unpinned_one_is_omitted() {
2368 let mut wire = minimal_create_wire();
2369 wire.base_image_version = Some("1".to_string());
2370 let value = serde_json::to_value(&wire).expect("serialises");
2371 assert_eq!(value["baseImageVersion"], "1");
2372
2373 let mut unpinned = minimal_create_wire();
2374 unpinned.base_image_version = None;
2375 let value = serde_json::to_value(&unpinned).expect("serialises");
2376 assert!(
2377 !value
2378 .as_object()
2379 .expect("object")
2380 .contains_key("baseImageVersion"),
2381 "omitted, not null: an absent member takes the service default, and a blank one \
2382 is a ValidationException: {value}"
2383 );
2384 }
2385
2386 /// `RunMicrovm.imageVersion` reaches the wire when pinned and is **absent** when it is not.
2387 ///
2388 /// The absence is what this client always sent, so the field existing must not change an
2389 /// unpinned launch by a byte — a `"imageVersion": null` on every launch would be a new
2390 /// member on a request that has worked for months.
2391 ///
2392 /// **Guard proof.** Remove `skip_serializing_if` and the absence assertion fails.
2393 #[test]
2394 fn a_pinned_launch_version_reaches_the_wire_and_an_unpinned_one_is_omitted() {
2395 let mut wire = minimal_run_wire();
2396 wire.image_version = Some("2.0".to_string());
2397 let value = serde_json::to_value(&wire).expect("serialises");
2398 assert_eq!(value["imageVersion"], "2.0");
2399 assert_eq!(
2400 value["imageIdentifier"], "arn:image",
2401 "the version does not replace the identifier; both are sent"
2402 );
2403
2404 let value = serde_json::to_value(minimal_run_wire()).expect("serialises");
2405 assert!(
2406 !value
2407 .as_object()
2408 .expect("object")
2409 .contains_key("imageVersion"),
2410 "an unpinned launch must emit byte-for-byte what this client always sent: {value}"
2411 );
2412 }
2413
2414 fn minimal_run_wire() -> RunMicrovmWire {
2415 RunMicrovmWire {
2416 image_identifier: "arn:image".to_string(),
2417 image_version: None,
2418 execution_role_arn: None,
2419 ingress_network_connectors: Vec::new(),
2420 egress_network_connectors: None,
2421 idle_policy: IdlePolicy {
2422 max_idle_duration_seconds: 600,
2423 suspended_duration_seconds: 600,
2424 auto_resume_enabled: false,
2425 },
2426 maximum_duration_in_seconds: 3_600,
2427 run_hook_payload: String::new(),
2428 logging: None,
2429 client_token: "run-arn-0011223344556677".to_string(),
2430 }
2431 }
2432
2433 fn minimal_create_wire() -> CreateMicrovmImageWire {
2434 CreateMicrovmImageWire {
2435 name: "img".to_string(),
2436 base_image_arn: "arn:base".to_string(),
2437 base_image_version: None,
2438 build_role_arn: "arn:role".to_string(),
2439 code_artifact: CodeArtifact {
2440 uri: "s3://b/k".to_string(),
2441 },
2442 cpu_configurations: vec![CpuConfiguration {
2443 architecture: "ARM_64".to_string(),
2444 }],
2445 resources: vec![Resources {
2446 minimum_memory_in_mib: 2048,
2447 }],
2448 hooks: Hooks {
2449 port: 9000,
2450 microvm_hooks: MicrovmHooks {
2451 run: HookState::Enabled,
2452 run_timeout_in_seconds: 30,
2453 resume: HookState::Enabled,
2454 resume_timeout_in_seconds: 30,
2455 suspend: HookState::Enabled,
2456 suspend_timeout_in_seconds: 30,
2457 terminate: HookState::Enabled,
2458 terminate_timeout_in_seconds: 30,
2459 },
2460 microvm_image_hooks: MicrovmImageHooks {
2461 ready: HookState::Enabled,
2462 ready_timeout_in_seconds: 300,
2463 validate: HookState::Enabled,
2464 validate_timeout_in_seconds: 300,
2465 },
2466 },
2467 additional_os_capabilities: None,
2468 logging: None,
2469 tags: None,
2470 client_token: "create-img-0011223344556677".to_string(),
2471 }
2472 }
2473
2474 // ── the logging union ─────────────────────────────────────────────────────
2475
2476 /// **Each `Logging` variant serialises as the member name the model declares, with
2477 /// nothing else alongside it** — the same claim
2478 /// [`each_port_specification_variant_serialises_as_its_model_member`] holds for the
2479 /// other union this client sends.
2480 ///
2481 /// **Guard proof.** Dropping `#[serde(untagged)]` makes both cases fail with the
2482 /// variant name as the key (`{"Disabled": ..}`); making `LoggingDisabled` a unit
2483 /// struct serialises it as `null` and the object assertion fails. Both applied and
2484 /// observed.
2485 #[test]
2486 fn each_logging_variant_serialises_as_its_model_member() {
2487 let cases = [
2488 (Logging::disabled(), "disabled", serde_json::json!({})),
2489 (
2490 Logging::cloud_watch("/aws/lambda-microvms/builds", None),
2491 "cloudWatch",
2492 serde_json::json!({"logGroup": "/aws/lambda-microvms/builds"}),
2493 ),
2494 (
2495 Logging::cloud_watch(
2496 "/aws/lambda-microvms/builds",
2497 Some("img/deadbeef00010203".to_string()),
2498 ),
2499 "cloudWatch",
2500 serde_json::json!({
2501 "logGroup": "/aws/lambda-microvms/builds",
2502 "logStream": "img/deadbeef00010203"
2503 }),
2504 ),
2505 ];
2506 for (logging, key, expected) in cases {
2507 let value = serde_json::to_value(&logging).expect("serialises");
2508 let object = value.as_object().expect("a union member is an object");
2509 assert_eq!(
2510 object.keys().collect::<Vec<_>>(),
2511 vec![key],
2512 "a union serialises as exactly one member named by the model: {value}"
2513 );
2514 assert_eq!(object[key], expected, "{key} carries the model's shape");
2515 }
2516 }
2517
2518 /// A configured `logging` reaches the wire under the model's member name, and an
2519 /// unconfigured one is **absent** — not `null`, not `{}`.
2520 ///
2521 /// The absence half is the compatibility claim: a create with no logging config must
2522 /// emit byte-for-byte the request this client always sent, because an absent member
2523 /// takes the service default and a `"logging": null` is a new member on a request
2524 /// that has worked for months.
2525 ///
2526 /// **Guard proof.** Remove `skip_serializing_if` from `logging` and the absence
2527 /// assertion fails with `"logging": null` on every unconfigured create.
2528 #[test]
2529 fn a_configured_logging_reaches_the_wire_and_an_unconfigured_one_is_omitted() {
2530 let mut wire = minimal_create_wire();
2531 wire.logging = Some(Logging::cloud_watch(
2532 "/aws/lambda-microvms/builds",
2533 Some("img/deadbeef00010203".to_string()),
2534 ));
2535 let value = serde_json::to_value(&wire).expect("serialises");
2536 assert_eq!(
2537 value["logging"]["cloudWatch"]["logGroup"],
2538 "/aws/lambda-microvms/builds"
2539 );
2540 assert_eq!(
2541 value["logging"]["cloudWatch"]["logStream"],
2542 "img/deadbeef00010203"
2543 );
2544
2545 let value = serde_json::to_value(minimal_create_wire()).expect("serialises");
2546 assert!(
2547 !value.as_object().expect("object").contains_key("logging"),
2548 "omitted, not null: an absent member takes the service default: {value}"
2549 );
2550 }
2551
2552 /// A group with no stream serialises without a `logStream` key at all: the member is
2553 /// optional in the model, and an absent stream means "the service names the streams"
2554 /// while an empty one is a `ValidationException` on the shape's `min: 1`.
2555 #[test]
2556 fn a_group_only_logging_config_omits_the_stream_member() {
2557 let value = serde_json::to_value(Logging::cloud_watch("/aws/lambda-microvms/b", None))
2558 .expect("serialises");
2559 let cloud_watch = value["cloudWatch"].as_object().expect("an object");
2560 assert_eq!(
2561 cloud_watch.keys().collect::<Vec<_>>(),
2562 vec!["logGroup"],
2563 "an absent stream is omitted, not empty: {value}"
2564 );
2565 }
2566}