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