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