Skip to main content

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