microvms_core/control/transport.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The signed rest-json transport, and the seam a test replaces it at.
3//!
4//! # Why this is hand-rolled
5//!
6//! `lambda-microvms` has no `aws-sdk-rust` crate. The alternatives were vendoring
7//! smithy-rs codegen — Gradle, JDK 17, Kotlin, and a project that declares its external
8//! interfaces unstable — or signing 24 rest-json operations by hand with the first-party
9//! low-level crates, which is the flow the AWS SDK maintainers point at for exactly this
10//! case. rest-json is also the easiest protocol to hand-roll: plain JSON bodies,
11//! URI-bound operations, standard headers, no XML and no query-protocol encoding.
12//!
13//! # The seam, and what the fake is allowed to know
14//!
15//! [`Transport`] is a trait with one method. The real implementation signs and sends;
16//! the test implementation is a **contract recorder** that asserts on the emitted
17//! request in the shape the service model declares.
18//!
19//! The rule the recorder follows is the lesson from the `buildState` bug: a fake that
20//! shares the client's assumptions hides exactly the class of defect the fake exists to
21//! catch. So the recorder never asserts on a value the client computed, and every
22//! response it hands back is **literal JSON in the model's spelling** — see
23//! [`crate::control::ops`] for why that is not a round trip through this crate's own
24//! serializer.
25//!
26//! # Local validation is not optional
27//!
28//! botocore's `VALIDATED_METADATA_ATTRS` is `{required, min, document, union}`, so
29//! `max`, `pattern`, and `enum` violations are serialized, sent, and answered with a
30//! `ValidationException` — confirmed empirically for `max` (runHookPayload 4097,
31//! maximumDurationInSeconds 28801, ImageName 65 chars, clientToken 129 chars), for
32//! `pattern`, and for `enum`. The same holds here with more force: **nothing** in this
33//! transport reads the service model at runtime, so every constraint is checked in the
34//! caller before a request is built or it is not checked at all.
35
36use std::time::SystemTime;
37
38use crate::error::{Error, ErrorKind};
39use crate::region::Region;
40
41/// The pinned API version, which is also the first path segment of every operation.
42///
43/// Read from [`crate::constants::MODEL_API_VERSION`] rather than written again, so the
44/// drift gate's version check and the URLs cannot disagree: a client signing
45/// `/2025-09-09/...` while claiming to implement a different model is a client whose
46/// constraint checks were verified against the wrong thing.
47const API_PATH_VERSION: &str = crate::constants::MODEL_API_VERSION;
48
49/// The SigV4 signing name, from the model's `signingName`.
50///
51/// `lambda`, not `lambda-microvms`. The `endpointPrefix` is also `lambda`, which is why
52/// an endpoint resolves for every AWS region and a client constructs happily for a region
53/// that does not carry MicroVMs (TRAP-6, `crate::region`).
54const SIGNING_NAME: &str = "lambda";
55
56/// One control-plane call: method, path, optional JSON body.
57///
58/// A struct rather than a long parameter list because the recorder asserts on it as a
59/// whole, and because `method` and `path` next to each other is how a reader checks a
60/// path against the model's `http` trait.
61#[derive(Clone, Debug, Eq, PartialEq)]
62pub struct Call {
63 /// The operation name, for diagnostics and for the recorder's ledger.
64 ///
65 /// Carried rather than derived from the path: the recorder's TRAP-11 assertion is
66 /// "no call named `CreateMicrovmShellAuthToken`", and matching that on a path is a
67 /// substring test that a renamed route would slip past.
68 pub operation: &'static str,
69 /// `GET`, `POST`, `PATCH`, or `DELETE` — the four the model's `http` traits use for the
70 /// operations this client implements.
71 pub method: Method,
72 /// The path **after** the host, with the API version and every URI parameter already
73 /// percent-encoded. Includes the query string when the operation has one.
74 pub path: String,
75 /// The rest-json body, or `None` for an operation the model gives no body members.
76 pub body: Option<Vec<u8>>,
77}
78
79/// The HTTP methods the model's operations use.
80///
81/// An enum so a call site cannot pass `"post"` and have the canonical request silently
82/// disagree with the wire method.
83///
84/// # `Patch` is one operation's, and only one
85///
86/// The model uses `PATCH` for exactly `UpdateMicrovmImageVersion` and `PUT` for exactly
87/// `UpdateMicrovmImage`. `Put` is deliberately absent: this client does not implement that
88/// operation, and a variant nothing constructs is a variant that suggests it does.
89/// `PATCH` is not interchangeable with `POST` here — a `POST` to the version path is a route
90/// the service does not declare, and the answer is a 404 that reads as a missing version
91/// rather than as a wrong method.
92#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93pub enum Method {
94 Get,
95 Post,
96 Patch,
97 Delete,
98}
99
100impl Method {
101 pub fn as_str(self) -> &'static str {
102 match self {
103 Method::Get => "GET",
104 Method::Post => "POST",
105 Method::Patch => "PATCH",
106 Method::Delete => "DELETE",
107 }
108 }
109}
110
111impl Call {
112 /// A `GET` with no body.
113 pub fn get(operation: &'static str, path: impl Into<String>) -> Self {
114 Self {
115 operation,
116 method: Method::Get,
117 path: path.into(),
118 body: None,
119 }
120 }
121
122 /// A `POST` carrying a serialized rest-json body.
123 pub fn post_json<T: serde::Serialize>(
124 operation: &'static str,
125 path: impl Into<String>,
126 body: &T,
127 ) -> Result<Self, Error> {
128 let body = serde_json::to_vec(body).map_err(|error| {
129 Error::new(
130 ErrorKind::Unexpected,
131 format!("could not serialize the {operation} request body: {error}"),
132 )
133 })?;
134 Ok(Self {
135 operation,
136 method: Method::Post,
137 path: path.into(),
138 body: Some(body),
139 })
140 }
141
142 /// A `PATCH` carrying a serialized rest-json body.
143 ///
144 /// The same shape as [`Call::post_json`] and written beside it rather than folded into a
145 /// method-taking constructor, for the reason [`Method`]'s docs give: the method is part of
146 /// the route the model declares, and a `with_method(Method::Patch)` builder is one a call
147 /// site can forget to call. `UpdateMicrovmImageVersion` is the only operation that reaches
148 /// this.
149 pub fn patch_json<T: serde::Serialize>(
150 operation: &'static str,
151 path: impl Into<String>,
152 body: &T,
153 ) -> Result<Self, Error> {
154 let body = serde_json::to_vec(body).map_err(|error| {
155 Error::new(
156 ErrorKind::Unexpected,
157 format!("could not serialize the {operation} request body: {error}"),
158 )
159 })?;
160 Ok(Self {
161 operation,
162 method: Method::Patch,
163 path: path.into(),
164 body: Some(body),
165 })
166 }
167
168 /// A `POST` with no body members. `SuspendMicrovm` and `ResumeMicrovm` are both this
169 /// shape: their only member is the URI-located identifier.
170 ///
171 /// The body is `Some(b"{}")` rather than `None`, because an empty POST and a POST of
172 /// `{}` are different canonical requests and rest-json services answer the former
173 /// inconsistently.
174 pub fn post_empty(operation: &'static str, path: impl Into<String>) -> Self {
175 Self {
176 operation,
177 method: Method::Post,
178 path: path.into(),
179 body: Some(b"{}".to_vec()),
180 }
181 }
182
183 /// A `DELETE` with no body.
184 pub fn delete(operation: &'static str, path: impl Into<String>) -> Self {
185 Self {
186 operation,
187 method: Method::Delete,
188 path: path.into(),
189 body: None,
190 }
191 }
192
193 /// The body as bytes, empty when there is none — which is what gets signed.
194 fn body_bytes(&self) -> &[u8] {
195 self.body.as_deref().unwrap_or(&[])
196 }
197}
198
199/// What the control plane answered: a status and a raw body.
200///
201/// Raw bytes rather than a deserialized value because the error path has to read a body
202/// the success types cannot hold, and because TRAP-6's null `message` field is only
203/// visible to something that did not already require a `String` there.
204#[derive(Clone, Debug)]
205pub struct Reply {
206 pub status: u16,
207 pub body: Vec<u8>,
208}
209
210impl Reply {
211 /// Deserializes the body as `T`, or reports the failure with the body attached.
212 ///
213 /// The body goes in the message because a rest-json parse failure with the text
214 /// withheld is unactionable: the reader cannot tell a renamed member from a truncated
215 /// response. Truncated to 512 bytes, since a list response can be large and the first
216 /// 512 characters always contain the member that failed.
217 pub fn json<T: serde::de::DeserializeOwned>(&self, operation: &str) -> Result<T, Error> {
218 serde_json::from_slice(&self.body).map_err(|error| {
219 let text = String::from_utf8_lossy(&self.body);
220 let shown: String = text.chars().take(512).collect();
221 Error::new(
222 ErrorKind::Platform,
223 format!(
224 "could not read the {operation} response ({error}). The service model for \
225 {API_PATH_VERSION} is what this client's shapes are transcribed from, so a \
226 member that has moved is a drift-gate failure rather than a transport bug. \
227 Body: {shown}"
228 ),
229 )
230 .with_source(error)
231 })
232 }
233
234 /// Whether the status is a success. rest-json operations here answer 200 or 201.
235 fn is_success(&self) -> bool {
236 (200..300).contains(&self.status)
237 }
238}
239
240/// The one seam every operation goes through.
241///
242/// One method, so a fake is a few lines and there is no partially-overridden transport
243/// whose behaviour is half real. `&self` rather than `&mut self` so the recorder can be
244/// shared behind an `Arc` while a lifecycle runs.
245pub trait Transport: Send + Sync {
246 /// Performs `call`, returning whatever the far side answered.
247 ///
248 /// A transport-level failure (no status at all) is an `Err`; a 4xx or 5xx is an
249 /// `Ok(Reply)` carrying the status, because classifying a status is
250 /// [`classify_failure`]'s job and a transport that classified would be a second
251 /// place the taxonomy lives.
252 fn send(
253 &self,
254 call: Call,
255 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Reply, Error>> + Send + '_>>;
256}
257
258/// Sends `call` through `transport`, retrying the retryable statuses, and turns a failure
259/// status into a classified [`Error`].
260///
261/// # Which failures retry
262///
263/// 429 (`ThrottlingException`), 500 (`InternalServerException`), and any other 5xx, plus
264/// a transport error that produced no status. AWS standard-mode semantics, matched by
265/// hand because the smithy retry pieces are coupled to an orchestrator this client does
266/// not have.
267///
268/// # Why retrying the mutating operations is safe
269///
270/// Every mutating operation this client sends carries a `clientToken`, so a retry is
271/// idempotent by the service's own contract — which is the same property that makes the
272/// token dangerous to derive (TRAP-1). `SuspendMicrovm`/`ResumeMicrovm`/`TerminateMicrovm`
273/// take no token and are retried anyway: they are state transitions whose second
274/// application is a no-op or a `ConflictException`, and a conflict is not retried.
275pub async fn send_with_retry(transport: &dyn Transport, call: Call) -> Result<Reply, Error> {
276 use backon::{ExponentialBuilder, Retryable};
277
278 let operation = call.operation;
279 let attempt = || {
280 let call = call.clone();
281 async move {
282 let reply = transport.send(call).await?;
283 if reply.is_success() {
284 return Ok(reply);
285 }
286 Err(classify_failure(operation, &reply))
287 }
288 };
289
290 attempt
291 .retry(
292 ExponentialBuilder::default()
293 .with_jitter()
294 .with_min_delay(std::time::Duration::from_millis(200))
295 .with_max_delay(std::time::Duration::from_secs(20))
296 .with_max_times(5),
297 )
298 .when(Error::retryable)
299 .await
300}
301
302/// Turns a failure status and body into an [`Error`] of the right kind.
303///
304/// # The statuses are the control plane's, not the daemon's
305///
306/// [`crate::error::WireKind`] is the *daemon's* status discipline and deliberately has no
307/// generic 4xx fallback, because the daemon's 400-versus-404 distinction is load-bearing.
308/// None of that applies here: these seven statuses come from the modeled exception shapes
309/// (`ValidationException` 400, `ServiceQuotaExceededException` 402,
310/// `AccessDeniedException` 403, `ResourceNotFoundException` 404, `ConflictException` 409,
311/// `ThrottlingException` 429, `InternalServerException` 500). So a control-plane failure
312/// carries an [`ErrorKind`] and **no** `WireKind` — which is what `error.rs` already
313/// documents: "`None` for every local reject and every control-plane failure — those never
314/// reached the in-VM daemon".
315///
316/// # 403 and the null message
317///
318/// A 403 whose `message` is null is the unsupported-region signature (TRAP-6). The
319/// message says so, because the alternative — forwarding a null as "AccessDenied: " — is
320/// precisely what sends someone to audit an IAM policy that is fine.
321pub fn classify_failure(operation: &str, reply: &Reply) -> Error {
322 let parsed: crate::control::ops::ServiceErrorWire =
323 serde_json::from_slice(&reply.body).unwrap_or_default();
324 let detail = parsed.message.as_deref().unwrap_or("").trim().to_string();
325
326 let (kind, explanation) = match reply.status {
327 400 => (
328 ErrorKind::Platform,
329 "ValidationException — the service refused a value. Every constraint the pinned \
330 service model states on a member this client sends is checked locally before the \
331 call — min as well as max, pattern, and enum, because nothing else validates a \
332 request here: this client signs with aws-sigv4 and sends with reqwest, so botocore's \
333 VALIDATED_METADATA_ATTRS never applies to it. So reaching this status means a \
334 constraint this client does not yet check, and closing it is a guard in \
335 microvms-core/src/control plus a line in scripts/check-model-drift.py."
336 .to_string(),
337 ),
338 402 => (
339 ErrorKind::Platform,
340 "ServiceQuotaExceededException — an account limit, not a request defect.".to_string(),
341 ),
342 403 if detail.is_empty() => (
343 ErrorKind::Credentials,
344 "AccessDeniedException with an empty or null message field. Measured 2026-08-07: this \
345 is the signature of a region that does not carry MicroVMs, and it is \
346 indistinguishable from a genuine IAM denial except that a real denial names the \
347 principal and the action (docs/PLATFORM.md, 'Calling an unpriced region returns \
348 AccessDeniedException with a null message'). Check the region before the policy."
349 .to_string(),
350 ),
351 403 => (
352 ErrorKind::Credentials,
353 "AccessDeniedException, with a message — so this is a genuine denial rather than the \
354 null-message region trap."
355 .to_string(),
356 ),
357 404 => (
358 ErrorKind::Platform,
359 "ResourceNotFoundException — the image or MicroVM does not exist.".to_string(),
360 ),
361 409 => (
362 ErrorKind::Platform,
363 "ConflictException — the resource is in a state that forbids this call. An image in \
364 CREATING refuses deletion, which is why teardown retries."
365 .to_string(),
366 ),
367 429 => (
368 ErrorKind::Retryable,
369 "ThrottlingException — retry the identical request.".to_string(),
370 ),
371 status if status >= 500 => (
372 ErrorKind::Retryable,
373 "InternalServerException — a service fault, retry the identical request.".to_string(),
374 ),
375 _ => (
376 ErrorKind::Platform,
377 "an unmodeled status: the service model declares 400, 402, 403, 404, 409, 429, and \
378 500 for these operations."
379 .to_string(),
380 ),
381 };
382
383 let said = if detail.is_empty() {
384 "the service sent no message".to_string()
385 } else {
386 format!("the service said {detail:?}")
387 };
388 Error::new(
389 kind,
390 format!(
391 "{operation} failed with HTTP {}: {said}. {explanation}",
392 reply.status
393 ),
394 )
395}
396
397/// The real transport: resolve credentials, sign SigV4, send with reqwest.
398pub struct SignedTransport {
399 region: Region,
400 endpoint: String,
401 credentials: aws_credential_types::provider::SharedCredentialsProvider,
402 http: reqwest::Client,
403}
404
405impl std::fmt::Debug for SignedTransport {
406 /// Hand-written because a derived one would print the credentials provider, and the
407 /// provider's own `Debug` is not something this crate controls.
408 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409 f.debug_struct("SignedTransport")
410 .field("region", &self.region)
411 .field("endpoint", &self.endpoint)
412 .finish_non_exhaustive()
413 }
414}
415
416impl SignedTransport {
417 /// Resolves the default credential chain for `region` and builds the HTTP client.
418 ///
419 /// # Why the chain rather than explicit keys
420 ///
421 /// Because the credentials a developer actually has are in SSO, a credential process,
422 /// or an instance profile, and re-implementing that resolution is how a client ends up
423 /// working only on the machine it was written on. `aws-config`'s default chain is the
424 /// whole reason to depend on it at all — the manifest turns off its HTTP client, since
425 /// reqwest is the one here, but keeps `sso` and `credentials-process`.
426 ///
427 /// The provider is held rather than the resolved credentials: instance-profile creds
428 /// are temporary, so each request re-resolves and picks up a rotation. That is why
429 /// this is a provider field and not a `Credentials` field.
430 pub async fn new(region: Region) -> Result<Self, Error> {
431 let config = aws_config::defaults(aws_config::BehaviorVersion::latest())
432 .region(aws_config::Region::new(region.as_str().to_string()))
433 .load()
434 .await;
435 let credentials = config.credentials_provider().ok_or_else(|| {
436 Error::new(
437 ErrorKind::Credentials,
438 "no credentials provider resolved. The default chain looks at environment \
439 variables, the shared config files, SSO, a credential process, then the EC2 \
440 instance metadata service; none of them answered. `aws sts get-caller-identity` \
441 is the cheapest way to see the same failure.",
442 )
443 })?;
444
445 let http = reqwest::Client::builder()
446 .connect_timeout(std::time::Duration::from_secs(10))
447 // Generous rather than tight: a control-plane call is not a hot path, and a
448 // timeout shorter than the service's own tail latency turns a slow answer into
449 // a retry storm against an operation that may not be idempotent.
450 .timeout(std::time::Duration::from_secs(60))
451 .build()
452 .map_err(|error| {
453 Error::new(
454 ErrorKind::Precondition,
455 format!("could not build the HTTP client: {error}"),
456 )
457 .with_source(error)
458 })?;
459
460 Ok(Self {
461 endpoint: endpoint_for(®ion),
462 region,
463 credentials,
464 http,
465 })
466 }
467
468 /// The URL this transport would send `call` to. Public for the test that checks a path
469 /// against the model without needing credentials.
470 fn url(&self, call: &Call) -> String {
471 format!("{}{}", self.endpoint, call.path)
472 }
473}
474
475/// `https://lambda.<region>.amazonaws.com`, from the model's `endpointPrefix`.
476///
477/// The prefix is `lambda` rather than `lambda-microvms`, which is why this resolves for
478/// every AWS region including the ones that answer the null-message denial.
479pub fn endpoint_for(region: &Region) -> String {
480 format!("https://{SIGNING_NAME}.{}.amazonaws.com", region.as_str())
481}
482
483impl Transport for SignedTransport {
484 fn send(
485 &self,
486 call: Call,
487 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Reply, Error>> + Send + '_>>
488 {
489 Box::pin(async move {
490 use aws_credential_types::provider::ProvideCredentials as _;
491
492 // Re-resolved per request so an instance-profile rotation is picked up. The
493 // provider caches internally, so this is not a metadata call per request.
494 let credentials = self
495 .credentials
496 .provide_credentials()
497 .await
498 .map_err(|error| {
499 Error::new(
500 ErrorKind::Credentials,
501 format!(
502 "could not resolve credentials for {}: {error}. Waiting will not fix \
503 this — the identity is wrong or absent.",
504 call.operation
505 ),
506 )
507 .with_source(error)
508 })?;
509
510 let url = self.url(&call);
511 let body = call.body_bytes().to_vec();
512
513 // Built before signing, because the signature covers the headers that are on
514 // it: content-type is signed, and adding one afterwards invalidates it.
515 let mut request = http::Request::builder()
516 .method(call.method.as_str())
517 .uri(&url)
518 .header("content-type", "application/json")
519 .body(body.clone())
520 .map_err(|error| {
521 Error::new(
522 ErrorKind::Unexpected,
523 format!("could not build the {} request: {error}", call.operation),
524 )
525 .with_source(error)
526 })?;
527
528 sign_in_place(&mut request, &credentials, &self.region)?;
529
530 let (parts, body) = request.into_parts();
531 let request = http::Request::from_parts(parts, reqwest::Body::from(body));
532 let request = reqwest::Request::try_from(request).map_err(|error| {
533 Error::new(
534 ErrorKind::Unexpected,
535 format!("could not convert the signed request: {error}"),
536 )
537 .with_source(error)
538 })?;
539
540 // A failure here produced no status, so it says nothing about service state:
541 // Retryable, matching the daemon transport's own rule.
542 let response = self.http.execute(request).await.map_err(|error| {
543 Error::new(
544 ErrorKind::Retryable,
545 format!(
546 "the {} request to {url} did not complete: {error}",
547 call.operation
548 ),
549 )
550 .with_source(error)
551 })?;
552
553 let status = response.status().as_u16();
554 let body = response
555 .bytes()
556 .await
557 .map_err(|error| {
558 Error::new(
559 ErrorKind::Retryable,
560 format!(
561 "could not read the {} response body: {error}",
562 call.operation
563 ),
564 )
565 .with_source(error)
566 })?
567 .to_vec();
568
569 Ok(Reply { status, body })
570 })
571 }
572}
573
574/// Signs `request` in place with SigV4 for `region`.
575///
576/// Split out so the signing step is one readable unit and so the test below can sign a
577/// request with static credentials and inspect the headers, which is the only way to check
578/// the signing name and region without a live call.
579fn sign_in_place(
580 request: &mut http::Request<Vec<u8>>,
581 credentials: &aws_credential_types::Credentials,
582 region: &Region,
583) -> Result<(), Error> {
584 use aws_sigv4::http_request::{SignableBody, SignableRequest, SigningSettings, sign};
585 use aws_sigv4::sign::v4;
586
587 let identity = credentials.clone().into();
588 let params: aws_sigv4::http_request::SigningParams = v4::SigningParams::builder()
589 .identity(&identity)
590 .region(region.as_str())
591 .name(SIGNING_NAME)
592 .time(SystemTime::now())
593 .settings(SigningSettings::default())
594 .build()
595 .map_err(|error| {
596 Error::new(
597 ErrorKind::Unexpected,
598 format!("could not build SigV4 signing parameters: {error}"),
599 )
600 .with_source(error)
601 })?
602 .into();
603
604 // The headers view has to borrow from `request`, so the signable view is built and
605 // consumed before the mutable borrow that applies the signature.
606 let instructions = {
607 let signable = SignableRequest::new(
608 request.method().as_str(),
609 request.uri().to_string(),
610 request.headers().iter().filter_map(|(name, value)| {
611 // A header whose value is not ASCII cannot be part of a canonical
612 // request. This client sets only content-type, so the filter is a
613 // guard against a future header rather than a live case — and dropping
614 // one is correct: an unsigned header is still sent, it is just not
615 // covered.
616 value.to_str().ok().map(|value| (name.as_str(), value))
617 }),
618 // `Bytes`, never `UnsignedPayload`: non-S3 services reject an unsigned
619 // payload, and an empty body still needs its empty-payload SHA256 signed.
620 SignableBody::Bytes(request.body()),
621 )
622 .map_err(|error| {
623 Error::new(
624 ErrorKind::Unexpected,
625 format!("could not build the signable request: {error}"),
626 )
627 .with_source(error)
628 })?;
629
630 sign(signable, ¶ms)
631 .map_err(|error| {
632 Error::new(
633 ErrorKind::Credentials,
634 format!("SigV4 signing failed: {error}"),
635 )
636 .with_source(error)
637 })?
638 .into_parts()
639 .0
640 };
641
642 // `http1x` rather than `http0x`: aws-sigv4's default features are sign-http + http1,
643 // which is the version reqwest 0.13 consumes through TryFrom. Mixing the two http
644 // versions would mean converting on every call.
645 instructions.apply_to_request_http1x(request);
646 Ok(())
647}
648
649/// The operation paths, one function per `http.requestUri` in the model.
650///
651/// Here rather than inlined at each call site so a path is written once and can be read
652/// against the model in one place. Every URI parameter is percent-encoded, because an
653/// image identifier may be an ARN — which contains `:` and `/` — and an unencoded ARN in a
654/// path segment is a different resource.
655pub mod paths {
656 use super::API_PATH_VERSION;
657
658 /// Percent-encodes a URI path segment.
659 ///
660 /// Hand-rolled against RFC 3986's unreserved set rather than pulling a dependency for
661 /// it. **`/` is encoded**, which is the whole point: an image ARN's slashes would
662 /// otherwise split into extra path segments and address something else. `:` is
663 /// encoded too — legal unencoded in a path per the RFC, but AWS's own SDKs encode it
664 /// in labels and the signature must match whatever is sent.
665 pub fn encode_segment(segment: &str) -> String {
666 let mut encoded = String::with_capacity(segment.len());
667 for byte in segment.bytes() {
668 match byte {
669 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
670 encoded.push(byte as char);
671 }
672 other => {
673 use std::fmt::Write as _;
674 let _ = write!(encoded, "%{other:02X}");
675 }
676 }
677 }
678 encoded
679 }
680
681 /// `POST /2025-09-09/microvm-images`
682 pub fn microvm_images() -> String {
683 format!("/{API_PATH_VERSION}/microvm-images")
684 }
685
686 /// `GET /2025-09-09/microvm-images`, with the listing's query members.
687 ///
688 /// `nameFilter` is the model's server-side **substring** filter — it narrows the
689 /// listing, it does not answer "the image named X", so an exact-match comparison
690 /// still happens in the caller. `nextToken` is the pagination cursor and is opaque,
691 /// which is why both values go through [`encode_segment`]: an opaque token may carry
692 /// `+` or `=`, and an unencoded one desynchronises the SigV4 canonical query from
693 /// the query actually sent.
694 pub fn microvm_images_list(name_filter: Option<&str>, next_token: Option<&str>) -> String {
695 let mut query: Vec<String> = Vec::new();
696 if let Some(filter) = name_filter {
697 query.push(format!("nameFilter={}", encode_segment(filter)));
698 }
699 if let Some(token) = next_token {
700 query.push(format!("nextToken={}", encode_segment(token)));
701 }
702 if query.is_empty() {
703 return microvm_images();
704 }
705 format!("{}?{}", microvm_images(), query.join("&"))
706 }
707
708 /// `GET|DELETE /2025-09-09/microvm-images/{imageIdentifier}`
709 pub fn microvm_image(image: &str) -> String {
710 format!(
711 "/{API_PATH_VERSION}/microvm-images/{}",
712 encode_segment(image)
713 )
714 }
715
716 /// One `nextToken=` query member, appended to `path`, or `path` unchanged.
717 ///
718 /// Shared by the three listings that take nothing else, so the encoding decision is
719 /// made once. The value goes through [`encode_segment`] for the reason
720 /// [`microvm_images_list`] states: a pagination token is **opaque**, so it may carry
721 /// `+`, `/`, or `=`, and an unencoded one desynchronises the SigV4 canonical query
722 /// from the query actually sent — a rejection that reads like bad credentials rather
723 /// than like a malformed URL.
724 fn with_next_token(path: String, next_token: Option<&str>) -> String {
725 match next_token {
726 Some(token) => format!("{path}?nextToken={}", encode_segment(token)),
727 None => path,
728 }
729 }
730
731 /// `GET /2025-09-09/microvm-images/{imageIdentifier}/versions`, with the pagination
732 /// cursor when there is one.
733 ///
734 /// `maxResults` is not sent: the model caps it at 50 and the service's own default is
735 /// what a caller reading every page wants, so naming a page size would only be a
736 /// second number to keep right. [`image_versions_paged`] is the one caller that does
737 /// name one, and says why.
738 pub fn image_versions(image: &str, next_token: Option<&str>) -> String {
739 image_versions_paged(image, next_token, None)
740 }
741
742 /// [`image_versions`] with an explicit `maxResults`, which **no production path sends**.
743 ///
744 /// # Why a page size exists at all when nothing ships one
745 ///
746 /// Because without it the cursor encoding is unfalsifiable against the real service,
747 /// and that encoding is the one place in this module where being wrong reads as a
748 /// *credentials* failure rather than a URL one. A real `nextToken` is opaque base64
749 /// carrying `+`, `/`, and `=`; an unencoded one desynchronises the SigV4 canonical
750 /// query and the service answers 403. Every test that could catch it went through an
751 /// injected transport, so the fake minted the token and the signer never saw it.
752 ///
753 /// Forcing a real cursor needs a listing with more items than one page, and the
754 /// service's default page is larger than any image's version count here — so the only
755 /// way to make the real service mint a real cursor for a resource that already exists
756 /// is to ask for a smaller page. That is what this is for, and
757 /// `microvms-core/tests/live_pagination.rs` is its caller.
758 ///
759 /// # Why it is not simply a parameter on [`image_versions`]
760 ///
761 /// A page size on the production path is a second number to keep right, and a wrong
762 /// one is invisible: reading every page with `maxResults=1` is correct and slow, which
763 /// is the kind of defect that survives. Keeping it to a separately named function means
764 /// the production call sites cannot acquire one by accident, and a reader of
765 /// [`image_versions`] sees no page size to wonder about.
766 ///
767 /// `max_results` is clamped to the model's `1..=50`, because a value outside it is a
768 /// `ValidationException` and a caller of this function is trying to observe pagination
769 /// rather than to discover the bound.
770 pub fn image_versions_paged(
771 image: &str,
772 next_token: Option<&str>,
773 max_results: Option<u32>,
774 ) -> String {
775 let mut query: Vec<String> = Vec::new();
776 if let Some(size) = max_results {
777 query.push(format!("maxResults={}", size.clamp(1, 50)));
778 }
779 if let Some(token) = next_token {
780 query.push(format!("nextToken={}", encode_segment(token)));
781 }
782 let path = format!("{}/versions", microvm_image(image));
783 if query.is_empty() {
784 return path;
785 }
786 format!("{path}?{}", query.join("&"))
787 }
788
789 /// `GET|PATCH|DELETE /2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}`
790 ///
791 /// One path for three operations, because the model gives them one `requestUri` and the
792 /// method is what distinguishes them: `GetMicrovmImageVersion` reads it,
793 /// `UpdateMicrovmImageVersion` patches it, `DeleteMicrovmImageVersion` deletes it. The
794 /// method lives on the [`Call`] rather than in three path functions, so a reader checking
795 /// this against `service-2.json` compares one string.
796 ///
797 /// Built from [`microvm_image`] rather than from [`image_versions`], because that one
798 /// now takes a cursor and none of the three may carry a query member.
799 pub fn image_version(image: &str, version: &str) -> String {
800 format!(
801 "{}/versions/{}",
802 microvm_image(image),
803 encode_segment(version)
804 )
805 }
806
807 /// `GET /2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds/{buildId}`
808 ///
809 /// The list path plus one segment. `buildId` is percent-encoded like every other URI
810 /// parameter even though a real one is a UUID: the model types it `NonBlankString`, so it
811 /// is not the encoder's business to assume the shape of a value the service mints.
812 pub fn image_build(image: &str, version: &str, build_id: &str) -> String {
813 format!(
814 "{}/builds/{}",
815 image_version(image, version),
816 encode_segment(build_id)
817 )
818 }
819
820 /// `GET /2025-09-09/managed-microvm-images`, with the pagination cursor when there is one.
821 ///
822 /// A **different route** from [`microvm_images`], not a filter on it: the managed bases
823 /// live under `managed-microvm-images` and their summaries carry a different shape
824 /// (`ManagedMicrovmImageSummary`, three members). Reading the account's own image listing
825 /// would never return one.
826 pub fn managed_microvm_images(next_token: Option<&str>) -> String {
827 with_next_token(
828 format!("/{API_PATH_VERSION}/managed-microvm-images"),
829 next_token,
830 )
831 }
832
833 /// `GET /2025-09-09/managed-microvm-images/{imageIdentifier}/versions`, with the cursor.
834 ///
835 /// `imageIdentifier` here is the managed base's **full ARN**, not its name: measured
836 /// 2026-08-16, `al2023-1` alone answers `ValidationException: Invalid ARN format:
837 /// al2023-1`. That is why [`crate::control::BaseImage::arn`] is what the caller passes —
838 /// and why the wrapper refuses a non-ARN locally, since the rejection names the value
839 /// without saying which member wanted an ARN.
840 pub fn managed_image_versions(image: &str, next_token: Option<&str>) -> String {
841 with_next_token(
842 format!(
843 "/{API_PATH_VERSION}/managed-microvm-images/{}/versions",
844 encode_segment(image)
845 ),
846 next_token,
847 )
848 }
849
850 /// `GET /2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds`,
851 /// with the pagination cursor when there is one.
852 pub fn image_builds(image: &str, version: &str, next_token: Option<&str>) -> String {
853 with_next_token(
854 format!("{}/builds", image_version(image, version)),
855 next_token,
856 )
857 }
858
859 /// `POST /2025-09-09/microvms`
860 ///
861 /// The bare collection path, which is what `RunMicrovm` posts to. `ListMicrovms` reads
862 /// the same route and lives in [`microvms_list`] rather than here, so a launch cannot
863 /// accidentally carry a `nextToken` — the same split [`microvm_images`] and
864 /// [`microvm_images_list`] already make.
865 pub fn microvms() -> String {
866 format!("/{API_PATH_VERSION}/microvms")
867 }
868
869 /// `GET /2025-09-09/microvms`, with the pagination cursor when there is one.
870 pub fn microvms_list(next_token: Option<&str>) -> String {
871 with_next_token(microvms(), next_token)
872 }
873
874 /// `GET|DELETE /2025-09-09/microvms/{microvmIdentifier}`
875 pub fn microvm(id: &str) -> String {
876 format!("/{API_PATH_VERSION}/microvms/{}", encode_segment(id))
877 }
878
879 /// `POST /2025-09-09/microvms/{microvmIdentifier}/suspend`
880 pub fn suspend(id: &str) -> String {
881 format!("{}/suspend", microvm(id))
882 }
883
884 /// `POST /2025-09-09/microvms/{microvmIdentifier}/resume`
885 pub fn resume(id: &str) -> String {
886 format!("{}/resume", microvm(id))
887 }
888
889 /// `POST /2025-09-09/microvms/{microvmIdentifier}/auth-token`
890 pub fn auth_token(id: &str) -> String {
891 format!("{}/auth-token", microvm(id))
892 }
893}
894
895#[cfg(test)]
896mod tests {
897 use super::*;
898
899 /// The regression that blocked the whole live tier: with aws-config's
900 /// `default-https-client` off, `load()` panics with "a http_client is
901 /// required" before any credential question is even asked. Constructing
902 /// through the real chain must yield a `Result` — either outcome is fine
903 /// here (this host may or may not have credentials); a panic is the bug.
904 /// IMDS is the only endpoint this can touch: link-local, free, and fast.
905 #[tokio::test]
906 async fn constructing_the_real_transport_returns_a_result_rather_than_panicking() {
907 let _ = SignedTransport::new(Region::UsEast1).await;
908 }
909
910 /// The endpoint, from the model's `endpointPrefix`. `lambda` and not
911 /// `lambda-microvms` — which is the fact that makes TRAP-6 possible, since this
912 /// resolves for every AWS region.
913 #[test]
914 fn the_endpoint_uses_the_models_lambda_prefix_for_every_region() {
915 assert_eq!(
916 endpoint_for(&Region::UsEast1),
917 "https://lambda.us-east-1.amazonaws.com"
918 );
919 assert_eq!(
920 endpoint_for(&Region::ApNortheast1),
921 "https://lambda.ap-northeast-1.amazonaws.com"
922 );
923 // Including one that does not carry MicroVMs, which is the point.
924 assert_eq!(
925 endpoint_for(&Region::unlisted("eu-central-1")),
926 "https://lambda.eu-central-1.amazonaws.com"
927 );
928 }
929
930 /// Every path against the model's `http.requestUri`, as literals. Transcribed from
931 /// `service-2.json` rather than built from a template, because a template shared with
932 /// the code under test would agree with a wrong template.
933 #[test]
934 fn every_path_matches_the_models_request_uri() {
935 assert_eq!(paths::microvm_images(), "/2025-09-09/microvm-images");
936 assert_eq!(
937 paths::microvm_image("img"),
938 "/2025-09-09/microvm-images/img"
939 );
940 assert_eq!(
941 paths::image_versions("img", None),
942 "/2025-09-09/microvm-images/img/versions"
943 );
944 assert_eq!(
945 paths::image_version("img", "1"),
946 "/2025-09-09/microvm-images/img/versions/1"
947 );
948 assert_eq!(
949 paths::image_builds("img", "1", None),
950 "/2025-09-09/microvm-images/img/versions/1/builds"
951 );
952 assert_eq!(
953 paths::image_build("img", "1", "build-abc"),
954 "/2025-09-09/microvm-images/img/versions/1/builds/build-abc"
955 );
956 assert_eq!(
957 paths::managed_microvm_images(None),
958 "/2025-09-09/managed-microvm-images"
959 );
960 assert_eq!(
961 paths::managed_image_versions(
962 "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
963 None
964 ),
965 "/2025-09-09/managed-microvm-images/\
966 arn%3Aaws%3Alambda%3Aus-east-1%3Aaws%3Amicrovm-image%3Aal2023-1/versions"
967 );
968 assert_eq!(paths::microvms(), "/2025-09-09/microvms");
969 assert_eq!(paths::microvms_list(None), "/2025-09-09/microvms");
970 assert_eq!(paths::microvm("mvm-1"), "/2025-09-09/microvms/mvm-1");
971 assert_eq!(
972 paths::suspend("mvm-1"),
973 "/2025-09-09/microvms/mvm-1/suspend"
974 );
975 assert_eq!(paths::resume("mvm-1"), "/2025-09-09/microvms/mvm-1/resume");
976 assert_eq!(
977 paths::auth_token("mvm-1"),
978 "/2025-09-09/microvms/mvm-1/auth-token"
979 );
980 }
981
982 /// The listing path carries its query members in the model's spelling, percent-encoded,
983 /// and a bare listing is the plain collection path with no `?`.
984 ///
985 /// An opaque `nextToken` may carry `+`, `/`, or `=`; unencoded, those desynchronise the
986 /// SigV4 canonical query from the query actually sent, and the rejection reads like bad
987 /// credentials.
988 #[test]
989 fn the_image_listing_path_encodes_its_query_members() {
990 assert_eq!(
991 paths::microvm_images_list(None, None),
992 "/2025-09-09/microvm-images"
993 );
994 assert_eq!(
995 paths::microvm_images_list(Some("my-image"), None),
996 "/2025-09-09/microvm-images?nameFilter=my-image"
997 );
998 assert_eq!(
999 paths::microvm_images_list(Some("my-image"), Some("a+b/c=")),
1000 "/2025-09-09/microvm-images?nameFilter=my-image&nextToken=a%2Bb%2Fc%3D"
1001 );
1002 assert_eq!(
1003 paths::microvm_images_list(None, Some("token")),
1004 "/2025-09-09/microvm-images?nextToken=token"
1005 );
1006 }
1007
1008 /// The other three paginated listings encode their cursor the same way, and emit no
1009 /// `?` at all without one.
1010 ///
1011 /// Written as literals per listing rather than as a loop over a helper, because the
1012 /// bug this closes is a path that forgets the cursor entirely — and a loop over the
1013 /// helper would pass against three call sites that never pass one.
1014 ///
1015 /// **Falsification** — drop the [`paths::encode_segment`] call from
1016 /// `with_next_token` and every `%2B`/`%2F`/`%3D` assertion below goes red, which is
1017 /// the SigV4 canonical-query desynchronisation this encoder exists to prevent.
1018 #[test]
1019 fn the_other_paginated_listings_encode_their_cursor_too() {
1020 assert_eq!(
1021 paths::image_versions("img", Some("a+b/c=")),
1022 "/2025-09-09/microvm-images/img/versions?nextToken=a%2Bb%2Fc%3D"
1023 );
1024 assert_eq!(
1025 paths::image_builds("img", "1", Some("a+b/c=")),
1026 "/2025-09-09/microvm-images/img/versions/1/builds?nextToken=a%2Bb%2Fc%3D"
1027 );
1028 assert_eq!(
1029 paths::microvms_list(Some("a+b/c=")),
1030 "/2025-09-09/microvms?nextToken=a%2Bb%2Fc%3D"
1031 );
1032
1033 // No cursor means no query string, not an empty one: `?nextToken=` is a member
1034 // present and blank, which is a different request from a member absent.
1035 for path in [
1036 paths::image_versions("img", None),
1037 paths::image_builds("img", "1", None),
1038 paths::microvms_list(None),
1039 ] {
1040 assert!(
1041 !path.contains('?'),
1042 "an absent cursor emits no query: {path}"
1043 );
1044 }
1045 }
1046
1047 /// The version listing's explicit page size: ordered before the cursor, clamped to the
1048 /// model's `1..=50`, and absent from the path when nothing asks for one.
1049 ///
1050 /// The clamp is asserted at both ends because a value outside the bound is a
1051 /// `ValidationException`, and the only caller of this function
1052 /// (`tests/live_pagination.rs`) is trying to *observe* a real cursor — a run that
1053 /// failed on the page size instead would prove nothing about the encoding it came for.
1054 ///
1055 /// **Falsification** — remove the `.clamp(1, 50)` and the `0` and `999` cases go red
1056 /// with `maxResults=0` and `maxResults=999`, both of which the service refuses.
1057 #[test]
1058 fn the_version_listings_explicit_page_size_is_ordered_and_clamped() {
1059 assert_eq!(
1060 paths::image_versions_paged("img", None, Some(1)),
1061 "/2025-09-09/microvm-images/img/versions?maxResults=1"
1062 );
1063 // Both members, and `maxResults` first — the order the query is built in, which is
1064 // asserted so a reordering is a visible change rather than a silent one.
1065 assert_eq!(
1066 paths::image_versions_paged("img", Some("a+b/c="), Some(2)),
1067 "/2025-09-09/microvm-images/img/versions?maxResults=2&nextToken=a%2Bb%2Fc%3D"
1068 );
1069 assert_eq!(
1070 paths::image_versions_paged("img", None, Some(0)),
1071 "/2025-09-09/microvm-images/img/versions?maxResults=1",
1072 "the model's min is 1; a 0 would be refused"
1073 );
1074 assert_eq!(
1075 paths::image_versions_paged("img", None, Some(999)),
1076 "/2025-09-09/microvm-images/img/versions?maxResults=50",
1077 "the model's max is 50; a larger value would be refused"
1078 );
1079
1080 // And the production spelling is unchanged by the new one existing: `image_versions`
1081 // delegates here with no page size, so it must still emit exactly what it did.
1082 assert_eq!(
1083 paths::image_versions_paged("img", None, None),
1084 paths::image_versions("img", None)
1085 );
1086 assert!(
1087 !paths::image_versions("img", Some("t")).contains("maxResults"),
1088 "no production path names a page size: {}",
1089 paths::image_versions("img", Some("t"))
1090 );
1091 }
1092
1093 /// The **managed** routes are a different collection from the account's own, and their
1094 /// cursor is encoded the same way.
1095 ///
1096 /// Asserted as its own case because the plausible mistake is treating the managed listing
1097 /// as a filter on `microvm-images` — it is a separate `requestUri` in the model with a
1098 /// different response shape, so a path built from [`paths::microvm_images`] would address
1099 /// the account's images and answer 200 with the wrong items.
1100 ///
1101 /// **Falsification** — drop the `managed-` prefix from either function and the two
1102 /// literals below go red while every request still succeeds against the real service,
1103 /// which is exactly why these are literals transcribed from the model rather than a
1104 /// shared template.
1105 #[test]
1106 fn the_managed_routes_are_their_own_collection_and_encode_their_cursor() {
1107 assert!(
1108 !paths::managed_microvm_images(None).contains('?'),
1109 "an absent cursor emits no query member"
1110 );
1111 assert_eq!(
1112 paths::managed_microvm_images(Some("a+b/c=")),
1113 "/2025-09-09/managed-microvm-images?nextToken=a%2Bb%2Fc%3D"
1114 );
1115 assert_eq!(
1116 paths::managed_image_versions("al2023-1", Some("a+b/c=")),
1117 "/2025-09-09/managed-microvm-images/al2023-1/versions?nextToken=a%2Bb%2Fc%3D"
1118 );
1119
1120 // Not a filter on the account's own listing: the two collections are different path
1121 // segments, and reading one for the other answers 200 with the wrong items.
1122 assert_ne!(
1123 paths::managed_microvm_images(None),
1124 paths::microvm_images_list(None, None)
1125 );
1126 assert!(
1127 !paths::microvm_images().contains("managed"),
1128 "the account's own collection must not acquire the managed prefix"
1129 );
1130 }
1131
1132 /// A `GET` of one build is the list path plus one encoded segment, and it carries no query
1133 /// member.
1134 ///
1135 /// The `buildId` is percent-encoded even though a real one is a UUID: the model types it
1136 /// `NonBlankString`, so the encoder does not get to assume the shape of a value the
1137 /// service mints.
1138 #[test]
1139 fn one_builds_path_is_the_listing_plus_an_encoded_segment() {
1140 let path = paths::image_build("img", "1", "4a4c5e30-811f-47fa-9893-260ea6a37a8f");
1141 assert_eq!(
1142 path,
1143 "/2025-09-09/microvm-images/img/versions/1/builds/4a4c5e30-811f-47fa-9893-260ea6a37a8f"
1144 );
1145 assert!(!path.contains('?'), "{path}");
1146 assert!(
1147 path.starts_with(&paths::image_builds("img", "1", None)),
1148 "the get path must extend the list path rather than be a second route: {path}"
1149 );
1150 // And an identifier with a separator in it cannot split into extra segments.
1151 assert_eq!(
1152 paths::image_build("img", "1", "a/b"),
1153 "/2025-09-09/microvm-images/img/versions/1/builds/a%2Fb"
1154 );
1155 }
1156
1157 /// A `DELETE` of one version carries no query member, even though its sibling
1158 /// [`paths::image_versions`] now takes a cursor. A version path with `?nextToken=`
1159 /// appended addresses nothing.
1160 #[test]
1161 fn deleting_one_version_carries_no_pagination_cursor() {
1162 let path = paths::image_version("img", "1");
1163 assert_eq!(path, "/2025-09-09/microvm-images/img/versions/1");
1164 assert!(!path.contains('?'), "{path}");
1165 assert!(!path.contains("nextToken"), "{path}");
1166 }
1167
1168 /// A **real** image ARN in a URI parameter is percent-encoded, every colon included.
1169 /// `MicrovmImageIdentifier` is documented as "ARN or ID", so this is the ordinary case
1170 /// rather than an edge one.
1171 ///
1172 /// The literal is the shape the service actually returns, measured 2026-08-15 in
1173 /// us-east-1: `microvm-image:<name>` with a **colon**, which is also the only form the
1174 /// model's `TaggableResource` pattern admits. This test used to hold
1175 /// `microvm-image/img`, and the slash was not a harmless stand-in — `GetMicrovmImage`
1176 /// on that form answers `AccessDeniedException`, because IAM evaluates a malformed ARN
1177 /// as a resource with no matching policy.
1178 #[test]
1179 fn a_real_arn_identifier_is_percent_encoded_colons_and_all() {
1180 let arn = "arn:aws:lambda:us-east-1:123456789012:microvm-image:img";
1181 let path = paths::microvm_image(arn);
1182 assert_eq!(
1183 path,
1184 "/2025-09-09/microvm-images/arn%3Aaws%3Alambda%3Aus-east-1%3A123456789012%3Amicrovm-image%3Aimg"
1185 );
1186 assert!(
1187 !path["/2025-09-09/microvm-images/".len()..].contains(':'),
1188 "an unencoded colon in a path segment is a signature mismatch: {path}"
1189 );
1190 }
1191
1192 /// The encoder still encodes `/`, which is the property that matters even though a real
1193 /// image ARN carries none.
1194 ///
1195 /// Kept as its own case rather than folded into the test above, because the input here
1196 /// is a *shape the service does not use* and labelling it "an ARN" is what let the slash
1197 /// form look load-bearing for twelve fakes. An unencoded slash would split into extra
1198 /// path segments addressing something else, and other identifiers this encoder sees
1199 /// (`imageVersion`, a `nextToken` cursor) genuinely can contain one.
1200 #[test]
1201 fn the_segment_encoder_encodes_slashes_wherever_they_come_from() {
1202 assert_eq!(paths::encode_segment("a/b"), "a%2Fb");
1203 let path = paths::microvm_image("has/a/slash");
1204 assert_eq!(path, "/2025-09-09/microvm-images/has%2Fa%2Fslash");
1205 assert!(
1206 !path["/2025-09-09/microvm-images/".len()..].contains('/'),
1207 "an encoded identifier contributes no path separators: {path}"
1208 );
1209 }
1210
1211 /// The API version in the path is the constant the drift gate checks, not a second
1212 /// literal. Two copies of `2025-09-09` are two things to update, and the one that gets
1213 /// missed is the one nothing compiles against.
1214 #[test]
1215 fn the_path_version_is_the_pinned_model_version() {
1216 assert_eq!(API_PATH_VERSION, crate::constants::MODEL_API_VERSION);
1217 assert!(paths::microvms().starts_with("/2025-09-09/"));
1218 }
1219
1220 /// The signing name is `lambda`, from the model's `signingName`. A signature computed
1221 /// for `lambda-microvms` is rejected in a way that reads like bad credentials.
1222 #[test]
1223 fn the_signing_name_is_lambda_not_lambda_microvms() {
1224 assert_eq!(SIGNING_NAME, "lambda");
1225 }
1226
1227 /// Signing puts an `authorization` header on the request naming the region and the
1228 /// signing name, and an `x-amz-security-token` when the credentials are temporary.
1229 ///
1230 /// Static credentials rather than a resolved chain, so this runs with no AWS
1231 /// configuration and no network — the signature is a pure function of the inputs.
1232 #[test]
1233 fn signing_names_the_region_and_the_service_in_the_credential_scope() {
1234 let credentials = aws_credential_types::Credentials::new(
1235 "AKIDEXAMPLE",
1236 "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
1237 Some("session-token".to_string()),
1238 None,
1239 "test",
1240 );
1241 let mut request = http::Request::builder()
1242 .method("POST")
1243 .uri("https://lambda.eu-west-1.amazonaws.com/2025-09-09/microvms")
1244 .header("content-type", "application/json")
1245 .body(b"{}".to_vec())
1246 .expect("builds");
1247
1248 sign_in_place(&mut request, &credentials, &Region::EuWest1).expect("signs");
1249
1250 let headers = request.headers();
1251 let authorization = headers
1252 .get("authorization")
1253 .expect("a signature was applied")
1254 .to_str()
1255 .expect("ascii");
1256 assert!(
1257 authorization.starts_with("AWS4-HMAC-SHA256 "),
1258 "{authorization}"
1259 );
1260 assert!(
1261 authorization.contains("/eu-west-1/lambda/aws4_request"),
1262 "the credential scope must name the request region and the signing name: \
1263 {authorization}"
1264 );
1265 assert!(
1266 headers.contains_key("x-amz-date"),
1267 "a signed date is required"
1268 );
1269 assert!(
1270 headers.contains_key("x-amz-security-token"),
1271 "temporary credentials carry a session token in the canonical request"
1272 );
1273 }
1274
1275 /// A `GET` with no body still gets signed, with the empty-payload SHA256 —
1276 /// `SignableBody::Bytes(&[])` rather than `UnsignedPayload`, which non-S3 services
1277 /// reject.
1278 #[test]
1279 fn a_bodyless_get_is_signed_rather_than_sent_unsigned() {
1280 let credentials =
1281 aws_credential_types::Credentials::new("AKIDEXAMPLE", "secret", None, None, "test");
1282 let mut request = http::Request::builder()
1283 .method("GET")
1284 .uri("https://lambda.us-east-1.amazonaws.com/2025-09-09/microvms/mvm-1")
1285 .body(Vec::new())
1286 .expect("builds");
1287
1288 sign_in_place(&mut request, &credentials, &Region::UsEast1).expect("signs");
1289 assert!(request.headers().contains_key("authorization"));
1290 assert!(
1291 !request.headers().contains_key("x-amz-security-token"),
1292 "static credentials carry no session token"
1293 );
1294 }
1295
1296 /// TRAP-6's diagnostic, on the exact response shape the trap produces: 403 with a
1297 /// null message. The message has to name the region cause *and* say the field was
1298 /// null, because "AccessDeniedException" alone is what sends a reader to the IAM
1299 /// console.
1300 #[test]
1301 fn a_null_message_access_denied_names_the_region_trap() {
1302 let reply = Reply {
1303 status: 403,
1304 body: br#"{"message": null}"#.to_vec(),
1305 };
1306 let error = classify_failure("ListMicrovms", &reply);
1307 assert_eq!(error.kind(), ErrorKind::Credentials);
1308 let message = error.to_string();
1309 assert!(message.contains("null"), "{message}");
1310 assert!(message.contains("region"), "{message}");
1311 assert!(message.contains("does not carry MicroVMs"), "{message}");
1312 assert!(
1313 message.contains("Check the region before the policy"),
1314 "the remedy has to be the region, not the policy: {message}"
1315 );
1316 }
1317
1318 /// A 403 *with* a message is a genuine denial and says so, so the two are not
1319 /// conflated. A classifier that named the region trap on every 403 would be as
1320 /// misleading in the other direction.
1321 #[test]
1322 fn a_403_with_a_message_is_reported_as_a_genuine_denial() {
1323 let reply = Reply {
1324 status: 403,
1325 body: br#"{"message": "User: arn:aws:iam::1:user/u is not authorized"}"#.to_vec(),
1326 };
1327 let error = classify_failure("RunMicrovm", &reply);
1328 assert_eq!(error.kind(), ErrorKind::Credentials);
1329 let message = error.to_string();
1330 assert!(message.contains("not authorized"), "{message}");
1331 assert!(
1332 message.contains("genuine denial"),
1333 "must distinguish itself from the null-message case: {message}"
1334 );
1335 assert!(
1336 !message.contains("does not carry MicroVMs"),
1337 "must not blame the region when the service named a principal: {message}"
1338 );
1339 }
1340
1341 /// Only the throttle and the 5xx family are retryable. A retried 409 would spin
1342 /// against an image in CREATING, and a retried 400 would send the same rejected value
1343 /// five more times.
1344 #[test]
1345 fn only_throttles_and_server_faults_are_retryable() {
1346 let cases = [
1347 (400, false),
1348 (402, false),
1349 (403, false),
1350 (404, false),
1351 (409, false),
1352 (429, true),
1353 (500, true),
1354 (502, true),
1355 (503, true),
1356 ];
1357 for (status, retryable) in cases {
1358 let reply = Reply {
1359 status,
1360 body: br#"{"message": "detail"}"#.to_vec(),
1361 };
1362 let error = classify_failure("GetMicrovm", &reply);
1363 assert_eq!(error.retryable(), retryable, "HTTP {status}");
1364 }
1365 }
1366
1367 /// A control-plane failure carries **no** `WireKind`: nothing reached the in-VM
1368 /// daemon, so there is no daemon-chosen status to report and the CLI's `data.kind`
1369 /// must be absent rather than invented.
1370 #[test]
1371 fn a_control_plane_failure_carries_no_daemon_wire_kind() {
1372 for status in [400, 403, 404, 409, 429, 500] {
1373 let reply = Reply {
1374 status,
1375 body: Vec::new(),
1376 };
1377 assert_eq!(
1378 classify_failure("GetMicrovm", &reply).wire_kind(),
1379 None,
1380 "HTTP {status} never reached the daemon"
1381 );
1382 }
1383 }
1384
1385 /// An unparseable error body still classifies by status rather than failing. A service
1386 /// answering an HTML error page or a truncated body must not turn a 429 into an
1387 /// unexpected error, which would stop the retry.
1388 #[test]
1389 fn an_unparseable_error_body_still_classifies_by_status() {
1390 let reply = Reply {
1391 status: 429,
1392 body: b"<html>Too Many Requests</html>".to_vec(),
1393 };
1394 let error = classify_failure("RunMicrovm", &reply);
1395 assert!(error.retryable(), "a throttle is a throttle");
1396 assert!(error.to_string().contains("no message"), "{error}");
1397 }
1398
1399 /// A body-parse failure names the operation and shows the body, because a rest-json
1400 /// parse error with the text withheld cannot distinguish a renamed member from a
1401 /// truncated response.
1402 #[test]
1403 fn a_response_that_does_not_parse_reports_the_body() {
1404 let reply = Reply {
1405 status: 200,
1406 body: br#"{"microvmId": 42}"#.to_vec(),
1407 };
1408 let error = reply
1409 .json::<crate::control::ops::MicrovmResponseWire>("GetMicrovm")
1410 .expect_err("microvmId is a string shape");
1411 let message = error.to_string();
1412 assert!(message.contains("GetMicrovm"), "{message}");
1413 assert!(message.contains("microvmId"), "{message}");
1414 assert_eq!(error.kind(), ErrorKind::Platform);
1415 }
1416
1417 /// A `POST` with no body members sends `{}` rather than nothing: an empty POST and a
1418 /// POST of `{}` are different canonical requests, and rest-json services answer the
1419 /// former inconsistently.
1420 #[test]
1421 fn a_bodyless_post_sends_an_empty_json_object() {
1422 let call = Call::post_empty("SuspendMicrovm", paths::suspend("mvm-1"));
1423 assert_eq!(call.body.as_deref(), Some(&b"{}"[..]));
1424 assert_eq!(call.method, Method::Post);
1425 }
1426
1427 /// A `GET` and a `DELETE` carry no body at all, and the signed empty payload is what
1428 /// `body_bytes` yields.
1429 #[test]
1430 fn a_get_and_a_delete_carry_no_body() {
1431 let get = Call::get("GetMicrovm", paths::microvm("mvm-1"));
1432 assert_eq!(get.body, None);
1433 assert_eq!(get.body_bytes(), b"");
1434
1435 let delete = Call::delete("TerminateMicrovm", paths::microvm("mvm-1"));
1436 assert_eq!(delete.body, None);
1437 assert_eq!(delete.method, Method::Delete);
1438 }
1439
1440 /// The methods, spelled as the canonical request needs them: uppercase.
1441 #[test]
1442 fn the_methods_are_the_ones_the_model_uses_spelled_uppercase() {
1443 assert_eq!(Method::Get.as_str(), "GET");
1444 assert_eq!(Method::Post.as_str(), "POST");
1445 assert_eq!(Method::Patch.as_str(), "PATCH");
1446 assert_eq!(Method::Delete.as_str(), "DELETE");
1447 }
1448
1449 /// A `PATCH` carries its serialized body and is **not** a `POST`.
1450 ///
1451 /// The distinction is load-bearing rather than cosmetic: `UpdateMicrovmImageVersion` is the
1452 /// model's only `PATCH`, and a `POST` to the version path is a route the service does not
1453 /// declare — so the failure would be a 404 that reads as a missing version rather than as a
1454 /// wrong method. The body assertion is here too, because a `PATCH` whose body was dropped
1455 /// would be a request with no `status` member at all.
1456 ///
1457 /// **Falsification** — set `method: Method::Post` in `patch_json` and the method assertion
1458 /// goes red; the path and body assertions would still pass, which is why the method is
1459 /// asserted separately.
1460 #[test]
1461 fn a_patch_carries_its_body_and_is_not_a_post() {
1462 let call = Call::patch_json(
1463 "UpdateMicrovmImageVersion",
1464 paths::image_version("img", "2.0"),
1465 &crate::control::ops::UpdateImageVersionWire {
1466 status: crate::control::ops::VersionStatus::Inactive,
1467 },
1468 )
1469 .expect("serialises");
1470
1471 assert_eq!(call.method, Method::Patch);
1472 assert_ne!(
1473 call.method,
1474 Method::Post,
1475 "a POST to the version path is a route the model does not declare"
1476 );
1477 assert_eq!(call.path, "/2025-09-09/microvm-images/img/versions/2.0");
1478 assert_eq!(
1479 call.body.as_deref(),
1480 Some(&br#"{"status":"INACTIVE"}"#[..]),
1481 "the one member the request has must reach the body"
1482 );
1483 assert_eq!(call.operation, "UpdateMicrovmImageVersion");
1484 }
1485
1486 /// A `PATCH` gets signed like every other method, with the empty-payload rule not applying
1487 /// because it has a body.
1488 ///
1489 /// Worth its own case because the signing path reads the method as a string for the
1490 /// canonical request: a method the enum spells and the signer does not is a signature over
1491 /// a different request than the one sent, which reads as bad credentials.
1492 #[test]
1493 fn a_patch_is_signed_with_its_method_in_the_canonical_request() {
1494 let credentials =
1495 aws_credential_types::Credentials::new("AKIDEXAMPLE", "secret", None, None, "test");
1496 let mut request = http::Request::builder()
1497 .method(Method::Patch.as_str())
1498 .uri(
1499 "https://lambda.us-east-1.amazonaws.com/2025-09-09/microvm-images/img/versions/2.0",
1500 )
1501 .header("content-type", "application/json")
1502 .body(br#"{"status":"INACTIVE"}"#.to_vec())
1503 .expect("builds");
1504
1505 sign_in_place(&mut request, &credentials, &Region::UsEast1).expect("signs");
1506 assert_eq!(request.method().as_str(), "PATCH");
1507 assert!(request.headers().contains_key("authorization"));
1508 }
1509}