Skip to main content

microvms_domain/
constants.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Every hardcoded service constraint, and the JSON the build gate checks them with.
3//!
4//! Each number and pattern below is transcribed from the botocore service model for
5//! `lambda-microvms`, API version [`MODEL_API_VERSION`]. The model is a
6//! machine-readable statement of the service's own request validation, and restating
7//! it by hand is how this project published a 16 KB `runHookPayload` ceiling against
8//! a real ceiling of 4096 — wrong by 4x in the dangerous direction, since it told a
9//! caller four times as much secret material fits as actually does.
10//!
11//! # Why they are checked locally at all
12//!
13//! Because the SDK does not check them. Measured 2026-08-07 by reading botocore's
14//! `validate.py`: `VALIDATED_METADATA_ATTRS` is `{'required', 'min', 'document',
15//! 'union'}`, so a `min` violation is caught before the wire while `max`, `pattern`,
16//! and `enum` violations are serialized, sent, and answered with a
17//! `ValidationException` — confirmed empirically for `max` (runHookPayload 4097,
18//! maximumDurationInSeconds 28801, ImageName 65 chars, NetworkConnectorList 11 items,
19//! clientToken 129 chars), for `pattern` (ImageName `"a b!"`), and for `enum`
20//! (architecture X86_64, additionalOsCapabilities CAP_SYS_ADMIN). Every one reached
21//! the wire. So the guards built on these values are load-bearing rather than
22//! belt-and-braces, and the obvious future simplification — "the SDK validates the
23//! model already, delete these" — silently reopens all of them.
24//!
25//! `IdlePolicy.maxIdleDurationSeconds` used to be listed here as the counter-example — the
26//! one constraint with no constant, on the grounds that its `min: 60` is a `min` and
27//! botocore enforces those locally. **That reasoning does not transfer to this client and
28//! the exemption is gone** ([`MIN_IDLE_DURATION_SEC`]). It was true of the deleted Python
29//! client, which called through botocore; this one signs with `aws-sigv4` and sends with
30//! `reqwest`, and `validate.py` is never on the path. Every constraint here is enforced by
31//! this crate or by nothing, `min` included.
32//!
33//! # The drift gate (TRAP-12)
34//!
35//! [`as_json`] emits every value in this module as one object. The names are the
36//! keys consumed by `tools/check-model-drift.py`, which compares each value with
37//! the pinned model. `MICROVM_REGIONS` and `SIZE_CLASSES` have no model source;
38//! the gate compares them with independently pinned literals.
39//!
40//! The names are therefore a contract with a script, not a style choice. Renaming
41//! `MAX_RUN_HOOK_PAYLOAD_BYTES` here without renaming it there does not fail
42//! compilation; it makes a check silently stop comparing. The test at the bottom of
43//! this file pins the key set for that reason.
44
45use serde_json::{Value, json};
46
47use crate::region::MICROVM_REGIONS;
48
49/// The model version every constraint here was read from.
50///
51/// The drift gate hard-fails when this disagrees with the service directory it
52/// resolves, rather than skipping: a constraint checked against a different API
53/// version is a constraint that was not checked.
54pub const MODEL_API_VERSION: &str = "2025-09-09";
55
56/// `RunMicrovmRequestRunHookPayloadString.max`.
57///
58/// **Inclusive**: 4096 bytes passes the length check and 4097 is rejected, bracketed
59/// 2026-08-07 by calling `RunMicrovm` with a deliberately bogus `imageIdentifier` so
60/// nothing could be created or billed. This is the only per-VM secret channel the
61/// platform offers — one bearer token fits, a cloud credential set does not.
62///
63/// # The model itself says 16,384, and it is wrong
64///
65/// Not only this repo's prose. `service-2.json`'s **documentation string** on
66/// `RunMicrovmRequest.runHookPayload` reads, verbatim for API version 2025-09-09:
67///
68/// > Per-MicroVM initialization data delivered as the request body of the /run lifecycle
69/// > hook. Use to pass tenant-specific configuration such as session IDs or secret
70/// > references. Maximum: 16,384 bytes.
71///
72/// while the shape that member names — `RunMicrovmRequestRunHookPayloadString` — declares
73/// `{"max": 4096, "min": 0}`. The shape is what the service validates against, and 4096 was
74/// measured inclusive against the real service. **So a reader who "corrects" this constant
75/// from the model's prose reintroduces the bug**, and they will be able to cite the model
76/// while doing it: that 16 KB figure is where this project's own 16 KB claim came from, and
77/// it survived several review passes because prose has nothing to disagree with. Issue #24
78/// named this trap specifically. The drift gate compares against the *shape*, which is why it
79/// stays green while the prose beside it says something else.
80pub const MAX_RUN_HOOK_PAYLOAD_BYTES: usize = 4096;
81
82/// The figure the model's own `runHookPayload` documentation string claims, which is **not**
83/// the ceiling.
84///
85/// Pinned as a constant so the wrong number has a name and a comparison rather than only a
86/// mention. [`MAX_RUN_HOOK_PAYLOAD_BYTES`] carries the full account; what this exists for is
87/// the drift gate, which reads the model's documentation string and asserts the claim is
88/// still 16,384 — because the day AWS fixes their prose is the day this constant and its
89/// warning should be deleted, and nothing else would say so.
90///
91/// It is deliberately **never** used as a bound. The test below asserts it is 4x the real
92/// ceiling, which is the shape of the hazard: wrong in the permissive direction, telling a
93/// caller four times as much secret material fits as actually does.
94pub const DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES: usize = 16_384;
95
96/// `ImageName.max`.
97///
98/// The minimum is 1 and this comment used to say botocore enforces that one. It does, and this
99/// client does not use botocore — so the min is checked by
100/// `microvms_core::control::require_valid_image_name` like everything else, and always was.
101pub const MAX_IMAGE_NAME_LEN: usize = 64;
102
103/// `ImageName.pattern`, as the model spells it.
104///
105/// No dots and no slashes, which rules out the two separators a caller reaching for a
106/// namespaced name writes first. Published as a string for the drift gate; the
107/// matcher is [`is_valid_image_name`], a direct byte check over the four ranges.
108pub const IMAGE_NAME_PATTERN: &str = "[a-zA-Z0-9-_]+";
109
110/// `Version.max`, which is also `NonBlankString.max`.
111///
112/// Checked by `microvms_core::control::require_valid_version` on the two members this client sends
113/// as a `Version` — `CreateMicrovmImage.baseImageVersion` and `RunMicrovm.imageVersion`. Issue
114/// #24 named `NonBlankString` as the model's most-reused unguarded shape; these are the two
115/// places it is now guarded, and both are sent at a moment where the service's own rejection
116/// is expensive (after an artifact upload, or in the middle of a rollback).
117pub const MAX_VERSION_LEN: usize = 2048;
118
119/// `Version.pattern` — **no whitespace anywhere**, not merely "not blank".
120///
121/// Published as a string for the drift gate; the check is hand-rolled beside it for the reason
122/// [`IMAGE_NAME_PATTERN`] gives. A version copied out of a terminal carries a trailing newline
123/// and satisfies "non-empty" while failing this, which is why the refusal names the character.
124pub const VERSION_PATTERN: &str = "[^\\s]+";
125
126/// `NonBlankString.max`, which today equals [`MAX_VERSION_LEN`] and is a different shape.
127///
128/// The model's most-reused constrained shape — 45 members name it — and the ones this client
129/// *sends* are `CodeArtifact.uri`, `CreateMicrovmImage.baseImageArn`, and
130/// `ListMicrovmImages.nameFilter`. Checked by `microvms_core::control::require_non_blank`.
131///
132/// A separate constant from [`MAX_VERSION_LEN`] rather than a reuse of it, and the reason is
133/// the same one the two connector ceilings give: `Version` and `NonBlankString` are two shapes
134/// in the model with two independent futures, and AWS can move one without moving the other.
135/// One constant serving both would be a comparison that silently stops being about one of
136/// them. The drift gate holds each against its own shape.
137pub const MAX_NON_BLANK_LEN: usize = 2048;
138
139/// `NonBlankString.pattern` — the same `[^\s]+` [`VERSION_PATTERN`] carries, held separately
140/// for the reason [`MAX_NON_BLANK_LEN`] gives.
141pub const NON_BLANK_PATTERN: &str = "[^\\s]+";
142
143/// `MicrovmIdentifier.max` and `MicrovmImageIdentifier.max`, which are the same number.
144///
145/// Both shapes are `min: 1, max: 256`, and between them they cover **twelve** URI, body, and
146/// querystring members across every implemented operation — every `GetMicrovm`, `Suspend`,
147/// `Resume`, `Terminate`, `CreateMicrovmAuthToken`, `GetMicrovmImage`, `Delete*`, `List*`, and
148/// `RunMicrovm.imageIdentifier`. Checked by `microvms_core::control::require_valid_identifier`.
149///
150/// # The model contradicts itself here, and the client resolves it toward 256
151///
152/// `MicrovmImageArn` is `min: 20, max: 2048`, and it is the shape the service **answers** with
153/// on `GetMicrovmResponse.imageArn`, `MicrovmItem.imageArn`, and `RunMicrovmResponse.imageArn`.
154/// So the model permits the service to return a 2048-character image ARN that is then illegal
155/// to pass back as a `MicrovmImageIdentifier`. That is a real contradiction, not a reading
156/// error, and only one side of it can be guarded: the request side.
157///
158/// This client refuses above 256 on the way out, because that is the bound the *request*
159/// shapes state and a request over it is rejected by the service regardless of where the value
160/// came from. Refusing there names the contradiction — see
161/// `microvms_core::control::require_valid_identifier`, whose message says an over-long identifier
162/// that came from a response is a service-side inconsistency to report rather than a caller
163/// mistake. The alternative, accepting up to 2048 because a response might carry one, would
164/// send a request that cannot succeed and report the service's `ValidationException` as though
165/// the caller had chosen the length.
166///
167/// In practice the gap is theoretical: a real image ARN in the longest-named MicroVM region is
168/// about 90 characters, and the test below pins that arithmetic so "it fits" is measured rather
169/// than assumed.
170pub const MAX_IDENTIFIER_LEN: usize = 256;
171
172/// `MicrovmImageArn.max` — 2048, the number that contradicts [`MAX_IDENTIFIER_LEN`].
173///
174/// Pinned so the contradiction is a comparison rather than a comment: this is a
175/// **response**-side shape, so nothing guards a value against it, and its only job here is to
176/// be the second half of the assertion that the two disagree. If AWS ever narrows this to 256
177/// the contradiction is gone and the paragraph in [`MAX_IDENTIFIER_LEN`] should go with it —
178/// the drift gate is what would notice.
179pub const MAX_IMAGE_ARN_LEN: usize = 2048;
180
181/// `TagKey.max`. Minimum is 1, so a blank key is not a tag.
182pub const MAX_TAG_KEY_LEN: usize = 128;
183
184/// `TagValue.max`. Minimum is **0** — an empty tag value is legal, unlike an empty key.
185pub const MAX_TAG_VALUE_LEN: usize = 256;
186
187/// The `TagKey`/`TagValue` pattern, which both shapes share verbatim.
188///
189/// Unicode property classes — letters, separators, numbers, and
190/// `_ . : / = + - @` — so this is the one pattern in this module that is **not** ASCII ranges,
191/// and the matcher [`is_valid_tag_component`] is written against `char::is_alphabetic` and
192/// friends rather than against byte ranges for that reason.
193///
194/// # The pattern is `*` and therefore matches everything, which is a trap
195///
196/// The whole thing is a `*`-quantified group, so the empty string matches and so does any
197/// prefix — an unanchored `*` pattern rejects nothing at all. What actually bites a caller is
198/// the character *set*: a tag key with a comma, a hash, or a percent in it is outside it. The
199/// matcher therefore checks that **every** character is in the set rather than trying to
200/// implement the regex, which is the useful reading of the constraint and the one the service
201/// enforces. Published as a string for the drift gate.
202pub const TAG_COMPONENT_PATTERN: &str = "([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)";
203
204/// `CloudWatchLoggingLogGroupString.max` — the ceiling on `logging.cloudWatch.logGroup`.
205///
206/// Checked by `microvms_core::control::require_valid_log_group` before the create call, which
207/// happens after the artifact upload — the same ordering argument every other create-side
208/// guard makes.
209pub const MAX_LOG_GROUP_LEN: usize = 512;
210
211/// `CloudWatchLoggingLogGroupString.pattern`, as the model spells it.
212///
213/// Letters, digits, and `_ - / . #` — no colon, no space. Published as a string for the
214/// drift gate; the matcher is [`is_valid_log_group`], a direct byte check for the reason
215/// [`IMAGE_NAME_PATTERN`] gives.
216pub const LOG_GROUP_PATTERN: &str = "[a-zA-Z0-9_\\-/.#]+";
217
218/// `CloudWatchLoggingLogStreamString.max` — the ceiling on `logging.cloudWatch.logStream`.
219///
220/// This bounds the value **on the wire**, which is never the caller's value verbatim: the
221/// client always appends `/<16 hex>` (see [`MAX_USER_LOG_STREAM_LEN`] for why, and
222/// `microvms_core::control::image` for the mechanism), so the caller-facing ceiling is lower.
223pub const MAX_LOG_STREAM_LEN: usize = 512;
224
225/// `CloudWatchLoggingLogStreamString.pattern` — anything but `:` and `*`.
226///
227/// The two excluded characters are CloudWatch's own stream-name reserved set. Published as
228/// a string for the drift gate; `microvms_core::control::require_valid_log_stream` names it in
229/// its refusal.
230pub const LOG_STREAM_PATTERN: &str = "[^:*]*";
231
232/// The ceiling on a **caller-supplied** log stream name: [`MAX_LOG_STREAM_LEN`] minus the
233/// 17 characters of per-build discriminator this client always appends (`/` + 16 hex).
234///
235/// # Why the client never sends a caller's stream name verbatim
236///
237/// The `logStream` member is an **exact** stream name, not a prefix (prefixes are
238/// unsupported — 2026-08 platform finding, docs/PLATFORM.md 'An image build is three VMs
239/// and three log streams'). One build emits three log streams, and a fixed configured name
240/// collapses all three — and every *successive* build's three — into one stream, making
241/// concurrent builds of different images indistinguishable. Appending a fresh CSPRNG
242/// discriminator per create attempt keeps a configured name useful as a *family* prefix
243/// while every attempt stays tellable apart, which is the same shape as TRAP-1's token
244/// nonce and reuses its mechanism.
245///
246/// The test beside these constants pins the arithmetic, so a change to the nonce width
247/// fails here rather than as a `ValidationException` after the artifact upload.
248pub const MAX_USER_LOG_STREAM_LEN: usize = 495;
249
250/// `RoleArn.min` — 20 characters, which is the shortest thing that can be an IAM role ARN.
251pub const MIN_ROLE_ARN_LEN: usize = 20;
252
253/// `RoleArn.max`.
254pub const MAX_ROLE_ARN_LEN: usize = 2048;
255
256/// `RoleArn.pattern`, as the model spells it.
257///
258/// Checked by `microvms_core::control::require_valid_role_arn` on `CreateMicrovmImage.buildRoleArn`
259/// and `RunMicrovm.executionRoleArn`. The build role is the one that matters most: the create
260/// call happens **after** the artifact upload, so the service's rejection of a malformed role
261/// ARN costs the caller the upload — the exact ordering `create_image` is arranged to prevent,
262/// and the reason issue #24 called this one out by name.
263///
264/// Hand-matched rather than compiled, for the reason [`IMAGE_NAME_PATTERN`] gives, and the
265/// matcher is deliberately a **structural** check rather than a full regex implementation: see
266/// [`is_valid_role_arn`] on what it does and does not decide.
267pub const ROLE_ARN_PATTERN: &str = "arn:aws[a-z\\-]*:iam::[0-9]{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+";
268
269/// `PortNumber.min`, and also `HooksPortInteger.min`. **1, not 0.**
270///
271/// Port 0 is what "let the kernel choose" means to a listener and it is not a port a proxy
272/// token or a hooks block can name. `with_port(0)` was representable and sent `{"port": 0}`
273/// (issue #24); `microvms_core::control::require_valid_port` is what refuses it now.
274pub const MIN_PORT: u16 = 1;
275
276/// `PortNumber.max`, which equals [`MAX_HOOK_PORT`] and is a different shape.
277///
278/// Held apart for the reason [`MAX_NON_BLANK_LEN`] gives: `PortNumber` bounds
279/// `PortSpecification.port` and both ends of a `PortRange`, `HooksPortInteger` bounds
280/// `Hooks.port`, and they are two shapes AWS can move independently.
281pub const MAX_PORT: u16 = 65_535;
282
283/// `IdlePolicyMaxIdleDurationSecondsInteger.min` — 60 seconds, with no maximum.
284///
285/// # Why this has a constant now when it deliberately did not
286///
287/// The old comment here and on `microvms_core::control::RunMicrovmRequest::max_idle_sec` justified
288/// having no guard on the grounds that `min` is one of the four keys in botocore's
289/// `VALIDATED_METADATA_ATTRS`, so botocore refuses it before the wire with a clear message.
290/// That is true of botocore and **false of this client**: `microvms-core` signs with
291/// `aws-sigv4` and sends with `reqwest`, and nothing in the dependency set imports
292/// `botocore/validate.py`. The reasoning was inherited from the deleted Python client, where it
293/// held, and it did not survive the port. Issue #24 measured the consequence:
294/// `max_idle_sec: 59` reached the wire.
295///
296/// Checked by `microvms_core::control::require_idle_duration`. There is no maximum in the model, and
297/// the client adds none: a caller who wants a VM that never auto-suspends within its
298/// `maximumDurationInSeconds` says so with a large number, and the eight-hour ceiling on the
299/// VM's life is the real bound.
300pub const MIN_IDLE_DURATION_SEC: u32 = 60;
301
302/// `RunMicrovmRequestMaximumDurationInSecondsInteger.max` — eight hours, and the hard
303/// ceiling on any single VM's life. A longer session needs a second VM, not a larger
304/// number.
305pub const MAX_DURATION_SEC: u32 = 28_800;
306
307/// `MicrovmHooks*TimeoutInSecondsInteger.max` (run, resume, suspend, terminate).
308///
309/// See [`crate::hooks`] for the 60x gap and why it is two types.
310pub const MAX_MICROVM_HOOK_TIMEOUT_SEC: u32 = 60;
311
312/// `MicrovmImageHooks*TimeoutInSecondsInteger.max` (ready, validate).
313pub const MAX_IMAGE_HOOK_TIMEOUT_SEC: u32 = 3_600;
314
315/// `HooksPortInteger.max`.
316pub const MAX_HOOK_PORT: u32 = 65_535;
317
318/// The `Capability` enum, which is exactly this one value.
319///
320/// Which is why guest identity repair is a boolean intent flag rather than a
321/// capability list (TRAP-3): there is no way to ask for `CAP_SYS_ADMIN` alone.
322pub const CAPABILITIES: [&str; 1] = ["ALL"];
323
324/// The `Architecture` enum, which is exactly this one value: a MicroVM cannot be x86.
325///
326/// Load-bearing for cost (COST-9) as well as for requests — the Pricing API returns
327/// both ARM and non-ARM compute rates 17.9% apart, and only the ARM line can ever
328/// apply.
329pub const ARCHITECTURES: [&str; 1] = ["ARM_64"];
330
331/// `NetworkConnectorList.max` — the **VM-level** list, which `RunMicrovm` sends.
332pub const MAX_NETWORK_CONNECTORS: usize = 10;
333
334/// `NetworkConnector.max` — the maximum ARN length accepted by `RunMicrovm`.
335pub const MAX_NETWORK_CONNECTOR_LEN: usize = 2048;
336
337/// The **image-level** egress list's max, which is `1` and not `10`.
338///
339/// Six shapes in the model declare an image-level `egressNetworkConnectors` with
340/// `min: 0, max: 1` — `CreateMicrovmImageRequest`, `MicrovmImageVersionSummary`,
341/// `GetMicrovmImageVersionOutput`, `UpdateMicrovmImageVersionResponse`, and two more. The
342/// VM-level `NetworkConnectorList` above allows 10. Issue #24 named the hazard: reusing
343/// [`MAX_NETWORK_CONNECTORS`] for an image-level list is wrong by an order of magnitude, and
344/// wrong in the permissive direction, so the rejection would arrive from the service.
345///
346/// Pinned here rather than left as a comment because the version readback now deserializes
347/// that list (`microvms_core::control::ops::MicrovmImageVersionSummaryWire`), so the two ceilings
348/// are both live in this crate and the drift gate can hold each against its own shape.
349pub const MAX_IMAGE_EGRESS_CONNECTORS: usize = 1;
350
351/// The `MicrovmImageVersionStatus` enum, in the model's order.
352///
353/// The values `UpdateMicrovmImageVersion` accepts and `GetMicrovmImageVersion` answers.
354/// Published so the drift gate compares them against the shape rather than against a literal
355/// inside the script — which is the gap the script's own comment admits for the five state
356/// enums, and this one is a request member, so a value the model dropped would be a call this
357/// client makes and the service refuses.
358///
359/// `microvms_core::control::ops::VersionStatus` is the typed spelling; this array is what the gate
360/// reads, and the test at the bottom of that module asserts the two agree.
361pub const IMAGE_VERSION_STATUSES: [&str; 2] = ["ACTIVE", "INACTIVE"];
362
363/// The `HookState` enum, in the model's order. `DISABLED` first.
364///
365/// The two values every one of the six hook flags takes. Published so the gate compares them
366/// against the shape, and because this is a **request** enum on six members of every
367/// `CreateMicrovmImage`: a value the model dropped is a call this client makes and the service
368/// refuses, on six fields at once.
369///
370/// `microvms_core::control::ops::HookState` is the typed spelling and is what the request carries.
371/// This array is what the gate reads, and the test in that module asserts the two agree — the
372/// same arrangement [`IMAGE_VERSION_STATUSES`] has with `ops::VersionStatus`.
373pub const HOOK_STATES: [&str; 2] = ["DISABLED", "ENABLED"];
374
375/// The `MicrovmState` enum, in the model's order.
376///
377/// # Why the state enums live here now
378///
379/// They were pinned against literals inside `tools/check-model-drift.py`, which the script's own
380/// comment admitted: the gate verified the model against the *script*, with no reader in the
381/// client at all. Issue #24 named the consequence — a `MicrovmState` AWS adds fails the gate
382/// with no compile-time consequence for the polling loops in
383/// `microvms_core::control::microvm` that branch on states, so the gate's failure and the loop's
384/// blindness were unrelated facts.
385///
386/// Moving the set here does not make a new state a compile error — a wire string cannot be
387/// exhaustively matched, and narrowing a *response* enum is the mistake
388/// `microvms_core::control::ops::MicrovmImageBuildSummaryWire::architecture` documents at length. What
389/// it does buy is a reader in the crate that the loops' own sets are checked against: the tests
390/// below assert [`TERMINAL_STATES`] and [`DEAD_STATES`] are subsets of this, and
391/// `microvms_core::control::microvm::SUSPEND_WANTED` is checked against it too. So a state removed or
392/// respelled by AWS fails the gate *and* fails a test naming the loop that branches on it.
393pub const MICROVM_STATES: [&str; 6] = [
394    "PENDING",
395    "RUNNING",
396    "SUSPENDING",
397    "SUSPENDED",
398    "TERMINATING",
399    "TERMINATED",
400];
401
402/// The `MicrovmImageState` enum, in the model's order.
403///
404/// What `microvms_core::control::image::Image::is_ready` and `is_failed` are decided against. The
405/// three `*_FAILED` spellings are why `is_failed` is a substring test rather than a set: a
406/// fourth added later is still recognised as a failure rather than polled to the deadline, and
407/// the test below asserts that reading is still true of every member here.
408pub const IMAGE_STATES: [&str; 9] = [
409    "CREATING",
410    "CREATED",
411    "CREATE_FAILED",
412    "UPDATING",
413    "UPDATED",
414    "UPDATE_FAILED",
415    "DELETING",
416    "DELETE_FAILED",
417    "DELETED",
418];
419
420/// The `MicrovmImageVersionState` enum, in the model's order.
421///
422/// What `MicrovmImageVersionSummary.state` carries. Note it is **not** the same set as
423/// [`IMAGE_STATES`] and not the same as [`BUILD_STATES`] either, which is the reason all three
424/// are here: a habit that works for one is wrong for the others.
425pub const IMAGE_VERSION_STATES: [&str; 7] = [
426    "PENDING",
427    "IN_PROGRESS",
428    "SUCCESSFUL",
429    "FAILED",
430    "DELETING",
431    "DELETED",
432    "DELETE_FAILED",
433];
434
435/// The `BuildState` enum, in the model's order.
436///
437/// `PENDING` is the one TRAP-2's stall probe reads: **all** builds still `PENDING` past the
438/// stall grace is the `clientToken` replay signature. The probe compares against a literal
439/// today; the test below asserts that literal is a member of this set, which is the check that
440/// notices a respelling — the same class of bug as `buildState`/`state`, which was dead against
441/// live AWS for a review round.
442pub const BUILD_STATES: [&str; 4] = ["PENDING", "IN_PROGRESS", "SUCCESSFUL", "FAILED"];
443
444/// The `Chipset` enum, which is exactly this one value.
445///
446/// Now deserialized: `microvms_core::control::ops::MicrovmImageBuildSummaryWire::chipset` and
447/// `GetImageBuildResponseWire::chipset` both read it, so the drift-gate observation in issue #24
448/// — "`Chipset` is drift-checked but deserialized nowhere" — was closed by the
449/// build-introspection work that added the model's five missing required members to those two
450/// shapes. Pinned here so the gate reads the value from the crate rather than from a literal in
451/// its own file.
452///
453/// Carried as a `String` on the wire types rather than narrowed to this set, for the reason
454/// those types state: a second chipset AWS adds must parse rather than fail a build readback.
455pub const CHIPSETS: [&str; 1] = ["GRAVITON"];
456
457/// `ResourcesList.max`.
458///
459/// Only one entry is accepted, so "give the VM two memory floors" is not a thing that
460/// can be asked.
461pub const MAX_RESOURCES: usize = 1;
462
463/// `Create/Run/UpdateMicrovmImageRequestClientTokenString.max`, all three 128.
464///
465/// Not a cosmetic cap. Run tokens fold in the image identifier, which is a full ARN,
466/// and an ap-northeast-1 ARN is long: the drift gate mints a token for the worst legal
467/// scope and asserts it fits, which is a check that found a real pre-launch bug.
468pub const MAX_CLIENT_TOKEN_LEN: usize = 128;
469
470/// The `MicrovmImageState` values that mean "built and usable", as the model spells
471/// them.
472///
473/// `UPDATED` is here even though this client never calls `UpdateMicrovmImage`: an
474/// image someone else updated is usable, and treating it as still-building is a
475/// 45-minute wait on a state that will never change.
476pub const MODEL_IMAGE_READY_STATES: [&str; 2] = ["CREATED", "UPDATED"];
477
478/// Spellings that are *not* in the 2025-09-09 `MicrovmImageState` enum, tolerated
479/// when the service answers with one.
480///
481/// Held apart from [`MODEL_IMAGE_READY_STATES`] so the drift gate can check the
482/// model-derived set *exactly* instead of being told that two of the three values it
483/// cannot find are fine. If a future model adds either, move it up. Kept at all
484/// because the service has answered differently across API versions, and a hard
485/// equality check on one spelling is how a working build looks like a stalled one.
486pub const TOLERATED_IMAGE_READY_STATES: [&str; 2] = ["ACTIVE", "AVAILABLE"];
487
488/// Terminal `MicrovmState` values.
489///
490/// Reaching any of them *before* RUNNING means the VM died during startup, which for a
491/// hook-serving daemon almost always means a lifecycle hook failed — and `stateReason`
492/// is where the answer is (TRAP-8).
493pub const TERMINAL_STATES: [&str; 4] = ["TERMINATED", "TERMINATING", "SUSPENDED", "SUSPENDING"];
494
495/// The subset of [`TERMINAL_STATES`] from which nothing comes back.
496///
497/// Separate because SUSPENDED is a death *before* RUNNING and an ordinary waypoint on
498/// the resume path — a resume that failed fast on SUSPENDED would fail on every
499/// resume, since that is the state the VM is in when the call is made.
500pub const DEAD_STATES: [&str; 2] = ["TERMINATED", "TERMINATING"];
501
502/// Whether `name` satisfies [`IMAGE_NAME_PATTERN`] and [`MAX_IMAGE_NAME_LEN`].
503///
504/// A direct byte check: the pattern is `[a-zA-Z0-9-_]+`, four character ranges, which
505/// `is_ascii_alphanumeric` states without a second place the pattern is written down.
506/// The length check is here too because a caller asking "is
507/// this name legal" means both constraints — they arrive from the same model shape and
508/// the service rejects on either.
509pub fn is_valid_image_name(name: &str) -> bool {
510    !name.is_empty()
511        && name.len() <= MAX_IMAGE_NAME_LEN
512        && name
513            .bytes()
514            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
515}
516
517/// Whether `group` satisfies [`LOG_GROUP_PATTERN`] and [`MAX_LOG_GROUP_LEN`].
518///
519/// A direct byte check over the pattern's character set — letters, digits, `_ - / . #` —
520/// for the reason [`is_valid_image_name`] gives. The length is checked here too, because a
521/// caller asking "is this group name legal" means both constraints: they arrive from the
522/// same model shape and the service rejects on either.
523pub fn is_valid_log_group(group: &str) -> bool {
524    !group.is_empty()
525        && group.len() <= MAX_LOG_GROUP_LEN
526        && group
527            .bytes()
528            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'/' | b'.' | b'#'))
529}
530
531/// Whether every character of `component` is in [`TAG_COMPONENT_PATTERN`]'s set.
532///
533/// **The length is not checked here**, unlike [`is_valid_image_name`], and the asymmetry is
534/// deliberate: a key and a value share this one pattern and have *different* ceilings (128
535/// against 256) and different minima (1 against 0). A combined check would need to know which
536/// side it was looking at, which is what `microvms_core::control::require_valid_tags` does — it names
537/// the key or the value in its message, so a caller with twenty tags is told which one and
538/// which half.
539///
540/// # Why the character set and not the regex
541///
542/// The model's pattern is one `*`-quantified group, and an unanchored `*` matches the empty
543/// string and every prefix — as a predicate it rejects nothing. The service nonetheless refuses
544/// a key with a comma or a percent in it, so the constraint that has any content is the
545/// character *set*, and that is what this decides. Unicode classes rather than byte ranges,
546/// because `\p{L}` includes `é` and `日` and a tag key in a non-Latin script is a legitimate
547/// tag: a byte-range matcher would refuse it.
548///
549/// `\p{Z}` is the separator class, which includes the ordinary space — so `"cost centre"` is a
550/// legal tag key, unlike an image name.
551pub fn is_valid_tag_component(component: &str) -> bool {
552    component.chars().all(|c| {
553        c.is_alphabetic()
554            || c.is_numeric()
555            // `\p{Z}`: separators. `char::is_whitespace` also covers `\n` and `\t`, which are
556            // `\p{Cc}` control characters and outside the class — so they are excluded here
557            // rather than folded in, and a tag key with a newline in it is refused.
558            || matches!(c, ' ' | '\u{00a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}'
559                | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}')
560            || matches!(c, '_' | '.' | ':' | '/' | '=' | '+' | '-' | '@')
561    })
562}
563
564/// Whether `arn` is structurally an IAM role ARN, per [`ROLE_ARN_PATTERN`].
565///
566/// # What this decides, and what it deliberately does not
567///
568/// The pattern is `arn:aws[a-z\-]*:iam::[0-9]{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+`, and this checks
569/// every part of it: the `arn:aws` prefix with its optional partition suffix, the literal
570/// `:iam::`, **exactly twelve digits** of account id, and a `:role` segment followed by a
571/// non-empty name in the permitted character set.
572///
573/// The twelve digits are the part worth having. Every real mistake this catches is one of three:
574/// a role *name* passed where an ARN was wanted, an ARN for the wrong service (a Lambda function
575/// ARN, say), or an account id with a digit dropped — and the third is the one no eyeball catches
576/// and no other check would. It is also the reason this is not a `starts_with("arn:")` test the
577/// way `microvms_core::control::ControlPlane::managed_base_versions`'s is: that one distinguishes an
578/// ARN from a bare name, and this one has a specific ARN grammar to hold a value to.
579///
580/// What it does not decide is whether the role **exists**, whether it is assumable, or whether it
581/// grants the `logs:*` on `/aws/lambda-microvms/*` that a build role needs. Those are the failures
582/// that actually happen most often, and none of them is knowable locally — IAM is not in this
583/// crate's dependency set. So this guard is narrow on purpose: it converts a class of malformed
584/// values into a local refusal and leaves the semantic failures to the service, which is the only
585/// party that can answer them.
586pub fn is_valid_role_arn(arn: &str) -> bool {
587    // `arn:aws` then the optional partition suffix, `[a-z\-]*`, up to the next `:`.
588    let Some(rest) = arn.strip_prefix("arn:aws") else {
589        return false;
590    };
591    let Some(colon) = rest.find(':') else {
592        return false;
593    };
594    let (partition_suffix, rest) = rest.split_at(colon);
595    if !partition_suffix
596        .bytes()
597        .all(|b| b.is_ascii_lowercase() || b == b'-')
598    {
599        return false;
600    }
601
602    // `:iam::` then exactly twelve digits then `:role`.
603    let Some(rest) = rest.strip_prefix(":iam::") else {
604        return false;
605    };
606    let Some(colon) = rest.find(':') else {
607        return false;
608    };
609    let (account, rest) = rest.split_at(colon);
610    if account.len() != 12 || !account.bytes().all(|b| b.is_ascii_digit()) {
611        return false;
612    }
613    let Some(name) = rest.strip_prefix(":role") else {
614        return false;
615    };
616    // `role/?` — the slash is optional in the pattern, and the name that follows is `+`, so it
617    // must be non-empty either way. `role/admin` and `roleadmin` both match the model's regex;
618    // only the first is a real ARN, and refusing the second would be this client being stricter
619    // than the service on a value it has no other reason to inspect.
620    let name = name.strip_prefix('/').unwrap_or(name);
621    !name.is_empty()
622        && name.bytes().all(|b| {
623            b.is_ascii_alphanumeric()
624                || matches!(b, b'_' | b'+' | b'=' | b',' | b'.' | b'@' | b'-' | b'/')
625        })
626}
627
628/// Every constant in this module as one JSON object, keyed for the model drift gate.
629///
630/// The drift gate's second source (TRAP-12). Emitted through `serde_json` rather than
631/// formatted by hand so the object is a function of the values above, which is the
632/// only version of this that cannot drift from them.
633///
634/// `MICROVM_REGIONS` is in here and is explicitly **not** model-backed — no service
635/// model states it and no API answers the question (see [`crate::region`]). It is
636/// published so the gate can compare it with its independently pinned region list.
637///
638/// # A list of pairs rather than one `json!({...})` literal, and that is forced
639///
640/// It was one object literal until issue #24's constants took the count past 40, at which
641/// point `json!` fails to compile: "recursion limit reached while expanding
642/// `$crate::json_internal!`", because the macro recurses once per entry against the crate's
643/// 128-deep default. The two ways out were a crate-wide `#![recursion_limit]` bump — a global
644/// knob turned for one macro in one function — and this. Each entry is still `json!(CONST)`, so
645/// every value is a function of the `pub const` above it, which is the property the gate rests
646/// on.
647pub fn as_json() -> Value {
648    let entries: Vec<(&str, Value)> = vec![
649        ("MODEL_API_VERSION", json!(MODEL_API_VERSION)),
650        (
651            "MAX_RUN_HOOK_PAYLOAD_BYTES",
652            json!(MAX_RUN_HOOK_PAYLOAD_BYTES),
653        ),
654        (
655            "DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES",
656            json!(DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES),
657        ),
658        ("MAX_IMAGE_NAME_LEN", json!(MAX_IMAGE_NAME_LEN)),
659        ("IMAGE_NAME_PATTERN", json!(IMAGE_NAME_PATTERN)),
660        ("MAX_VERSION_LEN", json!(MAX_VERSION_LEN)),
661        ("VERSION_PATTERN", json!(VERSION_PATTERN)),
662        ("MAX_NON_BLANK_LEN", json!(MAX_NON_BLANK_LEN)),
663        ("NON_BLANK_PATTERN", json!(NON_BLANK_PATTERN)),
664        ("MAX_IDENTIFIER_LEN", json!(MAX_IDENTIFIER_LEN)),
665        ("MAX_IMAGE_ARN_LEN", json!(MAX_IMAGE_ARN_LEN)),
666        ("MAX_TAG_KEY_LEN", json!(MAX_TAG_KEY_LEN)),
667        ("MAX_TAG_VALUE_LEN", json!(MAX_TAG_VALUE_LEN)),
668        ("TAG_COMPONENT_PATTERN", json!(TAG_COMPONENT_PATTERN)),
669        ("MAX_LOG_GROUP_LEN", json!(MAX_LOG_GROUP_LEN)),
670        ("LOG_GROUP_PATTERN", json!(LOG_GROUP_PATTERN)),
671        ("MAX_LOG_STREAM_LEN", json!(MAX_LOG_STREAM_LEN)),
672        ("LOG_STREAM_PATTERN", json!(LOG_STREAM_PATTERN)),
673        ("MAX_USER_LOG_STREAM_LEN", json!(MAX_USER_LOG_STREAM_LEN)),
674        ("MIN_ROLE_ARN_LEN", json!(MIN_ROLE_ARN_LEN)),
675        ("MAX_ROLE_ARN_LEN", json!(MAX_ROLE_ARN_LEN)),
676        ("ROLE_ARN_PATTERN", json!(ROLE_ARN_PATTERN)),
677        ("MIN_PORT", json!(MIN_PORT)),
678        ("MAX_PORT", json!(MAX_PORT)),
679        ("MIN_IDLE_DURATION_SEC", json!(MIN_IDLE_DURATION_SEC)),
680        ("MAX_DURATION_SEC", json!(MAX_DURATION_SEC)),
681        (
682            "MAX_MICROVM_HOOK_TIMEOUT_SEC",
683            json!(MAX_MICROVM_HOOK_TIMEOUT_SEC),
684        ),
685        (
686            "MAX_IMAGE_HOOK_TIMEOUT_SEC",
687            json!(MAX_IMAGE_HOOK_TIMEOUT_SEC),
688        ),
689        ("MAX_HOOK_PORT", json!(MAX_HOOK_PORT)),
690        ("CAPABILITIES", json!(CAPABILITIES)),
691        ("ARCHITECTURES", json!(ARCHITECTURES)),
692        ("MAX_NETWORK_CONNECTORS", json!(MAX_NETWORK_CONNECTORS)),
693        (
694            "MAX_NETWORK_CONNECTOR_LEN",
695            json!(MAX_NETWORK_CONNECTOR_LEN),
696        ),
697        (
698            "MAX_IMAGE_EGRESS_CONNECTORS",
699            json!(MAX_IMAGE_EGRESS_CONNECTORS),
700        ),
701        ("IMAGE_VERSION_STATUSES", json!(IMAGE_VERSION_STATUSES)),
702        ("HOOK_STATES", json!(HOOK_STATES)),
703        ("MICROVM_STATES", json!(MICROVM_STATES)),
704        ("IMAGE_STATES", json!(IMAGE_STATES)),
705        ("IMAGE_VERSION_STATES", json!(IMAGE_VERSION_STATES)),
706        ("BUILD_STATES", json!(BUILD_STATES)),
707        ("CHIPSETS", json!(CHIPSETS)),
708        ("MAX_RESOURCES", json!(MAX_RESOURCES)),
709        ("MAX_CLIENT_TOKEN_LEN", json!(MAX_CLIENT_TOKEN_LEN)),
710        ("MODEL_IMAGE_READY_STATES", json!(MODEL_IMAGE_READY_STATES)),
711        (
712            "TOLERATED_IMAGE_READY_STATES",
713            json!(TOLERATED_IMAGE_READY_STATES),
714        ),
715        ("TERMINAL_STATES", json!(TERMINAL_STATES)),
716        ("DEAD_STATES", json!(DEAD_STATES)),
717        (
718            "MICROVM_REGIONS",
719            json!(
720                MICROVM_REGIONS
721                    .iter()
722                    .map(|region| region.as_str())
723                    .collect::<Vec<_>>()
724            ),
725        ),
726        (
727            "SIZE_CLASSES",
728            json!(
729                crate::sizing::SIZE_CLASSES
730                    .iter()
731                    .map(|row| json!({
732                        "baseline_mib": row.baseline_mib,
733                        "baseline_vcpu": row.baseline_vcpu,
734                        "peak_mib": row.peak_mib,
735                        "peak_vcpu": row.peak_vcpu,
736                    }))
737                    .collect::<Vec<_>>()
738            ),
739        ),
740    ];
741    Value::Object(
742        entries
743            .into_iter()
744            .map(|(key, value)| (key.to_string(), value))
745            .collect(),
746    )
747}
748
749#[cfg(test)]
750mod tests {
751    use super::*;
752
753    /// **TRAP-12.** The key set the drift gate reads, pinned.
754    ///
755    /// This is the guard for the one failure mode a rename here produces: the script
756    /// looks a key up, does not find it, and either crashes or — worse, depending on
757    /// how it is written — reports nothing disagreed. Compilation cannot catch that,
758    /// because the coupling is a string in another language's file.
759    #[test]
760    fn as_json_carries_every_key_the_drift_gate_reads() {
761        let emitted = as_json();
762        let object = emitted.as_object().expect("an object");
763        let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
764        keys.sort_unstable();
765        assert_eq!(
766            keys,
767            [
768                "ARCHITECTURES",
769                "BUILD_STATES",
770                "CAPABILITIES",
771                "CHIPSETS",
772                "DEAD_STATES",
773                "DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES",
774                "HOOK_STATES",
775                "IMAGE_NAME_PATTERN",
776                "IMAGE_STATES",
777                "IMAGE_VERSION_STATES",
778                "IMAGE_VERSION_STATUSES",
779                "LOG_GROUP_PATTERN",
780                "LOG_STREAM_PATTERN",
781                "MAX_CLIENT_TOKEN_LEN",
782                "MAX_DURATION_SEC",
783                "MAX_HOOK_PORT",
784                "MAX_IDENTIFIER_LEN",
785                "MAX_IMAGE_ARN_LEN",
786                "MAX_IMAGE_EGRESS_CONNECTORS",
787                "MAX_IMAGE_HOOK_TIMEOUT_SEC",
788                "MAX_IMAGE_NAME_LEN",
789                "MAX_LOG_GROUP_LEN",
790                "MAX_LOG_STREAM_LEN",
791                "MAX_MICROVM_HOOK_TIMEOUT_SEC",
792                "MAX_NETWORK_CONNECTORS",
793                "MAX_NETWORK_CONNECTOR_LEN",
794                "MAX_NON_BLANK_LEN",
795                "MAX_PORT",
796                "MAX_RESOURCES",
797                "MAX_ROLE_ARN_LEN",
798                "MAX_RUN_HOOK_PAYLOAD_BYTES",
799                "MAX_TAG_KEY_LEN",
800                "MAX_TAG_VALUE_LEN",
801                "MAX_USER_LOG_STREAM_LEN",
802                "MAX_VERSION_LEN",
803                "MICROVM_REGIONS",
804                "MICROVM_STATES",
805                "MIN_IDLE_DURATION_SEC",
806                "MIN_PORT",
807                "MIN_ROLE_ARN_LEN",
808                "MODEL_API_VERSION",
809                "MODEL_IMAGE_READY_STATES",
810                "NON_BLANK_PATTERN",
811                "ROLE_ARN_PATTERN",
812                "SIZE_CLASSES",
813                "TAG_COMPONENT_PATTERN",
814                "TERMINAL_STATES",
815                "TOLERATED_IMAGE_READY_STATES",
816                "VERSION_PATTERN",
817            ]
818        );
819    }
820
821    /// The values against independent expected literals. Written
822    /// out rather than compared against the constants, so this test disagrees with a
823    /// changed constant instead of following it.
824    #[test]
825    fn the_emitted_values_are_the_measured_ones() {
826        let emitted = as_json();
827        assert_eq!(emitted["MODEL_API_VERSION"], "2025-09-09");
828        assert_eq!(emitted["MAX_RUN_HOOK_PAYLOAD_BYTES"], 4096);
829        assert_eq!(emitted["MAX_IMAGE_NAME_LEN"], 64);
830        assert_eq!(emitted["IMAGE_NAME_PATTERN"], "[a-zA-Z0-9-_]+");
831        assert_eq!(emitted["MAX_VERSION_LEN"], 2048);
832        assert_eq!(emitted["VERSION_PATTERN"], "[^\\s]+");
833        assert_eq!(emitted["MAX_NON_BLANK_LEN"], 2048);
834        assert_eq!(emitted["NON_BLANK_PATTERN"], "[^\\s]+");
835        assert_eq!(emitted["MAX_IDENTIFIER_LEN"], 256);
836        assert_eq!(emitted["MAX_IMAGE_ARN_LEN"], 2048);
837        assert_eq!(emitted["MAX_TAG_KEY_LEN"], 128);
838        assert_eq!(emitted["MAX_TAG_VALUE_LEN"], 256);
839        assert_eq!(
840            emitted["TAG_COMPONENT_PATTERN"],
841            "([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)"
842        );
843        assert_eq!(emitted["MAX_LOG_GROUP_LEN"], 512);
844        assert_eq!(emitted["LOG_GROUP_PATTERN"], "[a-zA-Z0-9_\\-/.#]+");
845        assert_eq!(emitted["MAX_LOG_STREAM_LEN"], 512);
846        assert_eq!(emitted["LOG_STREAM_PATTERN"], "[^:*]*");
847        assert_eq!(emitted["MAX_USER_LOG_STREAM_LEN"], 495);
848        assert_eq!(emitted["MIN_ROLE_ARN_LEN"], 20);
849        assert_eq!(emitted["MAX_ROLE_ARN_LEN"], 2048);
850        assert_eq!(
851            emitted["ROLE_ARN_PATTERN"],
852            "arn:aws[a-z\\-]*:iam::[0-9]{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+"
853        );
854        assert_eq!(emitted["MIN_PORT"], 1);
855        assert_eq!(emitted["MAX_PORT"], 65_535);
856        assert_eq!(emitted["MIN_IDLE_DURATION_SEC"], 60);
857        assert_eq!(emitted["MAX_DURATION_SEC"], 28_800);
858        assert_eq!(emitted["MAX_MICROVM_HOOK_TIMEOUT_SEC"], 60);
859        assert_eq!(emitted["MAX_IMAGE_HOOK_TIMEOUT_SEC"], 3_600);
860        assert_eq!(emitted["MAX_HOOK_PORT"], 65_535);
861        assert_eq!(emitted["CAPABILITIES"], json!(["ALL"]));
862        assert_eq!(emitted["ARCHITECTURES"], json!(["ARM_64"]));
863        assert_eq!(emitted["MAX_NETWORK_CONNECTORS"], 10);
864        // 1, not 10. The image-level list and the VM-level one differ by an order of
865        // magnitude, and this is the assertion that says so in one place.
866        assert_eq!(emitted["MAX_IMAGE_EGRESS_CONNECTORS"], 1);
867        assert_eq!(
868            emitted["IMAGE_VERSION_STATUSES"],
869            json!(["ACTIVE", "INACTIVE"])
870        );
871        assert_eq!(emitted["HOOK_STATES"], json!(["DISABLED", "ENABLED"]));
872        assert_eq!(
873            emitted["MICROVM_STATES"],
874            json!([
875                "PENDING",
876                "RUNNING",
877                "SUSPENDING",
878                "SUSPENDED",
879                "TERMINATING",
880                "TERMINATED"
881            ])
882        );
883        assert_eq!(
884            emitted["IMAGE_STATES"],
885            json!([
886                "CREATING",
887                "CREATED",
888                "CREATE_FAILED",
889                "UPDATING",
890                "UPDATED",
891                "UPDATE_FAILED",
892                "DELETING",
893                "DELETE_FAILED",
894                "DELETED"
895            ])
896        );
897        assert_eq!(
898            emitted["IMAGE_VERSION_STATES"],
899            json!([
900                "PENDING",
901                "IN_PROGRESS",
902                "SUCCESSFUL",
903                "FAILED",
904                "DELETING",
905                "DELETED",
906                "DELETE_FAILED"
907            ])
908        );
909        assert_eq!(
910            emitted["BUILD_STATES"],
911            json!(["PENDING", "IN_PROGRESS", "SUCCESSFUL", "FAILED"])
912        );
913        assert_eq!(emitted["CHIPSETS"], json!(["GRAVITON"]));
914        assert_eq!(emitted["MAX_RESOURCES"], 1);
915        assert_eq!(emitted["MAX_CLIENT_TOKEN_LEN"], 128);
916        assert_eq!(
917            emitted["TERMINAL_STATES"],
918            json!(["TERMINATED", "TERMINATING", "SUSPENDED", "SUSPENDING"])
919        );
920        assert_eq!(emitted["DEAD_STATES"], json!(["TERMINATED", "TERMINATING"]));
921        assert_eq!(
922            emitted["MODEL_IMAGE_READY_STATES"],
923            json!(["CREATED", "UPDATED"])
924        );
925        assert_eq!(
926            emitted["TOLERATED_IMAGE_READY_STATES"],
927            json!(["ACTIVE", "AVAILABLE"])
928        );
929        assert_eq!(
930            emitted["MICROVM_REGIONS"],
931            json!([
932                "us-east-1",
933                "us-east-2",
934                "us-west-2",
935                "eu-west-1",
936                "ap-northeast-1"
937            ])
938        );
939    }
940
941    /// The object survives a serialize/parse cycle unchanged, which is what the gate
942    /// does to it: the CLI prints it and the script calls `json.loads`. A value that
943    /// only compares equal in memory is a value the gate never sees.
944    #[test]
945    fn the_emitted_object_round_trips_through_a_string() {
946        let emitted = as_json();
947        let text = serde_json::to_string(&emitted).expect("serializes");
948        let parsed: Value = serde_json::from_str(&text).expect("parses");
949        assert_eq!(parsed, emitted);
950    }
951
952    /// The dead states are a subset of the terminal ones, which is the relationship
953    /// the two lists exist to express. A DEAD_STATES entry that is not terminal would
954    /// make the launch guard and the resume guard disagree about what SUSPENDED means.
955    #[test]
956    fn every_dead_state_is_also_a_terminal_state() {
957        for state in DEAD_STATES {
958            assert!(TERMINAL_STATES.contains(&state), "{state} is not terminal");
959        }
960        assert!(
961            !DEAD_STATES.contains(&"SUSPENDED"),
962            "SUSPENDED is terminal but not dead: it is the state a resume is called from"
963        );
964    }
965
966    /// **Issue #24's wrong-by-10x hazard.** The two connector ceilings are different
967    /// numbers, and the image-level one is the smaller.
968    ///
969    /// Stated as an inequality rather than only as two literals above, because the failure
970    /// mode is a future edit that *unifies* them — "there is only one connector limit, delete
971    /// the duplicate" — and the permissive direction is the one that reaches the wire. A
972    /// caller who applied `MAX_NETWORK_CONNECTORS` to an image's `egressNetworkConnectors`
973    /// would accept ten and have the service refuse two.
974    #[test]
975    fn the_image_level_connector_ceiling_is_one_and_not_the_vm_levels_ten() {
976        assert_eq!(MAX_IMAGE_EGRESS_CONNECTORS, 1);
977        assert_eq!(MAX_NETWORK_CONNECTORS, 10);
978        // Read out of `as_json()` rather than compared as two `const`s, because clippy's
979        // `assertions_on_constants` is right that a `const < const` assertion is decided at
980        // compile time and proves nothing at runtime. Going through the emitted object makes it
981        // a real comparison — and it is the object the drift gate reads, so this asserts the
982        // published pair rather than two literals a reader could unify.
983        let emitted = as_json();
984        let image = emitted["MAX_IMAGE_EGRESS_CONNECTORS"]
985            .as_u64()
986            .expect("a number");
987        let vm = emitted["MAX_NETWORK_CONNECTORS"]
988            .as_u64()
989            .expect("a number");
990        assert!(
991            image < vm,
992            "collapsing the two would be permissive by 10x on the image-level list: \
993             {image} against {vm}"
994        );
995    }
996
997    /// The version statuses are exactly the two the model declares, spelled uppercase.
998    ///
999    /// The typed request-side spelling is checked against this array in
1000    /// `microvms_core::control::ops`, so the two cannot drift; here what is pinned is the pair itself
1001    /// and the fact that neither is a lowercase or a past-tense variant of the other.
1002    #[test]
1003    fn the_two_version_statuses_are_active_and_inactive() {
1004        assert_eq!(IMAGE_VERSION_STATUSES, ["ACTIVE", "INACTIVE"]);
1005        for status in IMAGE_VERSION_STATUSES {
1006            assert_eq!(status, status.to_uppercase(), "{status}");
1007        }
1008        assert!(
1009            !IMAGE_VERSION_STATUSES.contains(&"DISABLED"),
1010            "DISABLED is HookState's spelling, not this enum's — mixing them is a \
1011             ValidationException on the only member the update request has"
1012        );
1013    }
1014
1015    /// The ready-state sets are disjoint, so the gate can check the model-derived one
1016    /// exactly. An overlap would mean a tolerated spelling was being presented as
1017    /// model-backed.
1018    #[test]
1019    fn the_model_and_tolerated_ready_states_do_not_overlap() {
1020        for state in TOLERATED_IMAGE_READY_STATES {
1021            assert!(
1022                !MODEL_IMAGE_READY_STATES.contains(&state),
1023                "{state} is claimed as both model-backed and tolerated"
1024            );
1025        }
1026    }
1027
1028    /// The pattern's four ranges and nothing else. The two rejected characters are the
1029    /// separators a caller reaching for a namespaced name writes first, which is why
1030    /// they are named.
1031    #[test]
1032    fn an_image_name_takes_letters_digits_hyphen_and_underscore_only() {
1033        assert!(is_valid_image_name("agentd-conformance_01"));
1034        assert!(is_valid_image_name("A"));
1035        assert!(is_valid_image_name(&"a".repeat(MAX_IMAGE_NAME_LEN)));
1036
1037        assert!(!is_valid_image_name(""), "min is 1");
1038        assert!(
1039            !is_valid_image_name(&"a".repeat(MAX_IMAGE_NAME_LEN + 1)),
1040            "65 characters is one past the ceiling"
1041        );
1042        for rejected in [
1043            "my.image",
1044            "team/image",
1045            "my image",
1046            "img!",
1047            "imagé",
1048            "img\n",
1049        ] {
1050            assert!(!is_valid_image_name(rejected), "{rejected}");
1051        }
1052    }
1053
1054    /// A multi-byte character cannot slip past the length check by being counted as
1055    /// one: the model's max is on bytes, and the character class rejects it anyway.
1056    #[test]
1057    fn a_multibyte_name_is_refused_by_the_character_class_not_by_luck() {
1058        assert!(!is_valid_image_name("é"));
1059        assert!(!is_valid_image_name("日本語"));
1060    }
1061
1062    /// The log-group matcher takes exactly the model's set — letters, digits, `_ - / . #` —
1063    /// and both length bounds.
1064    ///
1065    /// `/aws/lambda-microvms/img` is the shape the service itself creates, so it has to
1066    /// pass; a colon is the character a caller pasting an ARN brings in first, so it is the
1067    /// named rejection.
1068    #[test]
1069    fn a_log_group_takes_the_models_character_set_and_bounds() {
1070        assert!(is_valid_log_group("/aws/lambda-microvms/img"));
1071        assert!(is_valid_log_group("builds_2026.08#a"));
1072        assert!(is_valid_log_group(&"a".repeat(MAX_LOG_GROUP_LEN)));
1073
1074        assert!(!is_valid_log_group(""), "min is 1");
1075        assert!(
1076            !is_valid_log_group(&"a".repeat(MAX_LOG_GROUP_LEN + 1)),
1077            "513 characters is one past the ceiling"
1078        );
1079        for rejected in ["arn:aws:logs", "a group", "grp*", "grp\n", "imagé"] {
1080            assert!(!is_valid_log_group(rejected), "{rejected}");
1081        }
1082    }
1083
1084    /// The user-facing stream ceiling leaves exactly the discriminator's room under the
1085    /// wire ceiling: `/` plus sixteen hex characters.
1086    ///
1087    /// Pinned as arithmetic so a change to the nonce width (`token.rs`'s eight bytes) or to
1088    /// either ceiling fails here rather than as a `ValidationException` after the artifact
1089    /// upload — the same shape as `token.rs`'s own cap test.
1090    #[test]
1091    fn the_user_stream_ceiling_leaves_room_for_the_slash_and_sixteen_hex() {
1092        assert_eq!(MAX_USER_LOG_STREAM_LEN + 1 + 16, MAX_LOG_STREAM_LEN);
1093    }
1094
1095    /// **Issue #24's documentation trap, pinned as a comparison.** The model's own prose says
1096    /// 16,384 and its shape says 4096, and the shape is the one that is enforced.
1097    ///
1098    /// The pair is asserted rather than only commented because the failure mode is a future
1099    /// reader "correcting" [`MAX_RUN_HOOK_PAYLOAD_BYTES`] from the model's documentation string —
1100    /// which they would be able to cite while doing it. This test is what makes that a red build
1101    /// rather than a plausible-looking commit, and the 4x relationship is asserted so the shape of
1102    /// the hazard is in the test and not only in a doc comment.
1103    ///
1104    /// **Guard proof.** Set `MAX_RUN_HOOK_PAYLOAD_BYTES` to 16_384 and this fails on the
1105    /// inequality *and* on the ratio; delete `DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES` and it does not
1106    /// compile.
1107    #[test]
1108    fn the_models_own_prose_claims_four_times_the_ceiling_its_shape_states() {
1109        let emitted = as_json();
1110        let real = emitted["MAX_RUN_HOOK_PAYLOAD_BYTES"]
1111            .as_u64()
1112            .expect("a number");
1113        let documented = emitted["DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES"]
1114            .as_u64()
1115            .expect("a number");
1116        assert_eq!(real, 4096, "the shape, which is what the service enforces");
1117        assert_eq!(
1118            documented, 16_384,
1119            "the model's documentation string on RunMicrovmRequest.runHookPayload"
1120        );
1121        assert!(
1122            documented > real,
1123            "the model's prose is permissive against its own shape: {documented} against {real}"
1124        );
1125        assert_eq!(
1126            documented / real,
1127            4,
1128            "wrong by 4x, in the direction that tells a caller four times as much secret \
1129             material fits as actually does"
1130        );
1131    }
1132
1133    /// **The model's identifier contradiction, pinned.** A legal `MicrovmImageArn` can be longer
1134    /// than a legal `MicrovmImageIdentifier`, so the service may answer with a value it would
1135    /// refuse as a request.
1136    ///
1137    /// Held as an inequality because the fact is a *relationship* between two shapes and no
1138    /// single shape states it. If AWS ever narrows `MicrovmImageArn` to 256 this goes red, which
1139    /// is the signal that the paragraph in [`MAX_IDENTIFIER_LEN`] about resolving the
1140    /// contradiction should be deleted.
1141    ///
1142    /// The second half is the reason it is theoretical in practice: a real ARN in the
1143    /// longest-named MicroVM region is nowhere near 256, and that arithmetic is measured here
1144    /// rather than asserted as a habit.
1145    #[test]
1146    fn a_legal_image_arn_can_be_longer_than_a_legal_identifier() {
1147        let emitted = as_json();
1148        let identifier = emitted["MAX_IDENTIFIER_LEN"].as_u64().expect("a number");
1149        let arn = emitted["MAX_IMAGE_ARN_LEN"].as_u64().expect("a number");
1150        assert!(
1151            arn > identifier,
1152            "the model permits a {arn}-character image ARN and a {identifier}-character \
1153             identifier, so a legal response value can be an illegal request value"
1154        );
1155
1156        // The worst legal real ARN: the longest region name, a twelve-digit account, and a
1157        // 64-character image name. Built rather than written as a literal, so the arithmetic is
1158        // the test's rather than mine.
1159        let longest_region = MICROVM_REGIONS
1160            .iter()
1161            .map(|region| region.as_str().len())
1162            .max()
1163            .expect("five regions");
1164        let worst = format!(
1165            "arn:aws:lambda:{}:{}:microvm-image:{}",
1166            "x".repeat(longest_region),
1167            "9".repeat(12),
1168            "a".repeat(MAX_IMAGE_NAME_LEN),
1169        );
1170        assert!(
1171            worst.len() <= MAX_IDENTIFIER_LEN,
1172            "the worst legal image ARN is {} characters, which must fit the {MAX_IDENTIFIER_LEN} \
1173             identifier bound or the contradiction would be reachable rather than theoretical",
1174            worst.len(),
1175        );
1176    }
1177
1178    /// Every state set the client's loops branch on is a subset of the model's enum for it.
1179    ///
1180    /// **This is what moving the five state enums out of the drift script buys.** They were
1181    /// pinned against literals inside `tools/check-model-drift.py`, so a `MicrovmState` AWS
1182    /// respelled failed the gate with no consequence for the code that branches on it (issue
1183    /// #24). With the sets here, the same respelling fails this test as well, and this test names
1184    /// the loop.
1185    ///
1186    /// `microvms_core::control::microvm::SUSPEND_WANTED` is checked against the same enum in
1187    /// that module's tests, since this crate can't see it.
1188    ///
1189    /// **Guard proof.** Respell one member of `MICROVM_STATES` — `"SUSPENDED"` to
1190    /// `"SUSPEND_PENDING"`, say — and this fails naming `TERMINAL_STATES` and `DEAD_STATES` in
1191    /// turn, and core's test fails naming `SUSPEND_WANTED`. Drop `"PENDING"` from `BUILD_STATES` and the stall-probe
1192    /// assertion fails.
1193    #[test]
1194    fn every_state_set_the_polling_loops_use_is_a_subset_of_the_models_enum() {
1195        for state in TERMINAL_STATES {
1196            assert!(
1197                MICROVM_STATES.contains(&state),
1198                "TERMINAL_STATES has {state}, which is not a MicrovmState — \
1199                 ControlPlane::wait_for_running fails fast on it and would now never fire"
1200            );
1201        }
1202        for state in DEAD_STATES {
1203            assert!(
1204                MICROVM_STATES.contains(&state),
1205                "DEAD_STATES has {state}, which is not a MicrovmState — the resume path passes \
1206                 this set as its fail-fast list"
1207            );
1208        }
1209        for state in MODEL_IMAGE_READY_STATES {
1210            assert!(
1211                IMAGE_STATES.contains(&state),
1212                "MODEL_IMAGE_READY_STATES has {state}, which is not a MicrovmImageState — \
1213                 Image::is_ready would never answer true for it and a built image would poll to \
1214                 the 45-minute deadline"
1215            );
1216        }
1217        for state in TOLERATED_IMAGE_READY_STATES {
1218            assert!(
1219                !IMAGE_STATES.contains(&state),
1220                "{state} is in the model's enum now, so it is no longer a tolerated legacy \
1221                 spelling — promote it to MODEL_IMAGE_READY_STATES"
1222            );
1223        }
1224        // TRAP-2's stall probe compares `build_state == "PENDING"` against a literal. This is the
1225        // check that notices the literal going stale, which is the same class of bug as
1226        // `buildState`/`state` — dead against live AWS while its unit test passed.
1227        assert!(
1228            BUILD_STATES.contains(&"PENDING"),
1229            "the stall probe's replay signature is 'every build still PENDING'"
1230        );
1231        // `Image::is_failed` is a substring test on FAILED rather than a set, so that a fourth
1232        // failure spelling is still recognised. That reading has to stay true of the enum.
1233        let failed: Vec<&str> = IMAGE_STATES
1234            .iter()
1235            .copied()
1236            .filter(|state| state.contains("FAILED"))
1237            .collect();
1238        assert_eq!(
1239            failed,
1240            ["CREATE_FAILED", "UPDATE_FAILED", "DELETE_FAILED"],
1241            "the three spellings the substring test covers"
1242        );
1243    }
1244
1245    /// The tag character set: letters and digits in any script, spaces, and eight punctuation
1246    /// marks. Commas, `#`, `%`, and newlines are out.
1247    ///
1248    /// The non-Latin cases are the ones a byte-range matcher would have got wrong, and they are
1249    /// legitimate tags — `\p{L}` is every letter, not every ASCII letter. The newline case is the
1250    /// one `char::is_whitespace` would have got wrong in the other direction: `\n` is `\p{Cc}`,
1251    /// a control character, not the `\p{Z}` separator class the pattern names.
1252    #[test]
1253    fn a_tag_component_takes_any_script_and_eight_punctuation_marks() {
1254        for accepted in [
1255            "owner",
1256            "cost-centre",
1257            "cost centre",
1258            "team/agents",
1259            "a.b:c=d+e-f@g_h",
1260            "日本語",
1261            "café",
1262            "123",
1263            "",
1264        ] {
1265            assert!(is_valid_tag_component(accepted), "{accepted:?}");
1266        }
1267        for rejected in [
1268            "a,b",
1269            "a#b",
1270            "50%",
1271            "line\nbreak",
1272            "tab\there",
1273            "a!b",
1274            "a(b",
1275        ] {
1276            assert!(!is_valid_tag_component(rejected), "{rejected:?}");
1277        }
1278    }
1279
1280    /// The role-ARN matcher, and the twelve-digit account id is the part that earns it.
1281    ///
1282    /// Three real mistakes and one near-miss: a role name where an ARN was wanted, an ARN for
1283    /// another service, an account id with a digit dropped, and a `roleadmin` with no slash —
1284    /// which the model's regex accepts, so this does too rather than being stricter than the
1285    /// service on a value it has no other reason to inspect.
1286    #[test]
1287    fn a_role_arn_needs_twelve_account_digits_and_an_iam_role_path() {
1288        for accepted in [
1289            "arn:aws:iam::123456789012:role/build",
1290            "arn:aws:iam::123456789012:role/service-role/path/to/role",
1291            "arn:aws-us-gov:iam::123456789012:role/build",
1292            "arn:aws-cn:iam::123456789012:role/build",
1293            "arn:aws:iam::123456789012:role/name+with=every,allowed.char@here_x-y",
1294            // No slash: the model's `role/?` makes it optional, so this matches the pattern.
1295            "arn:aws:iam::123456789012:roleadmin",
1296        ] {
1297            assert!(is_valid_role_arn(accepted), "{accepted}");
1298        }
1299
1300        for rejected in [
1301            // A role *name*, which is the most common mistake.
1302            "bonk-sandbox-microvm-build",
1303            // The right shape for the wrong service.
1304            "arn:aws:lambda:us-east-1:123456789012:function:handler",
1305            // Eleven digits. The one nothing else catches.
1306            "arn:aws:iam::12345678901:role/build",
1307            // Thirteen.
1308            "arn:aws:iam::1234567890123:role/build",
1309            // Non-digits where the account goes.
1310            "arn:aws:iam::abcdefghijkl:role/build",
1311            // A region where IAM has none, which is what a copied Lambda ARN looks like.
1312            "arn:aws:iam:us-east-1:123456789012:role/build",
1313            // Nothing after `:role`.
1314            "arn:aws:iam::123456789012:role",
1315            "arn:aws:iam::123456789012:role/",
1316            // A user, not a role.
1317            "arn:aws:iam::123456789012:user/laith",
1318            // Uppercase partition, which the pattern's `[a-z\-]*` forbids.
1319            "arn:AWS:iam::123456789012:role/build",
1320            "",
1321            "arn:",
1322        ] {
1323            assert!(!is_valid_role_arn(rejected), "{rejected}");
1324        }
1325    }
1326
1327    /// The real conformance-account role ARNs match, which is what stops this guard from being a
1328    /// pattern that refuses every legitimate value.
1329    ///
1330    /// Written out as the account's actual ARNs rather than as a synthetic `role/build`: a
1331    /// matcher that accepts a fixture and refuses production is the failure mode a guard like this
1332    /// has, and it fires after the artifact upload.
1333    #[test]
1334    fn the_conformance_accounts_own_role_arns_are_accepted() {
1335        for real in [
1336            "arn:aws:iam::392583147479:role/bonk-sandbox-microvm-build",
1337            "arn:aws:iam::392583147479:role/bonk-sandbox-microvm-execution",
1338        ] {
1339            assert!(is_valid_role_arn(real), "{real}");
1340            assert!(real.len() >= MIN_ROLE_ARN_LEN, "{real}");
1341            assert!(real.len() <= MAX_ROLE_ARN_LEN, "{real}");
1342        }
1343    }
1344
1345    /// The two port constants bracket what a `u16` can hold, with the floor at 1 and not 0.
1346    ///
1347    /// `MAX_PORT` equalling `u16::MAX` is the fact that makes the ceiling closed by the type and
1348    /// the floor the only live half — which is what the guard's docs claim, asserted rather than
1349    /// stated.
1350    #[test]
1351    fn the_port_floor_is_one_and_the_ceiling_is_what_a_u16_holds() {
1352        assert_eq!(MIN_PORT, 1, "0 is 'let the kernel choose', not a port");
1353        assert_eq!(MAX_PORT, u16::MAX);
1354        assert_eq!(
1355            u32::from(MAX_PORT),
1356            MAX_HOOK_PORT,
1357            "PortNumber and HooksPortInteger agree today; they are two shapes and this is where \
1358             it is noticed if they stop"
1359        );
1360    }
1361
1362    /// The two `[^\s]+` shapes agree today, and the point of two constants is that this test is
1363    /// what says so rather than one constant making it unaskable.
1364    #[test]
1365    fn the_version_and_non_blank_shapes_agree_today_and_are_still_two_constants() {
1366        assert_eq!(MAX_VERSION_LEN, MAX_NON_BLANK_LEN);
1367        assert_eq!(VERSION_PATTERN, NON_BLANK_PATTERN);
1368        // Read out of the emitted object rather than compared as two `const`s, for the reason
1369        // the connector-ceiling test gives: a `const == const` assertion is decided at compile
1370        // time and proves nothing about the values the gate reads.
1371        let emitted = as_json();
1372        assert_eq!(emitted["MAX_VERSION_LEN"], emitted["MAX_NON_BLANK_LEN"]);
1373        assert_eq!(emitted["VERSION_PATTERN"], emitted["NON_BLANK_PATTERN"]);
1374    }
1375}