microvms_core/control/mod.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The control-plane client: SigV4-signed rest-json, and every trap closed before the
3//! request leaves the process.
4//!
5//! # The shape of the thing
6//!
7//! [`ControlPlane`] is the whole surface. It holds a [`transport::Transport`] (signed and
8//! real, or a contract recorder in a test), a [`Region`], and a [`Clock`] — and every
9//! operation is a method on it. There is no builder, no config struct, and no partially
10//! constructed state: [`ControlPlane::new`] resolves credentials and either yields a
11//! usable client or says why not.
12//!
13//! # What is closed here, and how strongly
14//!
15//! * **TRAP-1** — [`token`]: no `clientToken` parameter exists on any request type. S1.
16//! * **TRAP-2** — [`image`]: a build stuck in `CREATING` past the stall grace with every
17//! build `PENDING` is rejected naming the replay signature. S2.
18//! * **TRAP-3** — [`CreateImageRequest::repair_guest_identity`] is a `bool`, and the
19//! request injects `["ALL"]` itself. There is no capability list to put
20//! `CAP_SYS_ADMIN` in. S1.
21//! * **TRAP-4** — [`connector::ConnectorIntent`]: connectors are derived ARNs from a
22//! closed intent enum. S1.
23//! * **TRAP-5** — [`RunHookPayload`]: 4096 bytes inclusive, checked before any call. S2,
24//! and the type means an unchecked string cannot reach the field.
25//! * **TRAP-8** — [`ControlPlane::wait_for_running`]: a terminal state before RUNNING is
26//! rejected with the state *and* `stateReason` attached. S2.
27//! * **TRAP-11, revised again** — `mint_shell_auth_token` exists now, and the guard
28//! changed ground with it: the closure is no longer the method's absence but the exec
29//! path's separation from it, which is why the test still counts the calls a full
30//! lifecycle made and asserts zero shell operations among them. The connector half is
31//! unchanged: `SHELL_INGRESS` is a [`connector::ConnectorIntent`] variant, and the
32//! lifecycle test asserts a launch carries exactly the connectors its caller asked
33//! for. See [`connector`].
34//!
35//! # TRAP-11 is the one that needs saying out loud
36//!
37//! `CreateMicrovmShellAuthToken` is implemented — issue #69 builds `microvm shell` on
38//! it, and [`ControlPlane::mint_shell_auth_token`] is its one door. The original reason
39//! for staying away entirely — that the shell gates a console-only debugging flow, not
40//! a programmatic exec path — did not survive measurement: `docs/PLATFORM.md`
41//! (2026-08-15) found a real PTY over a WebSocket, programmatically drivable. What
42//! holds is narrower: **one interactive session is not programmatic exec** — no exec
43//! ids, no idempotency, no separated stdout/stderr, no exit codes — so the exec path
44//! never requests the shell connector and never mints a shell token, and the shell is
45//! its own surface ([`crate::session::shell`]) rather than a method the exec path can
46//! wander into.
47//!
48//! # Nothing in this module reads the service model at runtime
49//!
50//! Every constraint is a constant in [`crate::constants`], checked by the build gate
51//! against the pinned model (TRAP-12). That matters because botocore's
52//! `VALIDATED_METADATA_ATTRS` is `{required, min, document, union}` — `max`, `pattern`,
53//! and `enum` violations go to the wire — so every guard in this module is load-bearing
54//! rather than belt-and-braces, and "the SDK validates the model already" was never true.
55//!
56//! # And "botocore validates `min`" was never true *of this client*
57//!
58//! The sentence above is about `max`, `pattern`, and `enum`, and for a while it left `min`
59//! implicitly exempt: `min` **is** in `VALIDATED_METADATA_ATTRS`, so a `min` violation really is
60//! refused before the wire — by botocore. This client does not use botocore. It signs with
61//! `aws-sigv4` and sends with `reqwest`, and `validate.py` is nowhere in the dependency graph.
62//! That reasoning came from the deleted Python client, where it held, and it did not survive the
63//! port; issue #24 measured the consequence, `maxIdleDurationSeconds: 59` on the wire.
64//!
65//! So the rule is simpler than it was: **every constraint the model states on a member this
66//! client sends is enforced by this module or by nothing.** The guards below are the whole of it:
67//!
68//! * [`require_valid_image_name`] — `ImageName` (1..=64, `[a-zA-Z0-9-_]+`).
69//! * [`require_duration_in_range`] — `maximumDurationInSeconds` (1..=28800).
70//! * [`require_valid_version`] — `Version` (1..=2048, `[^\s]+`).
71//! * [`require_non_blank`] — `NonBlankString`, the model's most-reused shape.
72//! * [`require_valid_identifier`] — `MicrovmIdentifier`/`MicrovmImageIdentifier` (1..=256).
73//! * [`require_valid_role_arn`] — `RoleArn` (20..=2048, plus the twelve-digit account).
74//! * [`require_valid_port`] — `PortNumber`/`HooksPortInteger` (`min: 1`; 0 is not a port).
75//! * [`require_idle_duration`] — `maxIdleDurationSeconds` (`min: 60`).
76//! * [`require_valid_tags`] — `TagKey`/`TagValue`, two ceilings and two minima.
77//!
78//! Three constraints are closed by a **type** rather than by a function, which is the stronger
79//! form: [`RunHookPayload`] cannot hold over 4096 bytes, [`ops::VersionStatus`] and
80//! [`ops::HookState`] cannot spell a value the enum does not have, and
81//! [`connector::ConnectorIntent`] cannot name a connector the platform does not publish. A
82//! constraint the type system enforces cannot be forgotten at a call site.
83
84pub mod artifact;
85pub mod connector;
86pub mod image;
87pub mod microvm;
88pub mod ops;
89pub mod token;
90pub mod transport;
91
92use std::sync::Arc;
93use std::time::Duration;
94
95pub use artifact::{
96 BaseImage, Ecosystem, ProjectFiles, artifact_content_hash, build_artifact, default_dockerfile,
97};
98pub use connector::ConnectorIntent;
99pub use image::{Image, WaitOpts};
100pub use microvm::{Microvm, ProxyToken, RunHookPayload};
101
102use crate::error::{Error, ErrorKind};
103use crate::hooks::{BuildHookTimeout, RunHookTimeout};
104use crate::region::Region;
105use crate::sizing::SizeClass;
106
107/// The default agent port, matching the daemon's own default.
108pub const DEFAULT_AGENT_PORT: u16 = 9000;
109
110/// Monotonic time and sleeping, injectable so a wait can be tested without waiting.
111///
112/// # Why a trait rather than `tokio::time::pause`
113///
114/// Because the waits here are driven by *elapsed* comparisons against a deadline and a
115/// stall grace, and a test has to be able to say "now 300 seconds have passed" between two
116/// polls of a fake control plane. A paused tokio clock can do that, but only for code that
117/// sleeps on tokio — and it makes every test in the file share one global clock state.
118/// A [`Clock`] parameter makes the dependency visible in the signature.
119///
120/// Monotonic rather than wall-clock, and this is the same reasoning the Python client's
121/// injectable `time.monotonic` carries: the suspended window is a *duration*, and a wall
122/// clock that steps backward would reopen a closed one.
123pub trait Clock: Send + Sync {
124 /// Monotonic elapsed time since this clock started. Never decreases.
125 fn elapsed(&self) -> Duration;
126
127 /// Sleeps for `duration`.
128 fn sleep(
129 &self,
130 duration: Duration,
131 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>>;
132}
133
134/// The real clock: `Instant` and `tokio::time::sleep`.
135#[derive(Debug)]
136pub struct SystemClock {
137 started: std::time::Instant,
138}
139
140impl SystemClock {
141 pub fn new() -> Self {
142 Self {
143 started: std::time::Instant::now(),
144 }
145 }
146}
147
148impl Default for SystemClock {
149 fn default() -> Self {
150 Self::new()
151 }
152}
153
154impl Clock for SystemClock {
155 fn elapsed(&self) -> Duration {
156 self.started.elapsed()
157 }
158
159 fn sleep(
160 &self,
161 duration: Duration,
162 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
163 Box::pin(tokio::time::sleep(duration))
164 }
165}
166
167/// The control-plane client.
168///
169/// The transport and clock sit behind `Arc`, so a caller holding one across tasks does not
170/// need a second credential chain.
171pub struct ControlPlane {
172 transport: Arc<dyn transport::Transport>,
173 region: Region,
174 clock: Arc<dyn Clock>,
175 /// The agent port, which the hooks block and the proxy token both need.
176 port: u16,
177}
178
179impl std::fmt::Debug for ControlPlane {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 f.debug_struct("ControlPlane")
182 .field("region", &self.region)
183 .field("port", &self.port)
184 .finish_non_exhaustive()
185 }
186}
187
188impl ControlPlane {
189 /// Resolves credentials for `region` and returns a usable client.
190 ///
191 /// The region is a [`Region`], so an unsupported one is either a compile error or a
192 /// visible [`Region::unlisted`] at the call site — TRAP-6 is closed by the type before
193 /// this function is reached, which is why there is no region check here.
194 pub async fn new(region: Region) -> Result<Self, Error> {
195 let transport = transport::SignedTransport::new(region.clone()).await?;
196 Ok(Self {
197 transport: Arc::new(transport),
198 region,
199 clock: Arc::new(SystemClock::new()),
200 port: DEFAULT_AGENT_PORT,
201 })
202 }
203
204 /// A client over a caller-supplied transport and clock.
205 ///
206 /// The seam every test uses, and the reason it is public rather than `cfg(test)`: the
207 /// state-machine lane (T-W3-6) drives a `ControlPlane` and needs the same seam to test
208 /// its own lifecycle without AWS. A caller who passes a real transport here gets
209 /// exactly what [`ControlPlane::new`] builds.
210 pub fn with_transport(
211 transport: Arc<dyn transport::Transport>,
212 region: Region,
213 clock: Arc<dyn Clock>,
214 ) -> Self {
215 Self {
216 transport,
217 region,
218 clock,
219 port: DEFAULT_AGENT_PORT,
220 }
221 }
222
223 /// Sets the agent port the hooks block and the proxy token name.
224 ///
225 /// # Why this is fallible where every other builder method is not
226 ///
227 /// Because `port` is the one value on this type that the model bounds, and 0 is a value a
228 /// caller reaches for on purpose. `PortNumber` and `HooksPortInteger` are both `min: 1`;
229 /// `u16` closes the ceiling and nothing closed the floor, so before this returned a `Result`
230 /// the port set here landed in two places on the wire — `hooks.port` on every
231 /// `CreateMicrovmImage` built through the plane, and `allowedPorts: [{"port": 0}]` on every
232 /// token it minted (issue #24).
233 ///
234 /// Both of those are guarded at the call itself as well ([`require_valid_port`] in
235 /// [`ControlPlane::create_image`] and in [`ControlPlane::mint_auth_token_for`]), so the
236 /// constraint would be closed without this. It is fallible anyway because the two refusals
237 /// arrive a long way from the mistake: the create one after an artifact upload, and the mint
238 /// one at the moment a session needs a credential. Refusing here means `--port 0` fails
239 /// before a control plane is even usable, which is the difference between "that port is not
240 /// legal" and "your launch failed".
241 ///
242 /// Zero rather than the ceiling is what this actually catches, and it is not a typo case: 0
243 /// is what "let the kernel choose" means to a listener, so it is the value a caller passes
244 /// when they have a socket they have not bound yet.
245 pub fn with_port(mut self, port: u16) -> Result<Self, Error> {
246 require_valid_port("port", port)?;
247 self.port = port;
248 Ok(self)
249 }
250
251 /// The region every ARN in a request is derived for.
252 pub fn region(&self) -> &Region {
253 &self.region
254 }
255
256 /// The agent port.
257 pub fn port(&self) -> u16 {
258 self.port
259 }
260
261 pub(crate) fn transport(&self) -> &dyn transport::Transport {
262 self.transport.as_ref()
263 }
264
265 pub(crate) fn clock(&self) -> &dyn Clock {
266 self.clock.as_ref()
267 }
268}
269
270/// Everything `CreateMicrovmImage` needs, with the traps closed in the type.
271///
272/// # What is deliberately not here
273///
274/// A `client_token` field. See [`token`] for the fifteen-hour wedge that absence prevents;
275/// [`CreateImageRequest::token_scope`] is a **label** folded in beside a fresh nonce and
276/// cannot become the token.
277///
278/// A `capabilities` list. See `repair_guest_identity`.
279///
280/// An `architecture` field. The model's enum has exactly one value, so the only thing a
281/// field could express is a rejected request — and the rejection arrives *after* the
282/// artifact upload, reported as a constraint on a field the caller thought was a choice.
283/// `ARM_64` is injected. A caller who built an x86 binary finds out from `doctor`'s ELF
284/// check, not from a build cycle.
285#[derive(Clone, Debug)]
286pub struct CreateImageRequest {
287 /// The image name. Validated against `ImageName` (1..=64, `[a-zA-Z0-9-_]+`) before the
288 /// artifact is uploaded, because AWS's rejection arrives *after* the upload.
289 pub name: String,
290 /// The base image, pairing the `baseImageArn` with the Dockerfile `FROM`.
291 pub base_image: BaseImage,
292 /// `baseImageVersion`, or `None` to take whatever the service currently defaults to.
293 ///
294 /// # Why pinning is worth a field
295 ///
296 /// Without it a build floats. The managed base's version list is not static — `al2023-1`
297 /// carried one version in June and two by July (`"0"` and `"1"`, measured 2026-08-16) — so
298 /// two builds of identical inputs weeks apart can sit on different bases, and neither
299 /// recorded which. That is a reproducibility hole with no local symptom: the build
300 /// succeeds either way, and the difference appears in the guest.
301 ///
302 /// `None` is the default and stays the default, because pinning without knowing the legal
303 /// values is how a caller pins to a version that has been withdrawn.
304 /// [`ControlPlane::managed_base_versions`] is what answers that, and the version strings
305 /// are **bare integers** for a managed base where a custom image's are `"1.0"` — the two
306 /// are not comparable, so a value from anywhere else does not belong here.
307 ///
308 /// Checked against the `Version` shape before the call, because the create happens after
309 /// the artifact upload.
310 pub base_image_version: Option<String>,
311 /// The Dockerfile, or `None` for the derived default.
312 ///
313 /// A caller-supplied one is checked against `base_image`'s `docker_ref`: the two
314 /// disagreeing builds against a base none of the measured platform behaviour applies
315 /// to.
316 pub dockerfile: Option<String>,
317 /// The daemon binary's bytes, zipped into the artifact.
318 pub binary: Vec<u8>,
319 /// The project's dependency files — the lockfile plus its manifest — zipped into the
320 /// artifact beside the Dockerfile, or `None` for an image with no environment layer.
321 ///
322 /// This is what lets the derived Dockerfile's install step (`uv sync --locked`,
323 /// `npm ci`, `cargo fetch` per [`Ecosystem`]) see the files it installs from (#74).
324 /// The entry names are fixed by the ecosystem; there is no way to put an arbitrary
325 /// file into the shared snapshot through this field, which is the TRAP-5 property
326 /// restated as a type.
327 pub project_files: Option<ProjectFiles>,
328 /// Where the artifact is uploaded to. This client does not upload — S3 is not in the
329 /// crate's dependency set — so the caller puts the bytes there and passes the URI.
330 pub code_artifact_uri: String,
331 /// The build role, which must grant logs on `/aws/lambda-microvms/*`.
332 pub build_role_arn: String,
333 /// The size class. Selects a documented baseline; it does not size the VM (TRAP-10).
334 pub size: SizeClass,
335 /// Whether to repair guest identity (TRAP-3).
336 ///
337 /// # Why a bool and not a capability list
338 ///
339 /// Measured 2026-08-06: without the capability, a guest running as root still gets
340 /// `EPERM` from `sethostname` and from a bind mount over
341 /// `/proc/sys/kernel/random/boot_id`, because the MicroVM drops `CAP_SYS_ADMIN` by
342 /// default. Writing `/etc/machine-id` needs no capability and succeeds either way,
343 /// which is what makes the gap easy to miss — identity repair looks like it works
344 /// until you check the two steps that need the kernel's permission rather than the
345 /// filesystem's.
346 ///
347 /// `Capability`'s enum is exactly `["ALL"]`, so there is no way to ask for
348 /// `CAP_SYS_ADMIN` alone. A list parameter would let a caller write
349 /// `["CAP_SYS_ADMIN"]` — the request AWS rejects *after* the artifact upload — so the
350 /// intent is a boolean and the request injects `["ALL"]` itself.
351 pub repair_guest_identity: bool,
352 /// Whether the daemon should inherit the image's `WORKDIR`.
353 ///
354 /// Rejected when nothing declares one: most public ARM64 bases leave it empty, so the
355 /// inheritance silently resolves to `/` and the symptom appears in the guest a build
356 /// cycle later.
357 pub inherit_workdir: bool,
358 /// The run-family hook timeout: `run`, `resume`, `suspend`, `terminate`. Caps at 60s,
359 /// and the type is what keeps a build-sized value out of it.
360 pub run_hook_timeout: RunHookTimeout,
361 /// The build-family hook timeout: `ready`, `validate`. Caps at 3600s.
362 pub build_hook_timeout: BuildHookTimeout,
363 /// Tags, or none.
364 pub tags: std::collections::BTreeMap<String, String>,
365 /// `logging.cloudWatch.logGroup`, or `None` for the service default — a
366 /// service-created group under `/aws/lambda-microvms/<image-name>` with random stream
367 /// names.
368 ///
369 /// Checked against `CloudWatchLoggingLogGroupString` (1..=512, `[a-zA-Z0-9_\-/.#]+`)
370 /// before the artifact upload. The build role must be able to write to whatever this
371 /// names: the conformance account's role grants logs only on
372 /// `/aws/lambda-microvms/*`, so a group outside that prefix builds with no logs at
373 /// all — the same failure mode as the wrong-prefix policy (docs/PLATFORM.md).
374 pub log_group: Option<String>,
375 /// `logging.cloudWatch.logStream` — a stream-name **prefix**, never the exact name.
376 ///
377 /// # The client always appends a per-build discriminator
378 ///
379 /// The wire member is an EXACT stream name (prefixes unsupported — measured 2026-08,
380 /// docs/PLATFORM.md 'An image build is three VMs and three log streams'), and one
381 /// build emits three streams. A fixed configured name collapses all three of every
382 /// build into one stream, so [`ControlPlane::create_image`] sends
383 /// `<this>/<16 hex>` with fresh CSPRNG per create attempt — the same mechanism as
384 /// the `clientToken` nonce (TRAP-1) — and the resolved name comes back on
385 /// [`image::Image::log_stream`] so the caller can find their logs.
386 ///
387 /// Capped at [`crate::constants::MAX_USER_LOG_STREAM_LEN`] (495) so the resolved name
388 /// fits the shape's 512, and refused when it carries `:` or `*` (the pattern is
389 /// `[^:*]*`). Requires [`Self::log_group`]: a stream inside a group the service
390 /// chose randomly is a stream nobody can predict the location of.
391 pub log_stream: Option<String>,
392 /// A **label** folded into the create token for CloudTrail readability, defaulting to
393 /// the image name. Not the token, and cannot become it (TRAP-1).
394 pub token_scope: Option<String>,
395}
396
397impl CreateImageRequest {
398 /// A request with the measured defaults: the al2023 base, the default size class, the
399 /// derived Dockerfile, identity repair off, and 30-second hook timeouts.
400 ///
401 /// The hook timeouts are `expect`ed rather than propagated because 30 is legal for both
402 /// families by construction — it is below the run family's 60s ceiling, which is the
403 /// lower of the two — and a `Result` here would put a `?` on every call site for a
404 /// value this function chose itself.
405 pub fn new(
406 name: impl Into<String>,
407 binary: Vec<u8>,
408 code_artifact_uri: impl Into<String>,
409 build_role_arn: impl Into<String>,
410 ) -> Self {
411 Self {
412 name: name.into(),
413 base_image: BaseImage::al2023(),
414 base_image_version: None,
415 dockerfile: None,
416 binary,
417 project_files: None,
418 code_artifact_uri: code_artifact_uri.into(),
419 build_role_arn: build_role_arn.into(),
420 size: SizeClass::DEFAULT,
421 repair_guest_identity: false,
422 inherit_workdir: false,
423 run_hook_timeout: RunHookTimeout::try_new(30).expect("30s is under the 60s ceiling"),
424 build_hook_timeout: BuildHookTimeout::try_new(30)
425 .expect("30s is under the 3600s ceiling"),
426 tags: std::collections::BTreeMap::new(),
427 log_group: None,
428 log_stream: None,
429 token_scope: None,
430 }
431 }
432}
433
434/// Everything `RunMicrovm` needs.
435///
436/// `run_hook_payload` is a [`RunHookPayload`], which cannot hold an over-ceiling value —
437/// so TRAP-5 is closed before this struct exists rather than checked when it is used.
438#[derive(Clone, Debug)]
439pub struct RunMicrovmRequest {
440 /// The image ARN or ID to launch.
441 pub image_identifier: String,
442 /// `imageVersion`, or `None` for the image's own latest active version.
443 ///
444 /// # The launch half of blue/green
445 ///
446 /// `None` is what this client always sent, and it means "whatever
447 /// `latestActiveImageVersion` is now" — which is right for the ordinary case and wrong for
448 /// the two that matter. A canary wants to launch against exactly the version it is
449 /// testing, not against whatever became latest while it was starting. And a rollback wants
450 /// to re-pin to the known-good version, which "latest" cannot express at all once a bad
451 /// version is the latest one.
452 ///
453 /// With [`ControlPlane::set_image_version_status`] the three moves compose: build v2,
454 /// canary-launch pinned to v2, and on failure set v2 INACTIVE and re-pin to v1. A version
455 /// set INACTIVE refuses to launch when pinned here, which is what makes the retire real
456 /// rather than advisory.
457 ///
458 /// Checked against the `Version` shape before the call — see
459 /// [`require_valid_version`] on why a rollback is the worst moment for a rejection about
460 /// the request.
461 pub image_version: Option<String>,
462 /// The execution role. Optional in the model; every real launch needs one.
463 pub execution_role_arn: Option<String>,
464 /// The connectors to request, as intents (TRAP-4). Ingress is required for a session
465 /// to work at all; omitting egress is how you get no outbound network.
466 pub connectors: Vec<ConnectorIntent>,
467 /// The already-validated payload carrying the agent token.
468 pub run_hook_payload: RunHookPayload,
469 /// `maximumDurationInSeconds`, checked against 1..=28800 when the request is sent.
470 pub max_duration_sec: u32,
471 /// `idlePolicy.maxIdleDurationSeconds`, checked against the model's `min: 60` before the call.
472 ///
473 /// This comment used to say the guard was deliberately absent, because `min` is one of the four
474 /// keys botocore's `VALIDATED_METADATA_ATTRS` enforces locally. True of botocore, and this
475 /// client never touches it — see [`require_idle_duration`]. `59` reached the wire.
476 pub max_idle_sec: u32,
477 /// `idlePolicy.suspendedDurationSeconds`.
478 ///
479 /// The model's `min` is **0**, so every `u32` satisfies it and there is no guard — an absence
480 /// with a reason rather than an oversight, and the drift gate pins the 0 so a future floor is
481 /// noticed. Its ceiling is unstated.
482 ///
483 /// This value exists **only in the request** — the client is the only party that can
484 /// name the window it asked for, which is what STATE-12's refusal rests on.
485 pub suspended_sec: u32,
486 /// `idlePolicy.autoResumeEnabled`.
487 pub auto_resume: bool,
488 /// A label for the run token, defaulting to the image identifier (TRAP-1).
489 pub token_scope: Option<String>,
490}
491
492impl RunMicrovmRequest {
493 /// A launch with the measured defaults: ingress only, ten-minute idle and suspended
494 /// windows, a one-hour maximum duration, no auto-resume.
495 pub fn new(image_identifier: impl Into<String>, run_hook_payload: RunHookPayload) -> Self {
496 Self {
497 image_identifier: image_identifier.into(),
498 image_version: None,
499 execution_role_arn: None,
500 connectors: vec![ConnectorIntent::AllIngress],
501 run_hook_payload,
502 max_duration_sec: 3_600,
503 max_idle_sec: 600,
504 suspended_sec: 600,
505 auto_resume: false,
506 token_scope: None,
507 }
508 }
509
510 /// Adds the egress connector, which is what gives the VM outbound network.
511 #[must_use]
512 pub fn with_egress(mut self) -> Self {
513 if !self.connectors.contains(&ConnectorIntent::Egress) {
514 self.connectors.push(ConnectorIntent::Egress);
515 }
516 self
517 }
518
519 /// Requests a shell-capable launch: the ingress set becomes the measured pair,
520 /// `[HTTP_INGRESS, SHELL_INGRESS]`.
521 ///
522 /// **Replaces** `ALL_INGRESS` rather than adding beside it, because the platform
523 /// forbids the combination and says so only at token-mint time — the VM launches,
524 /// reaches RUNNING, and bills before the failure appears (`docs/PLATFORM.md`,
525 /// 2026-08-15). `[HTTP_INGRESS, SHELL_INGRESS]` is the set measured to both launch
526 /// and mint a shell token, and `HTTP_INGRESS` stays in the pair so the daemon
527 /// endpoint keeps working. Egress is untouched: shell access and outbound network
528 /// are separate questions.
529 #[must_use]
530 pub fn with_shell(mut self) -> Self {
531 self.connectors
532 .retain(|intent| *intent != ConnectorIntent::AllIngress);
533 for wanted in [ConnectorIntent::HttpIngress, ConnectorIntent::ShellIngress] {
534 if !self.connectors.contains(&wanted) {
535 self.connectors.push(wanted);
536 }
537 }
538 self
539 }
540
541 /// Pins the launch to one `imageVersion`. See the field for why that matters.
542 #[must_use]
543 pub fn with_image_version(mut self, version: impl Into<String>) -> Self {
544 self.image_version = Some(version.into());
545 self
546 }
547}
548
549/// Rejects a `maximumDurationInSeconds` outside the service range.
550///
551/// 28800 is eight hours and the hard ceiling on any single VM's life. A longer session
552/// needs a second VM, not a larger number — which is what the message says, because
553/// "outside the accepted range" alone invites someone to look for the flag that raises it.
554pub fn require_duration_in_range(seconds: u32) -> Result<u32, Error> {
555 if (1..=crate::constants::MAX_DURATION_SEC).contains(&seconds) {
556 return Ok(seconds);
557 }
558 Err(Error::invalid_arg(format!(
559 "maximumDurationInSeconds={seconds} is outside the accepted range 1..{} (service model \
560 {}) — {} seconds is eight hours, the hard ceiling on any one VM's life. A longer \
561 session needs a second VM, not a larger number.",
562 crate::constants::MAX_DURATION_SEC,
563 crate::constants::MODEL_API_VERSION,
564 crate::constants::MAX_DURATION_SEC,
565 )))
566}
567
568/// Rejects a `Version`/`NonBlankString` value the service would reject.
569///
570/// # Why this one is checked locally when so many are not
571///
572/// The model's `Version` shape is `min: 1, max: 2048, pattern: [^\s]+`, and issue #24 lists
573/// `NonBlankString` as its most-reused unguarded shape. Two of the three constraints are ones
574/// botocore would not catch even if this client used it (`max` and `pattern` are outside
575/// `VALIDATED_METADATA_ATTRS`), and this client uses `aws-sigv4` plus `reqwest` and never
576/// touches botocore's validator at all.
577///
578/// What makes it worth a guard rather than a comment is *where* the two callers sit.
579/// `CreateMicrovmImage.baseImageVersion` is sent **after** the artifact upload, so the
580/// service's rejection costs the caller the upload — the same argument
581/// [`require_valid_image_name`] makes. And `RunMicrovm.imageVersion` is the pinned-launch
582/// half of a rollback: a blank there is a `ValidationException` at the moment someone is
583/// trying to re-pin away from a bad version, which is the worst possible time for the failure
584/// to be about the request rather than about the version.
585///
586/// The pattern is `[^\s]+` — **no whitespace anywhere**, not merely "not blank". A version
587/// copied out of a terminal with a trailing newline satisfies "non-empty" and fails the
588/// pattern, so the message names the character rather than saying the value is invalid.
589pub fn require_valid_version(member: &str, version: &str) -> Result<(), Error> {
590 let model = crate::constants::MODEL_API_VERSION;
591 if version.is_empty() {
592 return Err(Error::invalid_arg(format!(
593 "{member} is empty, but the Version shape requires at least 1 character (service \
594 model {model}). Omit the member entirely to let the service choose — an absent \
595 version and a blank one are different requests, and only the first is legal."
596 )));
597 }
598 if version.len() > crate::constants::MAX_VERSION_LEN {
599 return Err(Error::invalid_arg(format!(
600 "{member} is {} characters, over the Version ceiling of {} (service model {model}).",
601 version.len(),
602 crate::constants::MAX_VERSION_LEN,
603 )));
604 }
605 if let Some(found) = version.chars().find(char::is_ascii_whitespace) {
606 return Err(Error::invalid_arg(format!(
607 "{member} {version:?} contains whitespace ({found:?}), which the Version pattern \
608 {:?} forbids anywhere in the value (service model {model}). A version pasted from \
609 a terminal carries a trailing newline and looks fine; this is that.",
610 crate::constants::VERSION_PATTERN,
611 )));
612 }
613 Ok(())
614}
615
616/// Rejects a `NonBlankString` value the service would reject.
617///
618/// # The model's most-reused shape, and the three members this client sends
619///
620/// `NonBlankString` is `min: 1, max: 2048, pattern: [^\s]+` and 45 members name it. Most are
621/// responses; the three this client puts on the wire are `CodeArtifact.uri`,
622/// `CreateMicrovmImage.baseImageArn`, and `ListMicrovmImages.nameFilter`, and issue #24 named
623/// all three as reachable with no guard.
624///
625/// Each of the three fails in its own expensive way. `codeArtifact.uri` and `baseImageArn` ride
626/// on the create call, which happens **after** the artifact upload — the ordering
627/// [`ControlPlane::create_image`] is arranged around, so a rejection about either costs the
628/// caller the upload. `nameFilter` is worse in a quieter way: it goes in the **query string**,
629/// so a blank one is a `nameFilter=` that either 400s or silently filters differently from what
630/// was meant, and [`ControlPlane::find_image_by_name`] is the resolver a launch depends on.
631///
632/// # `[^\s]+` forbids whitespace *anywhere*
633///
634/// Not merely "not blank". An S3 URI pasted from a console with a trailing newline satisfies
635/// "non-empty" and fails the pattern, which is why the message names the character it found
636/// rather than saying the value is invalid. The same reading [`require_valid_version`] documents
637/// for `Version`, which is the identical constraint triple on a different shape.
638///
639/// A separate function from [`require_valid_version`] even though the two shapes agree today,
640/// for the reason [`crate::constants::MAX_NON_BLANK_LEN`] gives: they are two shapes, AWS can
641/// move one, and one guard serving both would silently stop being about whichever moved.
642pub fn require_non_blank(member: &str, value: &str) -> Result<(), Error> {
643 let model = crate::constants::MODEL_API_VERSION;
644 if value.is_empty() {
645 return Err(Error::invalid_arg(format!(
646 "{member} is empty, but the NonBlankString shape requires at least 1 character \
647 (service model {model}). The shape's own documentation reads 'a string which is not \
648 empty or blank (only whitespace)'."
649 )));
650 }
651 if value.len() > crate::constants::MAX_NON_BLANK_LEN {
652 return Err(Error::invalid_arg(format!(
653 "{member} is {} characters, over the NonBlankString ceiling of {} (service model \
654 {model}).",
655 value.len(),
656 crate::constants::MAX_NON_BLANK_LEN,
657 )));
658 }
659 if let Some(found) = value.chars().find(char::is_ascii_whitespace) {
660 return Err(Error::invalid_arg(format!(
661 "{member} {value:?} contains whitespace ({found:?}), which the NonBlankString \
662 pattern {:?} forbids anywhere in the value (service model {model}). A URI pasted \
663 from a console carries a trailing newline and looks fine; this is that.",
664 crate::constants::NON_BLANK_PATTERN,
665 )));
666 }
667 Ok(())
668}
669
670/// Rejects a `MicrovmIdentifier`/`MicrovmImageIdentifier` the service would reject.
671///
672/// # Twelve members across every implemented operation
673///
674/// Both shapes are `min: 1, max: 256`, and between them they bound the identifier on
675/// `GetMicrovm`, `SuspendMicrovm`, `ResumeMicrovm`, `TerminateMicrovm`,
676/// `CreateMicrovmAuthToken`, `GetMicrovmImage`, `DeleteMicrovmImage`,
677/// `DeleteMicrovmImageVersion`, `GetMicrovmImageVersion`, `UpdateMicrovmImageVersion`,
678/// `GetMicrovmImageBuild`, the three listings, and `RunMicrovm.imageIdentifier`. Issue #24
679/// counted six implemented operations for each shape; every one of them is guarded here.
680///
681/// # An empty identifier is the case that pays for this
682///
683/// Ten of those members are **URI parameters**, and an empty one does not produce a validation
684/// error about a blank field: it collapses the path. `GET /2025-09-09/microvms/` addresses the
685/// *listing*, not a VM, so an empty id sent to `get_microvm` asks a different question and can
686/// get a 200 back for it — and `DELETE` on a collapsed path is worse. That failure mode is
687/// invisible in the service's answer, which is the strongest argument for a local refusal
688/// anywhere in this module.
689///
690/// # The model contradicts itself, and this is the side that can be guarded
691///
692/// `MicrovmImageArn` permits 2048 and is what the service *answers* with, so the model allows a
693/// legal response value that is an illegal request value — see
694/// [`crate::constants::MAX_IDENTIFIER_LEN`] for the whole account. The message says so, because
695/// a caller who hit it by echoing an ARN back is looking at a service inconsistency rather than
696/// at their own mistake, and telling them "shorten it" would be useless advice about a value
697/// they did not choose.
698pub fn require_valid_identifier(member: &str, identifier: &str) -> Result<(), Error> {
699 let model = crate::constants::MODEL_API_VERSION;
700 if identifier.is_empty() {
701 return Err(Error::invalid_arg(format!(
702 "{member} is empty, but the identifier shapes require at least 1 character (service \
703 model {model}). An empty identifier is not refused as a blank field — most of these \
704 are URI parameters, so it collapses the path onto the collection: \
705 `/microvms/` is the listing rather than one VM, and a request that addresses the \
706 wrong resource can succeed."
707 )));
708 }
709 if identifier.len() > crate::constants::MAX_IDENTIFIER_LEN {
710 return Err(Error::invalid_arg(format!(
711 "{member} is {} characters, over the {} the MicrovmIdentifier and \
712 MicrovmImageIdentifier shapes allow (service model {model}). Note the model \
713 disagrees with itself here: MicrovmImageArn permits {}, and that is the shape the \
714 service answers with on GetMicrovm's imageArn — so if this value came back from a \
715 response rather than being chosen here, it is a service-side inconsistency worth \
716 reporting rather than a length to shorten.",
717 identifier.len(),
718 crate::constants::MAX_IDENTIFIER_LEN,
719 crate::constants::MAX_IMAGE_ARN_LEN,
720 )));
721 }
722 Ok(())
723}
724
725/// Rejects a `RoleArn` the service would reject, before the artifact upload.
726///
727/// # Why the build role in particular
728///
729/// `CreateMicrovmImage.buildRoleArn` is sent on the create call, and the create call happens
730/// **after** the caller has uploaded the artifact. So the service's rejection of a malformed
731/// role ARN arrives having already cost the upload, which is the exact ordering
732/// [`ControlPlane::create_image`] exists to protect against and the reason issue #24 singled
733/// this member out. `RunMicrovm.executionRoleArn` is cheaper to get wrong but wrong in a
734/// confusing place: it is optional in the model, so a malformed one is a `ValidationException`
735/// on a member a caller may not know is being filled from their infra config.
736///
737/// # Three constraints, three messages
738///
739/// `min: 20`, `max: 2048`, and the pattern. They get separate messages because the pattern's
740/// wording ("this does not look like an IAM role ARN") is unhelpful for a value that is merely
741/// 3000 characters, and the length wording is unhelpful for a role *name* — which is the most
742/// common mistake and is short.
743///
744/// See [`crate::constants::is_valid_role_arn`] for what the structural check decides. It cannot
745/// tell you the role exists or grants the right log permissions; those are the failures that
746/// actually happen most and none of them is knowable without IAM.
747pub fn require_valid_role_arn(member: &str, arn: &str) -> Result<(), Error> {
748 let model = crate::constants::MODEL_API_VERSION;
749 if arn.len() < crate::constants::MIN_ROLE_ARN_LEN {
750 return Err(Error::invalid_arg(format!(
751 "{member} {arn:?} is {} characters, under the RoleArn minimum of {} (service model \
752 {model}). A value this short is almost always a role *name* where the ARN was \
753 wanted — `arn:aws:iam::<12-digit-account>:role/{arn}` is the shape.",
754 arn.len(),
755 crate::constants::MIN_ROLE_ARN_LEN,
756 )));
757 }
758 if arn.len() > crate::constants::MAX_ROLE_ARN_LEN {
759 return Err(Error::invalid_arg(format!(
760 "{member} is {} characters, over the RoleArn ceiling of {} (service model {model}).",
761 arn.len(),
762 crate::constants::MAX_ROLE_ARN_LEN,
763 )));
764 }
765 if !crate::constants::is_valid_role_arn(arn) {
766 return Err(Error::invalid_arg(format!(
767 "{member} {arn:?} does not match the RoleArn pattern {:?} (service model {model}). \
768 It wants `arn:aws:iam::` then **exactly twelve digits** of account id then `:role/` \
769 and a name — so the three things this catches are a role name passed as an ARN, an \
770 ARN for some other service, and an account id with a digit dropped. Rejected here \
771 rather than by AWS because for buildRoleArn the create call happens *after* the \
772 artifact upload, so the service's answer costs you the upload first. Whether the \
773 role exists and grants logs on {}/* is not checkable locally and is still the \
774 service's answer to give.",
775 crate::constants::ROLE_ARN_PATTERN,
776 image::BUILD_LOG_GROUP_PREFIX,
777 )));
778 }
779 Ok(())
780}
781
782/// Rejects a `logging.cloudWatch.logGroup` the service would reject, before the artifact
783/// upload.
784///
785/// The shape is `CloudWatchLoggingLogGroupString`: 1..=512, pattern `[a-zA-Z0-9_\-/.#]+`.
786/// The character the pattern excludes that a caller writes first is the colon — a group
787/// pasted as an ARN (`arn:aws:logs:...`) fails here with the pattern named, rather than as
788/// a `ValidationException` after the upload.
789pub fn require_valid_log_group(group: &str) -> Result<(), Error> {
790 let model = crate::constants::MODEL_API_VERSION;
791 if group.is_empty() {
792 return Err(Error::invalid_arg(format!(
793 "logging.cloudWatch.logGroup is empty, but the CloudWatchLoggingLogGroupString \
794 shape requires at least 1 character (service model {model}). Omit the setting \
795 entirely to take the service default — a service-created group under \
796 {}/<image-name>.",
797 image::BUILD_LOG_GROUP_PREFIX,
798 )));
799 }
800 if group.len() > crate::constants::MAX_LOG_GROUP_LEN {
801 return Err(Error::invalid_arg(format!(
802 "logging.cloudWatch.logGroup is {} characters, over the \
803 CloudWatchLoggingLogGroupString ceiling of {} (service model {model}).",
804 group.len(),
805 crate::constants::MAX_LOG_GROUP_LEN,
806 )));
807 }
808 if !crate::constants::is_valid_log_group(group) {
809 return Err(Error::invalid_arg(format!(
810 "logging.cloudWatch.logGroup {group:?} does not match the \
811 CloudWatchLoggingLogGroupString pattern {:?} (service model {model}) — letters, \
812 digits, and `_ - / . #` only. A colon usually means an ARN was pasted where the \
813 group *name* was wanted. Rejected here rather than by AWS because the create call \
814 happens after the artifact upload, so the service's answer costs you the upload \
815 first.",
816 crate::constants::LOG_GROUP_PATTERN,
817 )));
818 }
819 Ok(())
820}
821
822/// Rejects a caller-supplied `logging.cloudWatch.logStream` prefix the resolved name could
823/// not legally carry, before the artifact upload.
824///
825/// The shape is `CloudWatchLoggingLogStreamString`: 1..=512, pattern `[^:*]*` — anything
826/// but `:` and `*`. The caller's value is capped at
827/// [`crate::constants::MAX_USER_LOG_STREAM_LEN`] (495) rather than 512, because this
828/// client always appends `/<16 hex>` of per-build discriminator before the value reaches
829/// the wire — see [`CreateImageRequest::log_stream`] for why a verbatim stream name is
830/// never sent — and 495 + 17 is exactly the shape's ceiling.
831pub fn require_valid_log_stream(stream: &str) -> Result<(), Error> {
832 let model = crate::constants::MODEL_API_VERSION;
833 if stream.is_empty() {
834 return Err(Error::invalid_arg(format!(
835 "logging.cloudWatch.logStream is empty, but the CloudWatchLoggingLogStreamString \
836 shape requires at least 1 character (service model {model}). Omit the setting to \
837 let the service name the streams inside the configured group."
838 )));
839 }
840 if stream.len() > crate::constants::MAX_USER_LOG_STREAM_LEN {
841 return Err(Error::invalid_arg(format!(
842 "logging.cloudWatch.logStream is {} characters, over this client's ceiling of {}. \
843 The shape's own ceiling is {} (service model {model}), and the client always \
844 appends a 17-character per-build discriminator (`/` + 16 hex) — one image build \
845 is three VMs writing three streams, and the member is an exact stream name, so a \
846 fixed configured name would collapse every build's streams into one. The \
847 discriminator is what keeps them tellable apart, and it needs its room.",
848 stream.len(),
849 crate::constants::MAX_USER_LOG_STREAM_LEN,
850 crate::constants::MAX_LOG_STREAM_LEN,
851 )));
852 }
853 if let Some(found) = stream.chars().find(|c| matches!(c, ':' | '*')) {
854 return Err(Error::invalid_arg(format!(
855 "logging.cloudWatch.logStream {stream:?} contains {found:?}, which the \
856 CloudWatchLoggingLogStreamString pattern {:?} forbids anywhere in the value \
857 (service model {model}). A `*` usually means a prefix or glob was intended — the \
858 member is an exact stream name, prefixes are unsupported, and this client's own \
859 per-build suffix is how a configured name behaves like one.",
860 crate::constants::LOG_STREAM_PATTERN,
861 )));
862 }
863 Ok(())
864}
865
866/// Rejects a port the `PortNumber` or `HooksPortInteger` shapes would reject. **Minimum 1.**
867///
868/// # Port 0 is representable and means something else
869///
870/// Zero is what "let the kernel pick a port" means to a listener, so it is the value a caller
871/// reaches for when they do not have a port yet — and issue #24 measured that
872/// [`ControlPlane::with_port`]`(0)` was representable and produced `allowedPorts: [{"port": 0}]`
873/// on the wire, plus a `hooks.port` of 0 on every image built through that plane. Neither is a
874/// port the platform can forward to.
875///
876/// # There is no ceiling check here, and that is the type's doing rather than an omission
877///
878/// `PortNumber.max` and `HooksPortInteger.max` are both 65535, which is `u16::MAX` — so a `max`
879/// branch against the constant would be `port > u16::MAX`, a comparison that is false for every
880/// input. Clippy's `absurd_extreme_comparisons` says so, and it is right for the reason
881/// [`ControlPlane::create_image`] gives about the absent `hooks.port` check: a branch no input can
882/// reach reads as protection, appears in a coverage report as protection, and no test can make it
883/// fire.
884///
885/// The ceiling is still *pinned* — [`crate::constants::MAX_PORT`] is in the drift gate, and
886/// `the_port_floor_is_one_and_the_ceiling_is_what_a_u16_holds` asserts the equality with
887/// `u16::MAX` that makes this reasoning valid. If AWS ever lowers the ceiling below 65535 the gate
888/// goes red, that test goes red, and a real branch belongs here.
889pub fn require_valid_port(member: &str, port: u16) -> Result<(), Error> {
890 if port >= crate::constants::MIN_PORT {
891 return Ok(());
892 }
893 Err(Error::invalid_arg(format!(
894 "{member} is {port}, under the PortNumber minimum of {} (service model {}). Port 0 means \
895 'let the kernel choose' to a listener and is not a port the platform can forward to — a \
896 proxy token minted for it authorizes nothing, and an image whose hooks block names it has \
897 no reachable hook endpoint. Name the port the daemon actually listens on \
898 ({DEFAULT_AGENT_PORT} by default).",
899 crate::constants::MIN_PORT,
900 crate::constants::MODEL_API_VERSION,
901 )))
902}
903
904/// Rejects an `idlePolicy.maxIdleDurationSeconds` under the model's `min: 60`.
905///
906/// # The exemption this replaces was inherited from a client that no longer exists
907///
908/// [`RunMicrovmRequest::max_idle_sec`] and `constants.rs` both used to say there was
909/// deliberately no guard here, because `min` is one of the four keys in botocore's
910/// `VALIDATED_METADATA_ATTRS` and botocore therefore refuses it locally with a clear message.
911/// The premise is true and the conclusion does not apply: this client never touches botocore.
912/// `ControlPlane` signs with `aws-sigv4` and sends with `reqwest`, so `validate.py` is not on
913/// the path, and issue #24 measured `max_idle_sec: 59` reaching the wire.
914///
915/// It is the one place in this module where the *reason* for having no guard was wrong rather
916/// than the number, which is worth saying because the same reasoning would exempt every `min` in
917/// the model — `Version`'s, `NonBlankString`'s, the identifiers', `allowedPorts`'s. All of them
918/// are now guarded, and none of them by botocore.
919///
920/// No maximum, because the model states none. The bound that actually ends a VM's life is
921/// `maximumDurationInSeconds` ([`require_duration_in_range`]).
922pub fn require_idle_duration(seconds: u32) -> Result<(), Error> {
923 if seconds >= crate::constants::MIN_IDLE_DURATION_SEC {
924 return Ok(());
925 }
926 Err(Error::invalid_arg(format!(
927 "idlePolicy.maxIdleDurationSeconds={seconds} is under the minimum of {} (service model \
928 {}). This used to be documented as a constraint botocore enforced locally, which was \
929 true of the deleted Python client and never of this one — it signs with aws-sigv4 and \
930 sends with reqwest, so nothing validates a request before the wire except this crate.",
931 crate::constants::MIN_IDLE_DURATION_SEC,
932 crate::constants::MODEL_API_VERSION,
933 )))
934}
935
936/// Rejects a tag map the service would reject, naming the key and the half that failed.
937///
938/// # Sent since tags existed, checked by nothing
939///
940/// [`CreateImageRequest::tags`] goes straight onto `CreateMicrovmImage.tags` and was never
941/// validated (issue #24). Same ordering argument as everything else on that call: the rejection
942/// lands after the artifact upload.
943///
944/// # The key and the value have different rules, so the message says which
945///
946/// `TagKey` is `min: 1, max: 128`; `TagValue` is `min: 0, max: 256`. So an empty **value** is
947/// legal and an empty **key** is not, and the ceilings differ by 2x. They share one pattern.
948/// Every message here names the offending key, because a caller applying a dozen tags from a
949/// config file needs to know which one — a message that only said "a tag is invalid" would send
950/// them to read all twelve.
951///
952/// The key is quoted in the message even when the key itself is the problem, which is the
953/// deliberate choice: a key with a stray newline or a zero-width character in it is
954/// indistinguishable from a good one until it is printed with `{:?}`.
955pub fn require_valid_tags(tags: &std::collections::BTreeMap<String, String>) -> Result<(), Error> {
956 let model = crate::constants::MODEL_API_VERSION;
957 for (key, value) in tags {
958 if key.is_empty() {
959 return Err(Error::invalid_arg(format!(
960 "a tag key is empty, but TagKey requires at least 1 character (service model \
961 {model}). Note TagValue's minimum is 0, so an empty tag *value* is legal and an \
962 empty key is not."
963 )));
964 }
965 if key.len() > crate::constants::MAX_TAG_KEY_LEN {
966 return Err(Error::invalid_arg(format!(
967 "the tag key {key:?} is {} characters, over the TagKey ceiling of {} (service \
968 model {model}). TagValue allows {}, so the two halves are not \
969 interchangeable.",
970 key.len(),
971 crate::constants::MAX_TAG_KEY_LEN,
972 crate::constants::MAX_TAG_VALUE_LEN,
973 )));
974 }
975 if !crate::constants::is_valid_tag_component(key) {
976 return Err(Error::invalid_arg(format!(
977 "the tag key {key:?} has a character outside the TagKey pattern {:?} (service \
978 model {model}). Letters, digits, separators, and `_ . : / = + - @` — spaces and \
979 non-Latin scripts are fine, commas and `#` and `%` are not, and neither is a \
980 newline (it is a control character, not a separator).",
981 crate::constants::TAG_COMPONENT_PATTERN,
982 )));
983 }
984 if value.len() > crate::constants::MAX_TAG_VALUE_LEN {
985 return Err(Error::invalid_arg(format!(
986 "the value of tag {key:?} is {} characters, over the TagValue ceiling of {} \
987 (service model {model}).",
988 value.len(),
989 crate::constants::MAX_TAG_VALUE_LEN,
990 )));
991 }
992 if !crate::constants::is_valid_tag_component(value) {
993 return Err(Error::invalid_arg(format!(
994 "the value of tag {key:?} has a character outside the TagValue pattern {:?} \
995 (service model {model}). It is the same character set the key takes; the value \
996 differs only in allowing an empty string.",
997 crate::constants::TAG_COMPONENT_PATTERN,
998 )));
999 }
1000 }
1001 Ok(())
1002}
1003
1004/// Rejects an image name the service would reject, before the artifact upload.
1005///
1006/// The three cases get their own messages because the pattern message ("no dots, no
1007/// slashes") is actively misleading for a 70-character name that contains neither.
1008pub fn require_valid_image_name(name: &str) -> Result<(), Error> {
1009 let model = crate::constants::MODEL_API_VERSION;
1010 if name.is_empty() {
1011 return Err(Error::invalid_arg(format!(
1012 "the image name is empty, but ImageName requires at least 1 character (service \
1013 model {model})."
1014 )));
1015 }
1016 if name.len() > crate::constants::MAX_IMAGE_NAME_LEN {
1017 return Err(Error::invalid_arg(format!(
1018 "the image name is {} characters, over the ImageName ceiling of {} (service model \
1019 {model}). Rejected here rather than by AWS, because the create call happens \
1020 *after* the artifact upload — so the service's answer costs you the upload first.",
1021 name.len(),
1022 crate::constants::MAX_IMAGE_NAME_LEN,
1023 )));
1024 }
1025 if !crate::constants::is_valid_image_name(name) {
1026 return Err(Error::invalid_arg(format!(
1027 "the image name {name:?} does not match the ImageName pattern {:?} (service model \
1028 {model}). Letters, digits, hyphen, and underscore only — no dots and no slashes, \
1029 which are the two separators a namespaced name reaches for first.",
1030 crate::constants::IMAGE_NAME_PATTERN,
1031 )));
1032 }
1033 Ok(())
1034}
1035
1036/// The `Hooks` block with all six hooks enabled and both timeout families set.
1037///
1038/// All six because `ready` and `validate` are image-*build* hooks: the build calls them to
1039/// decide whether the snapshot it just produced is usable, before any instance exists and
1040/// therefore before any token has been delivered. Gating them on bootstrap state fails the
1041/// *build* rather than the run, which is a confusing place to discover the mistake.
1042///
1043/// The two timeouts are separate types, so the 60x gap cannot be crossed by passing one
1044/// number twice — see [`crate::hooks`].
1045/// `ENABLED` is [`ops::HookState::Enabled`] rather than a `&str` local, which is issue #24's
1046/// point about this function: the literal appeared six times with no constant naming either
1047/// value, so a typo in one of the six was a `ValidationException` on a create call made after
1048/// the artifact upload. It is now a compile error.
1049pub fn hooks_block(port: u16, run: RunHookTimeout, build: BuildHookTimeout) -> ops::Hooks {
1050 const ENABLED: ops::HookState = ops::HookState::Enabled;
1051 ops::Hooks {
1052 port,
1053 microvm_hooks: ops::MicrovmHooks {
1054 run: ENABLED,
1055 run_timeout_in_seconds: run.as_secs(),
1056 resume: ENABLED,
1057 resume_timeout_in_seconds: run.as_secs(),
1058 suspend: ENABLED,
1059 suspend_timeout_in_seconds: run.as_secs(),
1060 terminate: ENABLED,
1061 terminate_timeout_in_seconds: run.as_secs(),
1062 },
1063 microvm_image_hooks: ops::MicrovmImageHooks {
1064 ready: ENABLED,
1065 ready_timeout_in_seconds: build.as_secs(),
1066 validate: ENABLED,
1067 validate_timeout_in_seconds: build.as_secs(),
1068 },
1069 }
1070}
1071
1072/// A deadline elapsed on the client side. The remote resource is untouched.
1073pub(crate) fn timed_out(what: &str, waited: Duration) -> Error {
1074 Error::new(
1075 ErrorKind::Timeout,
1076 format!(
1077 "{what} within {:.0}s. This is a client-side deadline: nothing was cancelled, so \
1078 the resource is in whatever state the service last reported.",
1079 waited.as_secs_f64()
1080 ),
1081 )
1082}
1083
1084#[cfg(test)]
1085pub(crate) mod fake;
1086
1087#[cfg(test)]
1088mod tests {
1089 use super::*;
1090
1091 /// The three image-name rejections each get their own message, because the pattern
1092 /// wording is misleading for a name that is merely long.
1093 #[test]
1094 fn each_image_name_rejection_explains_its_own_case() {
1095 let empty = require_valid_image_name("").expect_err("min is 1");
1096 assert!(
1097 empty.to_string().contains("at least 1 character"),
1098 "{empty}"
1099 );
1100
1101 let long = require_valid_image_name(&"a".repeat(65)).expect_err("max is 64");
1102 let message = long.to_string();
1103 assert!(message.contains("65 characters"), "{message}");
1104 assert!(
1105 message.contains("after* the artifact upload"),
1106 "the reason to check locally is the cost: {message}"
1107 );
1108 assert!(
1109 !message.contains("no dots"),
1110 "the pattern wording is misleading for a merely-long name: {message}"
1111 );
1112
1113 let dotted = require_valid_image_name("my.image").expect_err("dots are not in the pattern");
1114 let message = dotted.to_string();
1115 assert!(message.contains("no dots and no slashes"), "{message}");
1116 assert!(message.contains("[a-zA-Z0-9-_]+"), "{message}");
1117 }
1118
1119 /// The boundaries are inclusive on both sides, and every rejection is an `InvalidArg`
1120 /// so the CLI reports it as refused-locally rather than as a platform failure.
1121 #[test]
1122 fn an_image_name_at_the_ceiling_is_accepted_and_one_past_it_is_not() {
1123 require_valid_image_name(&"a".repeat(64)).expect("64 is the ceiling");
1124 require_valid_image_name("a").expect("1 is the minimum");
1125 for bad in ["", &"a".repeat(65), "my.image", "team/image", "a b"] {
1126 let error = require_valid_image_name(bad).expect_err("rejected");
1127 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{bad:?}");
1128 }
1129 }
1130
1131 /// The duration range, at both boundaries. 28801 is the value the botocore gap was
1132 /// confirmed with, and the message has to say a second VM rather than a bigger number.
1133 #[test]
1134 fn the_duration_range_is_inclusive_and_names_the_eight_hour_ceiling() {
1135 assert_eq!(require_duration_in_range(1).expect("1 fits"), 1);
1136 assert_eq!(
1137 require_duration_in_range(28_800).expect("the ceiling fits"),
1138 28_800
1139 );
1140
1141 for bad in [0, 28_801, u32::MAX] {
1142 let error = require_duration_in_range(bad).expect_err("outside 1..28800");
1143 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{bad}");
1144 let message = error.to_string();
1145 assert!(message.contains("eight hours"), "{message}");
1146 assert!(
1147 message.contains("a second VM, not a larger number"),
1148 "{message}"
1149 );
1150 }
1151 }
1152
1153 /// The hooks block enables all six hooks, and the two families carry their own
1154 /// timeouts — which is the whole reason they are two types.
1155 #[test]
1156 fn the_hooks_block_enables_all_six_with_the_two_families_kept_apart() {
1157 let hooks = hooks_block(
1158 9000,
1159 RunHookTimeout::try_new(45).expect("45s is a legal run timeout"),
1160 BuildHookTimeout::try_new(1800).expect("1800s is a legal build timeout"),
1161 );
1162
1163 assert_eq!(hooks.port, 9000);
1164 for state in [
1165 hooks.microvm_hooks.run,
1166 hooks.microvm_hooks.resume,
1167 hooks.microvm_hooks.suspend,
1168 hooks.microvm_hooks.terminate,
1169 hooks.microvm_image_hooks.ready,
1170 hooks.microvm_image_hooks.validate,
1171 ] {
1172 assert_eq!(state, ops::HookState::Enabled, "all six hooks are served");
1173 // The wire spelling too, against a literal: the variant name and the string the
1174 // service reads are two different things, and `HookState::Enabled` rendering as
1175 // anything but `ENABLED` is a rejected create on six fields at once.
1176 assert_eq!(state.as_str(), "ENABLED");
1177 }
1178
1179 assert_eq!(hooks.microvm_hooks.run_timeout_in_seconds, 45);
1180 assert_eq!(hooks.microvm_hooks.terminate_timeout_in_seconds, 45);
1181 assert_eq!(hooks.microvm_image_hooks.ready_timeout_in_seconds, 1800);
1182 assert_eq!(
1183 hooks.microvm_image_hooks.validate_timeout_in_seconds, 1800,
1184 "1800 is legal for the build family and illegal for the run one, which is why \
1185 one shared number cannot serve both"
1186 );
1187 }
1188
1189 /// The default request carries the measured defaults, and identity repair is **off** —
1190 /// a capability granted by default is a capability nobody asked for.
1191 #[test]
1192 fn the_default_create_request_repairs_no_identity_and_takes_the_default_size() {
1193 let request = CreateImageRequest::new("img", vec![1, 2, 3], "s3://b/k", "arn:role");
1194 assert!(!request.repair_guest_identity);
1195 assert!(!request.inherit_workdir);
1196 assert_eq!(request.size, SizeClass::DEFAULT);
1197 assert_eq!(request.base_image, BaseImage::al2023());
1198 assert_eq!(request.token_scope, None);
1199 assert_eq!(request.dockerfile, None);
1200 }
1201
1202 /// The default launch requests ingress and **not** egress: omitting egress is how you
1203 /// get a VM with no outbound network, which is the right default for a daemon that
1204 /// needs none.
1205 #[test]
1206 fn the_default_launch_requests_ingress_only() {
1207 let payload = RunHookPayload::for_agent_token("token").expect("a token fits");
1208 let request = RunMicrovmRequest::new("arn:image", payload);
1209 assert_eq!(request.connectors, vec![ConnectorIntent::AllIngress]);
1210
1211 let with_egress = request.with_egress();
1212 assert_eq!(
1213 with_egress.connectors,
1214 vec![ConnectorIntent::AllIngress, ConnectorIntent::Egress]
1215 );
1216 }
1217
1218 /// Asking for egress twice does not send it twice. `NetworkConnectorList` caps at 10
1219 /// and a duplicate is a wasted slot at best.
1220 #[test]
1221 fn asking_for_egress_twice_adds_it_once() {
1222 let payload = RunHookPayload::for_agent_token("token").expect("a token fits");
1223 let request = RunMicrovmRequest::new("arn:image", payload)
1224 .with_egress()
1225 .with_egress();
1226 assert_eq!(request.connectors.len(), 2);
1227 }
1228
1229 /// `with_shell` **replaces** `ALL_INGRESS` with the measured pair rather than adding
1230 /// beside it: the platform accepts `ALL_INGRESS` + finer ingress at launch and
1231 /// refuses it only when a shell token is minted, after the VM has run and billed —
1232 /// and `run_microvm` refuses the combination client-side, so a `with_shell` that
1233 /// merely appended would build a request this client's own validation rejects.
1234 ///
1235 /// **Falsification** — watched fail 2026-08-31: dropping the `retain` from
1236 /// `with_shell` fails the first assertion with `ALL_INGRESS` still in the set.
1237 #[test]
1238 fn with_shell_replaces_all_ingress_with_the_measured_pair() {
1239 let payload = RunHookPayload::for_agent_token("token").expect("a token fits");
1240 let request = RunMicrovmRequest::new("arn:image", payload).with_shell();
1241 assert_eq!(
1242 request.connectors,
1243 vec![ConnectorIntent::HttpIngress, ConnectorIntent::ShellIngress]
1244 );
1245
1246 // Egress is a separate question and survives in either order.
1247 let payload = RunHookPayload::for_agent_token("token").expect("a token fits");
1248 let both = RunMicrovmRequest::new("arn:image", payload)
1249 .with_egress()
1250 .with_shell()
1251 .with_shell();
1252 assert_eq!(
1253 both.connectors,
1254 vec![
1255 ConnectorIntent::Egress,
1256 ConnectorIntent::HttpIngress,
1257 ConnectorIntent::ShellIngress
1258 ],
1259 "egress survives, and asking twice adds nothing"
1260 );
1261 }
1262
1263 /// A client-side deadline is an `ErrorKind::Timeout` and says the resource was not
1264 /// touched — because the caller's next question is whether to clean something up.
1265 #[test]
1266 fn a_client_side_deadline_says_the_resource_is_untouched() {
1267 let error = timed_out("the image did not become usable", Duration::from_secs(300));
1268 assert_eq!(error.kind(), ErrorKind::Timeout);
1269 let message = error.to_string();
1270 assert!(message.contains("300s"), "{message}");
1271 assert!(message.contains("nothing was cancelled"), "{message}");
1272 }
1273
1274 /// The default port matches the daemon's, and a caller can change it.
1275 #[test]
1276 fn the_agent_port_defaults_to_nine_thousand_and_is_overridable() {
1277 let plane = ControlPlane::with_transport(
1278 Arc::new(fake::FakeControlPlane::new()),
1279 Region::UsEast1,
1280 Arc::new(fake::TestClock::new()),
1281 );
1282 assert_eq!(plane.port(), DEFAULT_AGENT_PORT);
1283 assert_eq!(plane.port(), 9000);
1284 assert_eq!(
1285 plane.with_port(8080).expect("8080 is a legal port").port(),
1286 8080
1287 );
1288 }
1289
1290 /// **TRAP-1, the compile surface.** No public request type has a field that could carry
1291 /// a caller-supplied token.
1292 ///
1293 /// Asserted by destructuring rather than by grep: a struct pattern must name every
1294 /// field, so a `client_token` field added later fails to compile this test. That is the
1295 /// closest a test can get to asserting an absence.
1296 #[test]
1297 fn no_request_type_carries_a_caller_supplied_client_token() {
1298 let CreateImageRequest {
1299 name: _,
1300 base_image: _,
1301 base_image_version: _,
1302 dockerfile: _,
1303 binary: _,
1304 // Dependency-file *bytes* under ecosystem-fixed entry names — nothing
1305 // token-shaped, and no field a caller could name an arbitrary file into.
1306 project_files: _,
1307 code_artifact_uri: _,
1308 build_role_arn: _,
1309 size: _,
1310 repair_guest_identity: _,
1311 inherit_workdir: _,
1312 run_hook_timeout: _,
1313 build_hook_timeout: _,
1314 tags: _,
1315 // The logging pair. The stream is a *prefix* the create call suffixes with a
1316 // fresh nonce — the caller cannot name the exact wire stream, which is the
1317 // same closure shape as the token's.
1318 log_group: _,
1319 log_stream: _,
1320 // A *label*, folded in beside a fresh nonce. The only token-adjacent field,
1321 // and it cannot become the token.
1322 token_scope: _,
1323 } = CreateImageRequest::new("img", Vec::new(), "s3://b/k", "arn:role");
1324
1325 let RunMicrovmRequest {
1326 image_identifier: _,
1327 image_version: _,
1328 execution_role_arn: _,
1329 connectors: _,
1330 run_hook_payload: _,
1331 max_duration_sec: _,
1332 max_idle_sec: _,
1333 suspended_sec: _,
1334 auto_resume: _,
1335 token_scope: _,
1336 } = RunMicrovmRequest::new(
1337 "arn:image",
1338 RunHookPayload::for_agent_token("t").expect("fits"),
1339 );
1340 }
1341
1342 /// **TRAP-1's last mile.** The wire types' `client_token` fields are `pub(crate)`, so a
1343 /// caller outside this crate cannot build a request body with a token of their own.
1344 ///
1345 /// Worth its own test because the hole was real and I opened it: `ops` is a public module
1346 /// and the wire structs are public, so `pub client_token` on them meant an external
1347 /// caller could bypass `CreateImageRequest` entirely, hand-build a
1348 /// `CreateMicrovmImageWire` with a content digest, and serialize it — the wedge with one
1349 /// extra step, past a request type that has no such field.
1350 ///
1351 /// This test can only observe the *inside* of the boundary, since a compile failure
1352 /// outside the crate is not something an inline test can assert. What it pins is that the
1353 /// field is reachable from here and that the value in it came from the minter — so a
1354 /// later widening back to `pub` is at least a visible diff against a test that documents
1355 /// why it is narrow. The external half is enforced by the compiler.
1356 #[test]
1357 fn the_wire_types_token_field_is_crate_private_and_minted() {
1358 let wire = ops::RunMicrovmWire {
1359 image_identifier: "arn:image".to_string(),
1360 image_version: None,
1361 execution_role_arn: None,
1362 ingress_network_connectors: Vec::new(),
1363 egress_network_connectors: None,
1364 idle_policy: ops::IdlePolicy {
1365 max_idle_duration_seconds: 600,
1366 suspended_duration_seconds: 600,
1367 auto_resume_enabled: false,
1368 },
1369 maximum_duration_in_seconds: 3_600,
1370 run_hook_payload: String::new(),
1371 // Reachable from inside the crate, and only ever populated this way.
1372 client_token: token::run_token("arn:image"),
1373 };
1374 assert!(wire.client_token.starts_with("run-"));
1375 assert!(wire.client_token.len() <= crate::constants::MAX_CLIENT_TOKEN_LEN);
1376 assert_ne!(
1377 wire.client_token,
1378 token::run_token("arn:image"),
1379 "two mints of the same scope differ, which is the property the narrowing protects"
1380 );
1381 }
1382
1383 // ── issue #24's guards, at the message level ─────────────────────────────
1384 //
1385 // Each of these asserts the *refusal and its wording*; the zero-call proofs live beside
1386 // the operations they protect, in `image.rs` and `microvm.rs`, because only there can a
1387 // test observe that no control-plane call happened.
1388
1389 /// The three `NonBlankString` rejections each explain their own case, and the pattern one
1390 /// names the character it found.
1391 ///
1392 /// The whitespace message has to name the character, because the whole class of failure this
1393 /// catches is a value that *looks* right: a URI or a filter pasted out of a console carries a
1394 /// trailing newline, satisfies "non-empty", and fails the pattern.
1395 ///
1396 /// **Guard proof.** Delete the `is_empty` branch and the blank case returns `Ok`; delete the
1397 /// whitespace branch and the `"s3://b/k\n"` case does.
1398 #[test]
1399 fn each_non_blank_rejection_explains_its_own_case() {
1400 let blank = require_non_blank("codeArtifact.uri", "").expect_err("min is 1");
1401 assert_eq!(blank.kind(), ErrorKind::InvalidArg);
1402 assert!(
1403 blank.to_string().contains("at least 1 character"),
1404 "{blank}"
1405 );
1406 assert!(
1407 blank.to_string().contains("NonBlankString"),
1408 "the shape has to be named: {blank}"
1409 );
1410
1411 let long = require_non_blank("baseImageArn", &"a".repeat(2049)).expect_err("max is 2048");
1412 let message = long.to_string();
1413 assert!(message.contains("2049 characters"), "{message}");
1414 assert!(message.contains("ceiling of 2048"), "{message}");
1415
1416 let newline = require_non_blank("codeArtifact.uri", "s3://bucket/key.zip\n")
1417 .expect_err("whitespace anywhere is refused");
1418 let message = newline.to_string();
1419 assert!(
1420 message.contains(r"'\n'"),
1421 "the message must name the character it found: {message}"
1422 );
1423 assert!(message.contains("trailing newline"), "{message}");
1424
1425 // Whitespace in the middle, not only at the end: `[^\s]+` forbids it anywhere.
1426 let inner =
1427 require_non_blank("nameFilter", "coding agents").expect_err("an inner space too");
1428 assert!(
1429 inner.to_string().contains("anywhere in the value"),
1430 "{inner}"
1431 );
1432
1433 // And the legal values pass, so the guard is not refusing everything.
1434 require_non_blank("codeArtifact.uri", "s3://bucket/agentd.zip").expect("a real URI");
1435 require_non_blank(
1436 "baseImageArn",
1437 "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
1438 )
1439 .expect("a real base ARN");
1440 require_non_blank("nameFilter", "coding-agents").expect("a real filter");
1441 require_non_blank("imageVersion", &"9".repeat(2048)).expect("2048 is the ceiling");
1442 }
1443
1444 /// The identifier guard's two cases, and the over-long one names the model's own
1445 /// contradiction rather than telling the caller to shorten a value they may not have chosen.
1446 ///
1447 /// The empty message is the one that carries the reason this guard exists at all: ten of the
1448 /// twelve members are URI parameters, so an empty one collapses the path onto the collection
1449 /// and addresses the wrong resource — which the service can answer 200 to.
1450 ///
1451 /// **Guard proof.** Delete the `is_empty` branch and the blank case returns `Ok`; drop the
1452 /// `MicrovmImageArn` clause and the assertion on `2048` goes red.
1453 #[test]
1454 fn the_identifier_guard_names_the_collapsed_path_and_the_models_contradiction() {
1455 let blank = require_valid_identifier("microvmIdentifier", "").expect_err("min is 1");
1456 assert_eq!(blank.kind(), ErrorKind::InvalidArg);
1457 let message = blank.to_string();
1458 assert!(message.contains("at least 1 character"), "{message}");
1459 assert!(
1460 message.contains("collapses the path"),
1461 "the reason an empty URI parameter is dangerous has to be in the message: {message}"
1462 );
1463
1464 let long =
1465 require_valid_identifier("imageIdentifier", &"a".repeat(257)).expect_err("max is 256");
1466 let message = long.to_string();
1467 assert!(message.contains("257 characters"), "{message}");
1468 assert!(message.contains("256"), "{message}");
1469 assert!(
1470 message.contains("MicrovmImageArn permits 2048"),
1471 "the model's own contradiction has to be named, or the advice is 'shorten a value \
1472 the service gave you': {message}"
1473 );
1474
1475 require_valid_identifier(
1476 "imageIdentifier",
1477 "arn:aws:lambda:us-east-1:1:microvm-image:i",
1478 )
1479 .expect("a real ARN");
1480 require_valid_identifier("microvmIdentifier", "mvm-abc123").expect("a real id");
1481 require_valid_identifier("imageIdentifier", &"a".repeat(256)).expect("256 is the ceiling");
1482 }
1483
1484 /// The role-ARN guard's three cases, and the short one guesses the actual mistake.
1485 ///
1486 /// A value under 20 characters is almost always a role *name*, so the message renders the ARN
1487 /// the caller probably meant rather than restating the bound. That is the difference between
1488 /// a diagnostic and a validation error.
1489 ///
1490 /// **Guard proof.** Delete the `is_valid_role_arn` branch and the eleven-digit case returns
1491 /// `Ok` — which is the case nothing else catches.
1492 #[test]
1493 fn the_role_arn_guard_guesses_the_mistake_a_short_value_is() {
1494 let name = require_valid_role_arn("buildRoleArn", "build-role").expect_err("min is 20");
1495 assert_eq!(name.kind(), ErrorKind::InvalidArg);
1496 let message = name.to_string();
1497 assert!(message.contains("role *name*"), "{message}");
1498 assert!(
1499 message.contains("arn:aws:iam::<12-digit-account>:role/build-role"),
1500 "the message renders the ARN they probably meant: {message}"
1501 );
1502
1503 let long = require_valid_role_arn(
1504 "executionRoleArn",
1505 &format!("arn:aws:iam::123456789012:role/{}", "a".repeat(2048)),
1506 )
1507 .expect_err("max is 2048");
1508 assert!(long.to_string().contains("ceiling of 2048"), "{long}");
1509
1510 // Eleven digits, which is the case no eyeball and no other check catches.
1511 let eleven = require_valid_role_arn("buildRoleArn", "arn:aws:iam::12345678901:role/build")
1512 .expect_err("the account id is eleven digits");
1513 let message = eleven.to_string();
1514 assert!(
1515 message.contains("exactly twelve digits"),
1516 "the digit count is the whole value of this check: {message}"
1517 );
1518 assert!(
1519 message.contains("after* the artifact upload"),
1520 "the reason to check locally is the cost: {message}"
1521 );
1522 assert!(
1523 message.contains("/aws/lambda-microvms/*"),
1524 "and the message says what is still the service's answer to give: {message}"
1525 );
1526
1527 require_valid_role_arn(
1528 "buildRoleArn",
1529 "arn:aws:iam::392583147479:role/bonk-sandbox-microvm-build",
1530 )
1531 .expect("the conformance account's real build role");
1532 }
1533
1534 /// The port guard refuses 0 and says what 0 means, because 0 is not a typo.
1535 ///
1536 /// The ceiling branch cannot fire from a `u16` call site — `MAX_PORT` is `u16::MAX` — so what
1537 /// is asserted here is the floor and the two legal boundaries.
1538 ///
1539 /// **Guard proof.** Change the comparison to `port < 0` (or delete the branch) and the zero
1540 /// case returns `Ok`.
1541 #[test]
1542 fn the_port_guard_refuses_zero_and_says_what_zero_means() {
1543 let zero = require_valid_port("allowedPorts[].port", 0).expect_err("min is 1");
1544 assert_eq!(zero.kind(), ErrorKind::InvalidArg);
1545 let message = zero.to_string();
1546 assert!(
1547 message.contains("let the kernel choose"),
1548 "0 is a value a caller passes on purpose, so the message has to say why it is not a \
1549 port: {message}"
1550 );
1551 assert!(
1552 message.contains("authorizes nothing"),
1553 "the proxy-token consequence: {message}"
1554 );
1555 assert!(message.contains("9000"), "the default is named: {message}");
1556
1557 require_valid_port("port", 1).expect("1 is the minimum");
1558 require_valid_port("port", 9000).expect("the agent port");
1559 require_valid_port("port", 65_535).expect("65535 is the ceiling");
1560 }
1561
1562 /// The idle-duration guard refuses 59 and says the botocore reasoning did not transfer.
1563 ///
1564 /// The message names the wrong premise on purpose. The exemption was not a wrong number, it
1565 /// was a correct fact about a client that no longer exists — and a reader who deletes this
1566 /// guard will do it by reasoning that `min` is validated locally, which is exactly the
1567 /// sentence the message answers.
1568 ///
1569 /// **Guard proof.** Delete the call in `run_microvm` and the zero-call test in `microvm.rs`
1570 /// goes red; invert the comparison here and 600 is refused while 59 passes.
1571 #[test]
1572 fn the_idle_guard_refuses_fifty_nine_and_names_the_premise_that_did_not_transfer() {
1573 let under = require_idle_duration(59).expect_err("min is 60");
1574 assert_eq!(under.kind(), ErrorKind::InvalidArg);
1575 let message = under.to_string();
1576 assert!(message.contains("59"), "{message}");
1577 assert!(message.contains("minimum of 60"), "{message}");
1578 assert!(
1579 message.contains("botocore"),
1580 "the message has to name the premise, because the premise is what was wrong: \
1581 {message}"
1582 );
1583 assert!(
1584 message.contains("aws-sigv4"),
1585 "and say what this client actually does instead: {message}"
1586 );
1587
1588 require_idle_duration(60).expect("60 is the minimum");
1589 require_idle_duration(600).expect("the default");
1590 // No maximum in the model, and the client adds none.
1591 require_idle_duration(u32::MAX).expect("the model states no ceiling");
1592 }
1593
1594 /// Every tag rejection names the offending key, and the key and the value keep their
1595 /// different rules.
1596 ///
1597 /// The two asymmetries are the content of this test: an empty value is legal and an empty key
1598 /// is not, and the ceilings are 128 against 256. A guard that used one rule for both would
1599 /// pass a 200-character key or refuse a 200-character value, and neither is what the service
1600 /// does.
1601 ///
1602 /// **Guard proof.** Use `MAX_TAG_KEY_LEN` for the value branch and the 256-character-value
1603 /// case fails; drop the `key` from any message and the assertion naming it goes red.
1604 #[test]
1605 fn every_tag_rejection_names_the_key_and_the_two_halves_keep_their_own_rules() {
1606 use std::collections::BTreeMap;
1607
1608 let one = |key: &str, value: &str| {
1609 let mut tags = BTreeMap::new();
1610 tags.insert(key.to_string(), value.to_string());
1611 tags
1612 };
1613
1614 // An empty **value** is legal. TagValue's min is 0.
1615 require_valid_tags(&one("owner", "")).expect("an empty tag value is legal");
1616 // An empty **key** is not. TagKey's min is 1.
1617 let blank = require_valid_tags(&one("", "conformance")).expect_err("TagKey min is 1");
1618 assert_eq!(blank.kind(), ErrorKind::InvalidArg);
1619 assert!(
1620 blank.to_string().contains("TagValue's minimum is 0"),
1621 "the asymmetry is the thing to say: {blank}"
1622 );
1623
1624 // The two ceilings differ by 2x, and a 256-character *value* is legal.
1625 require_valid_tags(&one("owner", &"v".repeat(256))).expect("TagValue max is 256");
1626 let long_value = require_valid_tags(&one("owner", &"v".repeat(257)))
1627 .expect_err("257 is one past TagValue");
1628 assert!(long_value.to_string().contains("\"owner\""), "{long_value}");
1629 assert!(
1630 long_value.to_string().contains("257 characters"),
1631 "{long_value}"
1632 );
1633
1634 require_valid_tags(&one(&"k".repeat(128), "v")).expect("TagKey max is 128");
1635 let long_key =
1636 require_valid_tags(&one(&"k".repeat(129), "v")).expect_err("129 is one past TagKey");
1637 let message = long_key.to_string();
1638 assert!(message.contains("129 characters"), "{message}");
1639 assert!(
1640 message.contains("TagValue allows 256"),
1641 "the message says the two halves are not interchangeable: {message}"
1642 );
1643
1644 // The pattern, both halves, with the key named either way.
1645 let bad_key = require_valid_tags(&one("cost,centre", "x")).expect_err("a comma");
1646 let message = bad_key.to_string();
1647 assert!(message.contains("\"cost,centre\""), "{message}");
1648 assert!(
1649 message.contains("commas and `#` and `%` are not"),
1650 "{message}"
1651 );
1652
1653 let bad_value = require_valid_tags(&one("owner", "50%")).expect_err("a percent");
1654 let message = bad_value.to_string();
1655 assert!(
1656 message.contains("the value of tag \"owner\""),
1657 "the message says which half as well as which key: {message}"
1658 );
1659
1660 // A newline in a key: legal-looking, and the reason keys are printed with `{:?}`.
1661 let newline = require_valid_tags(&one("owner\n", "x")).expect_err("a control character");
1662 assert!(
1663 newline.to_string().contains(r#""owner\n""#),
1664 "a key with a stray newline is indistinguishable from a good one until it is quoted: \
1665 {newline}"
1666 );
1667
1668 // And a realistic tag set passes, including a space and a non-Latin key.
1669 let mut real = BTreeMap::new();
1670 real.insert("owner".to_string(), "conformance".to_string());
1671 real.insert("cost centre".to_string(), "team/agents".to_string());
1672 real.insert("所有者".to_string(), "らいす".to_string());
1673 real.insert("empty".to_string(), String::new());
1674 require_valid_tags(&real).expect("a realistic tag set");
1675
1676 // An empty map is not a tag problem, and `create_image` omits the member entirely.
1677 require_valid_tags(&BTreeMap::new()).expect("no tags is not an invalid tag");
1678 }
1679
1680 /// **Issue #24's `HookState` half.** The two values are named by a type, so neither can be
1681 /// misspelled, and the block this client sends is six `Enabled`s.
1682 ///
1683 /// The wire spellings are asserted against literals rather than derived from the variant
1684 /// names, because the variant name and the string the service reads are two different things
1685 /// — the same reason `ops::VersionStatus` does it that way.
1686 ///
1687 /// **Guard proof.** Change `HookState::Enabled`'s rename to `"ENABLE"` and this fails on the
1688 /// serialization assertion; add a third variant and the `HOOK_STATES` comparison fails.
1689 #[test]
1690 fn the_hook_state_enum_is_the_models_two_values_and_nothing_else() {
1691 assert_eq!(ops::HookState::Disabled.as_str(), "DISABLED");
1692 assert_eq!(ops::HookState::Enabled.as_str(), "ENABLED");
1693 assert_eq!(ops::HookState::Enabled.to_string(), "ENABLED");
1694
1695 // Through serde, which is what actually reaches the wire — `as_str` could be right while
1696 // the `rename` is wrong.
1697 assert_eq!(
1698 serde_json::to_value(ops::HookState::Enabled).expect("serialises"),
1699 serde_json::json!("ENABLED")
1700 );
1701 assert_eq!(
1702 serde_json::to_value(ops::HookState::Disabled).expect("serialises"),
1703 serde_json::json!("DISABLED")
1704 );
1705
1706 // The typed spelling and the drift gate's array agree, or one of them is checking
1707 // something the other does not send.
1708 let spelled = [ops::HookState::Disabled, ops::HookState::Enabled];
1709 let mut wire: Vec<&str> = spelled.iter().map(|state| state.as_str()).collect();
1710 wire.sort_unstable();
1711 let mut pinned = crate::constants::HOOK_STATES.to_vec();
1712 pinned.sort_unstable();
1713 assert_eq!(wire, pinned);
1714
1715 // And the misspellings a `String` field allowed are now parse failures on the way in,
1716 // which is the closest an inline test gets to asserting they are compile errors on the
1717 // way out.
1718 for typo in ["\"ENABLE\"", "\"Enabled\"", "\"ACTIVE\"", "\"enabled\""] {
1719 serde_json::from_str::<ops::HookState>(typo)
1720 .expect_err(&format!("{typo} is not a HookState"));
1721 }
1722 }
1723}