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/// 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 ([`crate::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/// [`crate::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/// [`crate::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 `scripts/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/// [`crate::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/// [`crate::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/// [`crate::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 [`crate::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: [`crate::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 [`crate::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 [`crate::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 as `sandbox.py` names them.
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 at least check the Rust and Python lists against each
637/// other, which is the one comparison available for a measured-only value.
638///
639/// # A list of pairs rather than one `json!({...})` literal, and that is forced
640///
641/// It was one object literal until issue #24's constants took the count past 40, at which
642/// point `json!` fails to compile: "recursion limit reached while expanding
643/// `$crate::json_internal!`", because the macro recurses once per entry against the crate's
644/// 128-deep default. The two ways out were a crate-wide `#![recursion_limit]` bump — a global
645/// knob turned for one macro in one function — and this. Each entry is still `json!(CONST)`, so
646/// every value is a function of the `pub const` above it, which is the property the gate rests
647/// on.
648pub fn as_json() -> Value {
649 let entries: Vec<(&str, Value)> = vec![
650 ("MODEL_API_VERSION", json!(MODEL_API_VERSION)),
651 (
652 "MAX_RUN_HOOK_PAYLOAD_BYTES",
653 json!(MAX_RUN_HOOK_PAYLOAD_BYTES),
654 ),
655 (
656 "DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES",
657 json!(DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES),
658 ),
659 ("MAX_IMAGE_NAME_LEN", json!(MAX_IMAGE_NAME_LEN)),
660 ("IMAGE_NAME_PATTERN", json!(IMAGE_NAME_PATTERN)),
661 ("MAX_VERSION_LEN", json!(MAX_VERSION_LEN)),
662 ("VERSION_PATTERN", json!(VERSION_PATTERN)),
663 ("MAX_NON_BLANK_LEN", json!(MAX_NON_BLANK_LEN)),
664 ("NON_BLANK_PATTERN", json!(NON_BLANK_PATTERN)),
665 ("MAX_IDENTIFIER_LEN", json!(MAX_IDENTIFIER_LEN)),
666 ("MAX_IMAGE_ARN_LEN", json!(MAX_IMAGE_ARN_LEN)),
667 ("MAX_TAG_KEY_LEN", json!(MAX_TAG_KEY_LEN)),
668 ("MAX_TAG_VALUE_LEN", json!(MAX_TAG_VALUE_LEN)),
669 ("TAG_COMPONENT_PATTERN", json!(TAG_COMPONENT_PATTERN)),
670 ("MAX_LOG_GROUP_LEN", json!(MAX_LOG_GROUP_LEN)),
671 ("LOG_GROUP_PATTERN", json!(LOG_GROUP_PATTERN)),
672 ("MAX_LOG_STREAM_LEN", json!(MAX_LOG_STREAM_LEN)),
673 ("LOG_STREAM_PATTERN", json!(LOG_STREAM_PATTERN)),
674 ("MAX_USER_LOG_STREAM_LEN", json!(MAX_USER_LOG_STREAM_LEN)),
675 ("MIN_ROLE_ARN_LEN", json!(MIN_ROLE_ARN_LEN)),
676 ("MAX_ROLE_ARN_LEN", json!(MAX_ROLE_ARN_LEN)),
677 ("ROLE_ARN_PATTERN", json!(ROLE_ARN_PATTERN)),
678 ("MIN_PORT", json!(MIN_PORT)),
679 ("MAX_PORT", json!(MAX_PORT)),
680 ("MIN_IDLE_DURATION_SEC", json!(MIN_IDLE_DURATION_SEC)),
681 ("MAX_DURATION_SEC", json!(MAX_DURATION_SEC)),
682 (
683 "MAX_MICROVM_HOOK_TIMEOUT_SEC",
684 json!(MAX_MICROVM_HOOK_TIMEOUT_SEC),
685 ),
686 (
687 "MAX_IMAGE_HOOK_TIMEOUT_SEC",
688 json!(MAX_IMAGE_HOOK_TIMEOUT_SEC),
689 ),
690 ("MAX_HOOK_PORT", json!(MAX_HOOK_PORT)),
691 ("CAPABILITIES", json!(CAPABILITIES)),
692 ("ARCHITECTURES", json!(ARCHITECTURES)),
693 ("MAX_NETWORK_CONNECTORS", json!(MAX_NETWORK_CONNECTORS)),
694 (
695 "MAX_IMAGE_EGRESS_CONNECTORS",
696 json!(MAX_IMAGE_EGRESS_CONNECTORS),
697 ),
698 ("IMAGE_VERSION_STATUSES", json!(IMAGE_VERSION_STATUSES)),
699 ("HOOK_STATES", json!(HOOK_STATES)),
700 ("MICROVM_STATES", json!(MICROVM_STATES)),
701 ("IMAGE_STATES", json!(IMAGE_STATES)),
702 ("IMAGE_VERSION_STATES", json!(IMAGE_VERSION_STATES)),
703 ("BUILD_STATES", json!(BUILD_STATES)),
704 ("CHIPSETS", json!(CHIPSETS)),
705 ("MAX_RESOURCES", json!(MAX_RESOURCES)),
706 ("MAX_CLIENT_TOKEN_LEN", json!(MAX_CLIENT_TOKEN_LEN)),
707 ("MODEL_IMAGE_READY_STATES", json!(MODEL_IMAGE_READY_STATES)),
708 (
709 "TOLERATED_IMAGE_READY_STATES",
710 json!(TOLERATED_IMAGE_READY_STATES),
711 ),
712 ("TERMINAL_STATES", json!(TERMINAL_STATES)),
713 ("DEAD_STATES", json!(DEAD_STATES)),
714 (
715 "MICROVM_REGIONS",
716 json!(
717 MICROVM_REGIONS
718 .iter()
719 .map(|region| region.as_str())
720 .collect::<Vec<_>>()
721 ),
722 ),
723 (
724 "SIZE_CLASSES",
725 json!(
726 crate::sizing::SIZE_CLASSES
727 .iter()
728 .map(|row| json!({
729 "baseline_mib": row.baseline_mib,
730 "baseline_vcpu": row.baseline_vcpu,
731 "peak_mib": row.peak_mib,
732 "peak_vcpu": row.peak_vcpu,
733 }))
734 .collect::<Vec<_>>()
735 ),
736 ),
737 ];
738 Value::Object(
739 entries
740 .into_iter()
741 .map(|(key, value)| (key.to_string(), value))
742 .collect(),
743 )
744}
745
746#[cfg(test)]
747mod tests {
748 use super::*;
749
750 /// The key set the drift gate reads, pinned.
751 ///
752 /// This is the guard for the one failure mode a rename here produces: the script
753 /// looks a key up, does not find it, and either crashes or — worse, depending on
754 /// how it is written — reports nothing disagreed. Compilation cannot catch that,
755 /// because the coupling is a string in another language's file.
756 #[test]
757 fn as_json_carries_every_key_the_drift_gate_reads() {
758 let emitted = as_json();
759 let object = emitted.as_object().expect("an object");
760 let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
761 keys.sort_unstable();
762 assert_eq!(
763 keys,
764 [
765 "ARCHITECTURES",
766 "BUILD_STATES",
767 "CAPABILITIES",
768 "CHIPSETS",
769 "DEAD_STATES",
770 "DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES",
771 "HOOK_STATES",
772 "IMAGE_NAME_PATTERN",
773 "IMAGE_STATES",
774 "IMAGE_VERSION_STATES",
775 "IMAGE_VERSION_STATUSES",
776 "LOG_GROUP_PATTERN",
777 "LOG_STREAM_PATTERN",
778 "MAX_CLIENT_TOKEN_LEN",
779 "MAX_DURATION_SEC",
780 "MAX_HOOK_PORT",
781 "MAX_IDENTIFIER_LEN",
782 "MAX_IMAGE_ARN_LEN",
783 "MAX_IMAGE_EGRESS_CONNECTORS",
784 "MAX_IMAGE_HOOK_TIMEOUT_SEC",
785 "MAX_IMAGE_NAME_LEN",
786 "MAX_LOG_GROUP_LEN",
787 "MAX_LOG_STREAM_LEN",
788 "MAX_MICROVM_HOOK_TIMEOUT_SEC",
789 "MAX_NETWORK_CONNECTORS",
790 "MAX_NON_BLANK_LEN",
791 "MAX_PORT",
792 "MAX_RESOURCES",
793 "MAX_ROLE_ARN_LEN",
794 "MAX_RUN_HOOK_PAYLOAD_BYTES",
795 "MAX_TAG_KEY_LEN",
796 "MAX_TAG_VALUE_LEN",
797 "MAX_USER_LOG_STREAM_LEN",
798 "MAX_VERSION_LEN",
799 "MICROVM_REGIONS",
800 "MICROVM_STATES",
801 "MIN_IDLE_DURATION_SEC",
802 "MIN_PORT",
803 "MIN_ROLE_ARN_LEN",
804 "MODEL_API_VERSION",
805 "MODEL_IMAGE_READY_STATES",
806 "NON_BLANK_PATTERN",
807 "ROLE_ARN_PATTERN",
808 "SIZE_CLASSES",
809 "TAG_COMPONENT_PATTERN",
810 "TERMINAL_STATES",
811 "TOLERATED_IMAGE_READY_STATES",
812 "VERSION_PATTERN",
813 ]
814 );
815 }
816
817 /// The values, as literals, against the same numbers `sandbox.py` carries. Written
818 /// out rather than compared against the constants, so this test disagrees with a
819 /// changed constant instead of following it.
820 #[test]
821 fn the_emitted_values_are_the_measured_ones() {
822 let emitted = as_json();
823 assert_eq!(emitted["MODEL_API_VERSION"], "2025-09-09");
824 assert_eq!(emitted["MAX_RUN_HOOK_PAYLOAD_BYTES"], 4096);
825 assert_eq!(emitted["MAX_IMAGE_NAME_LEN"], 64);
826 assert_eq!(emitted["IMAGE_NAME_PATTERN"], "[a-zA-Z0-9-_]+");
827 assert_eq!(emitted["MAX_VERSION_LEN"], 2048);
828 assert_eq!(emitted["VERSION_PATTERN"], "[^\\s]+");
829 assert_eq!(emitted["MAX_NON_BLANK_LEN"], 2048);
830 assert_eq!(emitted["NON_BLANK_PATTERN"], "[^\\s]+");
831 assert_eq!(emitted["MAX_IDENTIFIER_LEN"], 256);
832 assert_eq!(emitted["MAX_IMAGE_ARN_LEN"], 2048);
833 assert_eq!(emitted["MAX_TAG_KEY_LEN"], 128);
834 assert_eq!(emitted["MAX_TAG_VALUE_LEN"], 256);
835 assert_eq!(
836 emitted["TAG_COMPONENT_PATTERN"],
837 "([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)"
838 );
839 assert_eq!(emitted["MAX_LOG_GROUP_LEN"], 512);
840 assert_eq!(emitted["LOG_GROUP_PATTERN"], "[a-zA-Z0-9_\\-/.#]+");
841 assert_eq!(emitted["MAX_LOG_STREAM_LEN"], 512);
842 assert_eq!(emitted["LOG_STREAM_PATTERN"], "[^:*]*");
843 assert_eq!(emitted["MAX_USER_LOG_STREAM_LEN"], 495);
844 assert_eq!(emitted["MIN_ROLE_ARN_LEN"], 20);
845 assert_eq!(emitted["MAX_ROLE_ARN_LEN"], 2048);
846 assert_eq!(
847 emitted["ROLE_ARN_PATTERN"],
848 "arn:aws[a-z\\-]*:iam::[0-9]{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+"
849 );
850 assert_eq!(emitted["MIN_PORT"], 1);
851 assert_eq!(emitted["MAX_PORT"], 65_535);
852 assert_eq!(emitted["MIN_IDLE_DURATION_SEC"], 60);
853 assert_eq!(emitted["MAX_DURATION_SEC"], 28_800);
854 assert_eq!(emitted["MAX_MICROVM_HOOK_TIMEOUT_SEC"], 60);
855 assert_eq!(emitted["MAX_IMAGE_HOOK_TIMEOUT_SEC"], 3_600);
856 assert_eq!(emitted["MAX_HOOK_PORT"], 65_535);
857 assert_eq!(emitted["CAPABILITIES"], json!(["ALL"]));
858 assert_eq!(emitted["ARCHITECTURES"], json!(["ARM_64"]));
859 assert_eq!(emitted["MAX_NETWORK_CONNECTORS"], 10);
860 // 1, not 10. The image-level list and the VM-level one differ by an order of
861 // magnitude, and this is the assertion that says so in one place.
862 assert_eq!(emitted["MAX_IMAGE_EGRESS_CONNECTORS"], 1);
863 assert_eq!(
864 emitted["IMAGE_VERSION_STATUSES"],
865 json!(["ACTIVE", "INACTIVE"])
866 );
867 assert_eq!(emitted["HOOK_STATES"], json!(["DISABLED", "ENABLED"]));
868 assert_eq!(
869 emitted["MICROVM_STATES"],
870 json!([
871 "PENDING",
872 "RUNNING",
873 "SUSPENDING",
874 "SUSPENDED",
875 "TERMINATING",
876 "TERMINATED"
877 ])
878 );
879 assert_eq!(
880 emitted["IMAGE_STATES"],
881 json!([
882 "CREATING",
883 "CREATED",
884 "CREATE_FAILED",
885 "UPDATING",
886 "UPDATED",
887 "UPDATE_FAILED",
888 "DELETING",
889 "DELETE_FAILED",
890 "DELETED"
891 ])
892 );
893 assert_eq!(
894 emitted["IMAGE_VERSION_STATES"],
895 json!([
896 "PENDING",
897 "IN_PROGRESS",
898 "SUCCESSFUL",
899 "FAILED",
900 "DELETING",
901 "DELETED",
902 "DELETE_FAILED"
903 ])
904 );
905 assert_eq!(
906 emitted["BUILD_STATES"],
907 json!(["PENDING", "IN_PROGRESS", "SUCCESSFUL", "FAILED"])
908 );
909 assert_eq!(emitted["CHIPSETS"], json!(["GRAVITON"]));
910 assert_eq!(emitted["MAX_RESOURCES"], 1);
911 assert_eq!(emitted["MAX_CLIENT_TOKEN_LEN"], 128);
912 assert_eq!(
913 emitted["TERMINAL_STATES"],
914 json!(["TERMINATED", "TERMINATING", "SUSPENDED", "SUSPENDING"])
915 );
916 assert_eq!(emitted["DEAD_STATES"], json!(["TERMINATED", "TERMINATING"]));
917 assert_eq!(
918 emitted["MODEL_IMAGE_READY_STATES"],
919 json!(["CREATED", "UPDATED"])
920 );
921 assert_eq!(
922 emitted["TOLERATED_IMAGE_READY_STATES"],
923 json!(["ACTIVE", "AVAILABLE"])
924 );
925 assert_eq!(
926 emitted["MICROVM_REGIONS"],
927 json!([
928 "us-east-1",
929 "us-east-2",
930 "us-west-2",
931 "eu-west-1",
932 "ap-northeast-1"
933 ])
934 );
935 }
936
937 /// The object survives a serialize/parse cycle unchanged, which is what the gate
938 /// does to it: the CLI prints it and the script calls `json.loads`. A value that
939 /// only compares equal in memory is a value the gate never sees.
940 #[test]
941 fn the_emitted_object_round_trips_through_a_string() {
942 let emitted = as_json();
943 let text = serde_json::to_string(&emitted).expect("serializes");
944 let parsed: Value = serde_json::from_str(&text).expect("parses");
945 assert_eq!(parsed, emitted);
946 }
947
948 /// The dead states are a subset of the terminal ones, which is the relationship
949 /// the two lists exist to express. A DEAD_STATES entry that is not terminal would
950 /// make the launch guard and the resume guard disagree about what SUSPENDED means.
951 #[test]
952 fn every_dead_state_is_also_a_terminal_state() {
953 for state in DEAD_STATES {
954 assert!(TERMINAL_STATES.contains(&state), "{state} is not terminal");
955 }
956 assert!(
957 !DEAD_STATES.contains(&"SUSPENDED"),
958 "SUSPENDED is terminal but not dead: it is the state a resume is called from"
959 );
960 }
961
962 /// **Issue #24's wrong-by-10x hazard.** The two connector ceilings are different
963 /// numbers, and the image-level one is the smaller.
964 ///
965 /// Stated as an inequality rather than only as two literals above, because the failure
966 /// mode is a future edit that *unifies* them — "there is only one connector limit, delete
967 /// the duplicate" — and the permissive direction is the one that reaches the wire. A
968 /// caller who applied `MAX_NETWORK_CONNECTORS` to an image's `egressNetworkConnectors`
969 /// would accept ten and have the service refuse two.
970 #[test]
971 fn the_image_level_connector_ceiling_is_one_and_not_the_vm_levels_ten() {
972 assert_eq!(MAX_IMAGE_EGRESS_CONNECTORS, 1);
973 assert_eq!(MAX_NETWORK_CONNECTORS, 10);
974 // Read out of `as_json()` rather than compared as two `const`s, because clippy's
975 // `assertions_on_constants` is right that a `const < const` assertion is decided at
976 // compile time and proves nothing at runtime. Going through the emitted object makes it
977 // a real comparison — and it is the object the drift gate reads, so this asserts the
978 // published pair rather than two literals a reader could unify.
979 let emitted = as_json();
980 let image = emitted["MAX_IMAGE_EGRESS_CONNECTORS"]
981 .as_u64()
982 .expect("a number");
983 let vm = emitted["MAX_NETWORK_CONNECTORS"]
984 .as_u64()
985 .expect("a number");
986 assert!(
987 image < vm,
988 "collapsing the two would be permissive by 10x on the image-level list: \
989 {image} against {vm}"
990 );
991 }
992
993 /// The version statuses are exactly the two the model declares, spelled uppercase.
994 ///
995 /// The typed request-side spelling is checked against this array in
996 /// `crate::control::ops`, so the two cannot drift; here what is pinned is the pair itself
997 /// and the fact that neither is a lowercase or a past-tense variant of the other.
998 #[test]
999 fn the_two_version_statuses_are_active_and_inactive() {
1000 assert_eq!(IMAGE_VERSION_STATUSES, ["ACTIVE", "INACTIVE"]);
1001 for status in IMAGE_VERSION_STATUSES {
1002 assert_eq!(status, status.to_uppercase(), "{status}");
1003 }
1004 assert!(
1005 !IMAGE_VERSION_STATUSES.contains(&"DISABLED"),
1006 "DISABLED is HookState's spelling, not this enum's — mixing them is a \
1007 ValidationException on the only member the update request has"
1008 );
1009 }
1010
1011 /// The ready-state sets are disjoint, so the gate can check the model-derived one
1012 /// exactly. An overlap would mean a tolerated spelling was being presented as
1013 /// model-backed.
1014 #[test]
1015 fn the_model_and_tolerated_ready_states_do_not_overlap() {
1016 for state in TOLERATED_IMAGE_READY_STATES {
1017 assert!(
1018 !MODEL_IMAGE_READY_STATES.contains(&state),
1019 "{state} is claimed as both model-backed and tolerated"
1020 );
1021 }
1022 }
1023
1024 /// The pattern's four ranges and nothing else. The two rejected characters are the
1025 /// separators a caller reaching for a namespaced name writes first, which is why
1026 /// they are named.
1027 #[test]
1028 fn an_image_name_takes_letters_digits_hyphen_and_underscore_only() {
1029 assert!(is_valid_image_name("agentd-conformance_01"));
1030 assert!(is_valid_image_name("A"));
1031 assert!(is_valid_image_name(&"a".repeat(MAX_IMAGE_NAME_LEN)));
1032
1033 assert!(!is_valid_image_name(""), "min is 1");
1034 assert!(
1035 !is_valid_image_name(&"a".repeat(MAX_IMAGE_NAME_LEN + 1)),
1036 "65 characters is one past the ceiling"
1037 );
1038 for rejected in [
1039 "my.image",
1040 "team/image",
1041 "my image",
1042 "img!",
1043 "imagé",
1044 "img\n",
1045 ] {
1046 assert!(!is_valid_image_name(rejected), "{rejected}");
1047 }
1048 }
1049
1050 /// A multi-byte character cannot slip past the length check by being counted as
1051 /// one: the model's max is on bytes, and the character class rejects it anyway.
1052 #[test]
1053 fn a_multibyte_name_is_refused_by_the_character_class_not_by_luck() {
1054 assert!(!is_valid_image_name("é"));
1055 assert!(!is_valid_image_name("日本語"));
1056 }
1057
1058 /// The log-group matcher takes exactly the model's set — letters, digits, `_ - / . #` —
1059 /// and both length bounds.
1060 ///
1061 /// `/aws/lambda-microvms/img` is the shape the service itself creates, so it has to
1062 /// pass; a colon is the character a caller pasting an ARN brings in first, so it is the
1063 /// named rejection.
1064 #[test]
1065 fn a_log_group_takes_the_models_character_set_and_bounds() {
1066 assert!(is_valid_log_group("/aws/lambda-microvms/img"));
1067 assert!(is_valid_log_group("builds_2026.08#a"));
1068 assert!(is_valid_log_group(&"a".repeat(MAX_LOG_GROUP_LEN)));
1069
1070 assert!(!is_valid_log_group(""), "min is 1");
1071 assert!(
1072 !is_valid_log_group(&"a".repeat(MAX_LOG_GROUP_LEN + 1)),
1073 "513 characters is one past the ceiling"
1074 );
1075 for rejected in ["arn:aws:logs", "a group", "grp*", "grp\n", "imagé"] {
1076 assert!(!is_valid_log_group(rejected), "{rejected}");
1077 }
1078 }
1079
1080 /// The user-facing stream ceiling leaves exactly the discriminator's room under the
1081 /// wire ceiling: `/` plus sixteen hex characters.
1082 ///
1083 /// Pinned as arithmetic so a change to the nonce width (`token.rs`'s eight bytes) or to
1084 /// either ceiling fails here rather than as a `ValidationException` after the artifact
1085 /// upload — the same shape as `token.rs`'s own cap test.
1086 #[test]
1087 fn the_user_stream_ceiling_leaves_room_for_the_slash_and_sixteen_hex() {
1088 assert_eq!(MAX_USER_LOG_STREAM_LEN + 1 + 16, MAX_LOG_STREAM_LEN);
1089 }
1090
1091 /// **Issue #24's documentation trap, pinned as a comparison.** The model's own prose says
1092 /// 16,384 and its shape says 4096, and the shape is the one that is enforced.
1093 ///
1094 /// The pair is asserted rather than only commented because the failure mode is a future
1095 /// reader "correcting" [`MAX_RUN_HOOK_PAYLOAD_BYTES`] from the model's documentation string —
1096 /// which they would be able to cite while doing it. This test is what makes that a red build
1097 /// rather than a plausible-looking commit, and the 4x relationship is asserted so the shape of
1098 /// the hazard is in the test and not only in a doc comment.
1099 ///
1100 /// **Guard proof.** Set `MAX_RUN_HOOK_PAYLOAD_BYTES` to 16_384 and this fails on the
1101 /// inequality *and* on the ratio; delete `DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES` and it does not
1102 /// compile.
1103 #[test]
1104 fn the_models_own_prose_claims_four_times_the_ceiling_its_shape_states() {
1105 let emitted = as_json();
1106 let real = emitted["MAX_RUN_HOOK_PAYLOAD_BYTES"]
1107 .as_u64()
1108 .expect("a number");
1109 let documented = emitted["DOCUMENTED_RUN_HOOK_PAYLOAD_BYTES"]
1110 .as_u64()
1111 .expect("a number");
1112 assert_eq!(real, 4096, "the shape, which is what the service enforces");
1113 assert_eq!(
1114 documented, 16_384,
1115 "the model's documentation string on RunMicrovmRequest.runHookPayload"
1116 );
1117 assert!(
1118 documented > real,
1119 "the model's prose is permissive against its own shape: {documented} against {real}"
1120 );
1121 assert_eq!(
1122 documented / real,
1123 4,
1124 "wrong by 4x, in the direction that tells a caller four times as much secret \
1125 material fits as actually does"
1126 );
1127 }
1128
1129 /// **The model's identifier contradiction, pinned.** A legal `MicrovmImageArn` can be longer
1130 /// than a legal `MicrovmImageIdentifier`, so the service may answer with a value it would
1131 /// refuse as a request.
1132 ///
1133 /// Held as an inequality because the fact is a *relationship* between two shapes and no
1134 /// single shape states it. If AWS ever narrows `MicrovmImageArn` to 256 this goes red, which
1135 /// is the signal that the paragraph in [`MAX_IDENTIFIER_LEN`] about resolving the
1136 /// contradiction should be deleted.
1137 ///
1138 /// The second half is the reason it is theoretical in practice: a real ARN in the
1139 /// longest-named MicroVM region is nowhere near 256, and that arithmetic is measured here
1140 /// rather than asserted as a habit.
1141 #[test]
1142 fn a_legal_image_arn_can_be_longer_than_a_legal_identifier() {
1143 let emitted = as_json();
1144 let identifier = emitted["MAX_IDENTIFIER_LEN"].as_u64().expect("a number");
1145 let arn = emitted["MAX_IMAGE_ARN_LEN"].as_u64().expect("a number");
1146 assert!(
1147 arn > identifier,
1148 "the model permits a {arn}-character image ARN and a {identifier}-character \
1149 identifier, so a legal response value can be an illegal request value"
1150 );
1151
1152 // The worst legal real ARN: the longest region name, a twelve-digit account, and a
1153 // 64-character image name. Built rather than written as a literal, so the arithmetic is
1154 // the test's rather than mine.
1155 let longest_region = MICROVM_REGIONS
1156 .iter()
1157 .map(|region| region.as_str().len())
1158 .max()
1159 .expect("five regions");
1160 let worst = format!(
1161 "arn:aws:lambda:{}:{}:microvm-image:{}",
1162 "x".repeat(longest_region),
1163 "9".repeat(12),
1164 "a".repeat(MAX_IMAGE_NAME_LEN),
1165 );
1166 assert!(
1167 worst.len() <= MAX_IDENTIFIER_LEN,
1168 "the worst legal image ARN is {} characters, which must fit the {MAX_IDENTIFIER_LEN} \
1169 identifier bound or the contradiction would be reachable rather than theoretical",
1170 worst.len(),
1171 );
1172 }
1173
1174 /// Every state set the client's loops branch on is a subset of the model's enum for it.
1175 ///
1176 /// **This is what moving the five state enums out of the drift script buys.** They were
1177 /// pinned against literals inside `scripts/check-model-drift.py`, so a `MicrovmState` AWS
1178 /// respelled failed the gate with no consequence for the code that branches on it (issue
1179 /// #24). With the sets here, the same respelling fails this test as well, and this test names
1180 /// the loop.
1181 ///
1182 /// **Guard proof.** Respell one member of `MICROVM_STATES` — `"SUSPENDED"` to
1183 /// `"SUSPEND_PENDING"`, say — and this fails naming `TERMINAL_STATES`, `DEAD_STATES`, and
1184 /// `SUSPEND_WANTED` in turn. Drop `"PENDING"` from `BUILD_STATES` and the stall-probe
1185 /// assertion fails.
1186 #[test]
1187 fn every_state_set_the_polling_loops_use_is_a_subset_of_the_models_enum() {
1188 for state in TERMINAL_STATES {
1189 assert!(
1190 MICROVM_STATES.contains(&state),
1191 "TERMINAL_STATES has {state}, which is not a MicrovmState — \
1192 ControlPlane::wait_for_running fails fast on it and would now never fire"
1193 );
1194 }
1195 for state in DEAD_STATES {
1196 assert!(
1197 MICROVM_STATES.contains(&state),
1198 "DEAD_STATES has {state}, which is not a MicrovmState — the resume path passes \
1199 this set as its fail-fast list"
1200 );
1201 }
1202 for state in crate::control::microvm::SUSPEND_WANTED {
1203 assert!(
1204 MICROVM_STATES.contains(&state),
1205 "SUSPEND_WANTED has {state}, which is not a MicrovmState — a suspend would wait \
1206 for a state the service cannot report and time out"
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}