microvms_core/sandbox.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The `Sandbox` lifecycle: one VM's whole life, with the state machine the symspec
3//! model describes made true of the code.
4//!
5//! Composes [`crate::control`] and [`crate::session`] into the surface the CLI and the
6//! bindings use: build, run, suspend, resume, terminate, the launch-time suspended
7//! window (STATE-12), and teardown in the order that does not leak.
8//!
9//! # The lifecycle is a field, and every transition is guarded
10//!
11//! [`Lifecycle`] is the symspec's `vm_state` verbatim, and [`Sandbox`] carries the other
12//! four variables beside it — `token_installed`, `image_exists`, `was_terminated`,
13//! `bootstrap_count`. The Z3 proofs over that model (bootstrap at most once, suspend from
14//! non-RUNNING unreachable, TERMINATED never returns to RUNNING) are proofs about *this*
15//! struct's reachable states, which is only worth something if the transitions here are
16//! the only way to move it. They are: every one of those fields is private, and every
17//! mutation happens in one of the five methods below.
18//!
19//! # Runtime-checked rather than typestate, deliberately
20//!
21//! The packet offered `Sandbox<Running>` returning a `Suspended` handle, which would make
22//! STATE-5's wrong call a compile error rather than a local refusal — strictly stronger on
23//! the ladder in [`crate`]. It is not what landed, for the reason the packet names as
24//! acceptable: T-W3-8 wraps **one** object for PyO3 and napi-rs, and a type whose Rust
25//! identity changes on every transition cannot be one `#[pyclass]`. A typestate sandbox
26//! would be re-erased into a runtime-checked enum at the binding boundary, so the check
27//! would exist twice with the binding's copy being the one most callers actually hit.
28//!
29//! What is kept from the typestate idea is the part that costs nothing: the check happens
30//! **before** the wire call, so a suspend from SUSPENDED is refused with zero
31//! control-plane calls rather than answered by AWS. The test asserts the call count, which
32//! is the observable that distinguishes the two.
33//!
34//! # The suspended window is the client's alone (STATE-12)
35//!
36//! `suspendedDurationSeconds` exists only in the `RunMicrovm` **request**. `GetMicrovm`
37//! does not return it, so the client that sent the launch is the only party that can name
38//! the window it asked for — and the launch-time `idlePolicy` *terminates* a suspended VM
39//! once that window passes, which means "resume later" silently stops working. A resume
40//! past the window is refused locally, before `ResumeMicrovm`, because the alternative is
41//! calling and reading the failure: the service answers about a terminated id, which is
42//! not the same statement as "the window you set at launch closed", and getting there
43//! costs the full poll timeout first.
44//!
45//! # Teardown never raises, and the log group is last
46//!
47//! [`Sandbox::terminate`] returns a [`TeardownReport`] rather than a `Result`. It runs
48//! where a caller's `finally` would, and an error raised there replaces the real failure
49//! with a teardown failure — the real one being the one worth reading.
50//!
51//! The order is VM, then image (retrying), then the log group **last**, because the
52//! service can recreate a group deleted before its image. See
53//! [`TeardownReport::undeleted`] for what this crate can and cannot delete.
54//!
55//! # There is no `Drop` that tears down
56//!
57//! Rust has no context manager and `Drop` cannot await. A `Drop` that blocked on a runtime
58//! would deadlock inside one; a `Drop` that spawned would race the process exit. So
59//! [`Sandbox`]'s `Drop` only **warns** about a live VM, naming the id, and the rule is
60//! that a caller calls [`Sandbox::terminate`] explicitly.
61
62use std::sync::Arc;
63use std::time::Duration;
64
65use crate::control::{
66 ControlPlane, CreateImageRequest, Image, Microvm, RunHookPayload, RunMicrovmRequest, WaitOpts,
67};
68use crate::error::{Error, ErrorKind};
69use crate::region::Region;
70use crate::session::{Session, TokenMinter};
71
72/// The default launch wait: five minutes, matching the Python client's `ready_timeout_sec`.
73pub const DEFAULT_READY_TIMEOUT: Duration = Duration::from_secs(300);
74
75/// The default lifecycle wait for suspend, resume, and terminate.
76pub const DEFAULT_LIFECYCLE_TIMEOUT: Duration = Duration::from_secs(300);
77
78/// How many times a teardown retries the image delete.
79///
80/// Twenty, from the Python client: an image in `CREATING` refuses deletion and a VM still
81/// terminating holds a reference, so this is the difference between a clean account and a
82/// billed leak rather than politeness.
83pub const DEFAULT_DELETE_ATTEMPTS: u32 = 20;
84
85/// The gap between image-delete attempts.
86pub const DEFAULT_DELETE_BACKOFF: Duration = Duration::from_secs(15);
87
88/// How often a lifecycle wait polls.
89const LIFECYCLE_POLL_INTERVAL: Duration = Duration::from_secs(5);
90
91/// The symspec's `vm_state`, verbatim.
92///
93/// Six states and no others, which is the S1 half of this module: a lifecycle held as a
94/// `String` would let `"RUNNING "` and `"Running"` both exist, and every guard below would
95/// have to decide which it meant.
96#[derive(Clone, Copy, Debug, Eq, PartialEq)]
97pub enum Lifecycle {
98 /// The initial state, and the state a launch is accepted into (STATE-1).
99 Pending,
100 /// The run hook answered with a success status and the token is installed (STATE-2).
101 Running,
102 /// A suspend was accepted and the platform has not yet reported it complete (STATE-4).
103 Suspending,
104 /// The platform reported suspension complete (STATE-6).
105 Suspended,
106 /// A terminate was accepted (STATE-9).
107 Terminating,
108 /// The platform reported termination complete (STATE-10).
109 Terminated,
110}
111
112impl Lifecycle {
113 /// The name the service uses for this state, which is also what an error message says.
114 pub fn as_str(self) -> &'static str {
115 match self {
116 Lifecycle::Pending => "PENDING",
117 Lifecycle::Running => "RUNNING",
118 Lifecycle::Suspending => "SUSPENDING",
119 Lifecycle::Suspended => "SUSPENDED",
120 Lifecycle::Terminating => "TERMINATING",
121 Lifecycle::Terminated => "TERMINATED",
122 }
123 }
124
125 /// Whether a VM in this state is still billing, which is what a `Drop` warning is for.
126 pub fn is_live(self) -> bool {
127 matches!(
128 self,
129 Lifecycle::Pending | Lifecycle::Running | Lifecycle::Suspending | Lifecycle::Suspended
130 )
131 }
132}
133
134impl std::fmt::Display for Lifecycle {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 f.write_str(self.as_str())
137 }
138}
139
140/// Everything a launch needs, with the defaults the Python client measured.
141///
142/// `agent_token` is optional because the common case is a per-VM secret nobody needs to
143/// see; a caller who has one already — a harness minting its own, or a retry that must
144/// reuse the first attempt's — passes it.
145#[derive(Clone, Debug)]
146pub struct RunRequest {
147 /// The image to launch, or `None` for the one [`Sandbox::build_image`] built.
148 pub image_identifier: Option<String>,
149 /// `imageVersion`, or `None` for the image's own latest active version.
150 ///
151 /// Pinning is what makes a canary a canary: without it a launch takes whatever version is
152 /// latest at the moment the call lands, which is not necessarily the one the caller just
153 /// built. Paired with [`crate::control::ControlPlane::set_image_version_status`] it is also
154 /// the rollback — set the bad version INACTIVE, re-pin here to the good one — and a version
155 /// set INACTIVE refuses to launch when named here.
156 ///
157 /// See [`crate::control::RunMicrovmRequest::image_version`], which this forwards to.
158 pub image_version: Option<String>,
159 /// The execution role. Optional in the model; every real launch needs one.
160 pub execution_role_arn: Option<String>,
161 /// The bearer token the daemon will accept, or `None` to mint one.
162 pub agent_token: Option<String>,
163 /// Base environment for every exec in the launched VM, delivered in the same
164 /// `runHookPayload` as the token.
165 ///
166 /// The daemon applies this *under* each request's own `env`, so a per-exec value
167 /// wins on a key both set. Empty by default, and an empty map produces byte-for-byte
168 /// the payload this client always sent — a caller who never touches this field
169 /// cannot be affected by the field existing.
170 ///
171 /// It shares the token's 4096-byte payload budget, and the check is local:
172 /// [`crate::control::RunHookPayload::for_launch`] refuses an over-ceiling payload
173 /// before any call, naming the byte count and how much of it the env is. That
174 /// matters here more than for the token, because one bearer token has always fit
175 /// with room to spare and a map of credentials does not.
176 pub launch_env: std::collections::HashMap<String, String>,
177 /// Whether to generate and deliver a tunnel identity (#70 layer 3).
178 ///
179 /// On, the launch generates two fresh x25519 seeds, delivers the VM's seed and the
180 /// host's public key in the same payload as the token, and [`RunOutcome`]-equivalent
181 /// state on the session keeps the [`crate::identity::TunnelIdentity`] — the host secret
182 /// and the VM's public pin — for `tunnel --verify-identity` to prove the far end.
183 /// Off (the default) sends byte-for-byte the payload this client always sent.
184 ///
185 /// A flag rather than always-on, deliberately: the material spends 137 bytes of the
186 /// payload's measured 4096-byte budget, and a caller near the ceiling with a launch env
187 /// deserves to choose which feature gets the room.
188 pub identity: bool,
189 /// Whether to request the egress connector. Off means no outbound network.
190 pub egress: bool,
191 /// `idlePolicy.maxIdleDurationSeconds`.
192 pub max_idle_sec: u32,
193 /// `idlePolicy.suspendedDurationSeconds` — the window STATE-12 refuses past.
194 pub suspended_sec: u32,
195 /// `idlePolicy.autoResumeEnabled`.
196 pub auto_resume: bool,
197 /// `maximumDurationInSeconds`, checked against 1..=28800 before the call.
198 pub max_duration_sec: u32,
199 /// How long to wait for RUNNING.
200 pub ready_timeout: Duration,
201 /// A label for the run token (TRAP-1). Never the token.
202 pub token_scope: Option<String>,
203}
204
205impl Default for RunRequest {
206 fn default() -> Self {
207 Self {
208 image_identifier: None,
209 image_version: None,
210 execution_role_arn: None,
211 agent_token: None,
212 launch_env: std::collections::HashMap::new(),
213 identity: false,
214 egress: false,
215 max_idle_sec: 600,
216 suspended_sec: 600,
217 auto_resume: false,
218 max_duration_sec: 3_600,
219 ready_timeout: DEFAULT_READY_TIMEOUT,
220 token_scope: None,
221 }
222 }
223}
224
225impl RunRequest {
226 /// A launch with the measured defaults: ingress only, ten-minute idle and suspended
227 /// windows, a one-hour maximum duration, no auto-resume.
228 pub fn new() -> Self {
229 Self::default()
230 }
231
232 /// Launches `identifier` rather than the built image.
233 #[must_use]
234 pub fn with_image(mut self, identifier: impl Into<String>) -> Self {
235 self.image_identifier = Some(identifier.into());
236 self
237 }
238
239 /// Requests the egress connector, which is what gives the VM outbound network.
240 #[must_use]
241 pub fn with_egress(mut self) -> Self {
242 self.egress = true;
243 self
244 }
245
246 /// Pins the launch to one `imageVersion`. See the field for why.
247 #[must_use]
248 pub fn with_image_version(mut self, version: impl Into<String>) -> Self {
249 self.image_version = Some(version.into());
250 self
251 }
252
253 /// Sets the suspended window this sandbox will refuse a resume past (STATE-12).
254 #[must_use]
255 pub fn with_suspended_sec(mut self, seconds: u32) -> Self {
256 self.suspended_sec = seconds;
257 self
258 }
259
260 /// Reuses a caller-supplied agent token rather than minting one.
261 #[must_use]
262 pub fn with_agent_token(mut self, token: impl Into<String>) -> Self {
263 self.agent_token = Some(token.into());
264 self
265 }
266
267 /// Generates and delivers a tunnel identity with the launch (#70 layer 3).
268 ///
269 /// After a `run` with this set, [`Sandbox::tunnel_identity`] holds what
270 /// `tunnel --verify-identity` needs: the host's secret and the VM's public pin.
271 #[must_use]
272 pub fn with_identity(mut self) -> Self {
273 self.identity = true;
274 self
275 }
276
277 /// Adds one launch-environment variable, which every exec in the VM starts with.
278 ///
279 /// One pair per call rather than a whole map, because that is how a caller builds
280 /// one — from flags, from a config file, one credential at a time — and a
281 /// map-taking setter makes the second call silently discard the first. The field is
282 /// public for a caller who really does hold a map.
283 #[must_use]
284 pub fn with_launch_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
285 self.launch_env.insert(key.into(), value.into());
286 self
287 }
288}
289
290/// What a teardown should delete beyond the VM itself.
291///
292/// Both deletions are opt-in, because both destroy something a caller may still want: the
293/// image is reusable across runs, and the log group is where a failed build's only evidence
294/// lives.
295#[derive(Clone, Copy, Debug)]
296pub struct TeardownOpts {
297 /// Whether to delete the image the sandbox built.
298 pub delete_image: bool,
299 /// Whether the build log group should be deleted.
300 ///
301 /// This crate **cannot** delete it — CloudWatch is not in the dependency set — so
302 /// asking names the group in [`TeardownReport::undeleted`] rather than removing it.
303 /// See that field for why naming is the honest answer rather than a silent success.
304 pub delete_log_group: bool,
305 /// How many times the image delete is retried.
306 pub delete_attempts: u32,
307 /// The gap between image-delete attempts.
308 pub delete_backoff: Duration,
309 /// How long to wait for TERMINATED, or `None` to return as soon as the terminate call
310 /// is accepted.
311 ///
312 /// `None` by default, matching the Python client: the caller is on the way out, and a
313 /// teardown that blocked five minutes on a state nobody reads is five minutes of a CI
314 /// job. A caller that needs STATE-10 *observed* passes
315 /// [`TeardownOpts::waiting_for_terminated`].
316 pub wait_for_terminated: Option<Duration>,
317}
318
319impl Default for TeardownOpts {
320 fn default() -> Self {
321 Self {
322 delete_image: false,
323 delete_log_group: false,
324 delete_attempts: DEFAULT_DELETE_ATTEMPTS,
325 delete_backoff: DEFAULT_DELETE_BACKOFF,
326 wait_for_terminated: None,
327 }
328 }
329}
330
331impl TeardownOpts {
332 /// Deletes the image as well as the VM.
333 #[must_use]
334 pub fn deleting_image(mut self) -> Self {
335 self.delete_image = true;
336 self
337 }
338
339 /// Asks for the log group too, which names it rather than deleting it.
340 #[must_use]
341 pub fn deleting_log_group(mut self) -> Self {
342 self.delete_log_group = true;
343 self
344 }
345
346 /// Waits for TERMINATED before returning (STATE-10).
347 #[must_use]
348 pub fn waiting_for_terminated(mut self) -> Self {
349 self.wait_for_terminated = Some(DEFAULT_LIFECYCLE_TIMEOUT);
350 self
351 }
352}
353
354/// What a teardown did, and what it left behind.
355///
356/// Returned rather than raised. See the module docs: this runs where a `finally` would.
357#[derive(Clone, Debug, Default, Eq, PartialEq)]
358pub struct TeardownReport {
359 /// Identifiers of everything a caller asked to have deleted that still exists.
360 ///
361 /// The CLI emits these (CLI-6), which is the whole reason they are identifiers rather
362 /// than a boolean: a leak nobody can name is a leak nobody can clean up.
363 ///
364 /// Two things land here. A delete that was attempted and failed — an image whose twenty
365 /// attempts all hit a conflict. And the build **log group**, which this crate cannot
366 /// delete at all: no CloudWatch client exists anywhere in this workspace, and a logs
367 /// API for one delete call is a bigger surface than the leak it would hide (an
368 /// `aws-sdk-cloudwatchlogs` edge is a reasonable future add if teardown grows more
369 /// log-group work). Naming it is strictly better than the
370 /// alternatives: deleting it is unavailable, and silently succeeding would report a
371 /// clean teardown over six accumulated log groups — which is how the leak was found in
372 /// the first place.
373 pub undeleted: Vec<String>,
374 /// Whether the terminate call was accepted.
375 pub terminate_accepted: bool,
376 /// Whether the image was deleted, or `None` when deletion was not asked for.
377 pub image_deleted: Option<bool>,
378 /// The lifecycle state the sandbox ended in.
379 pub lifecycle: Option<Lifecycle>,
380 /// Every failure the teardown swallowed, in the order it hit them.
381 ///
382 /// Kept because a teardown that never raises is a teardown whose failures are invisible
383 /// otherwise, and the first one is usually the cause of the rest.
384 pub failures: Vec<String>,
385}
386
387impl TeardownReport {
388 /// Whether anything a caller asked for was left behind.
389 pub fn leaked(&self) -> bool {
390 !self.undeleted.is_empty()
391 }
392}
393
394/// Mints proxy tokens for one MicroVM through the control plane.
395///
396/// The bridge between the two lanes: `ControlPlane::mint_auth_token` answers a
397/// `control::ProxyToken`, [`TokenMinter`] wants a `session::ProxyToken`, and the `From`
398/// impl at `session/proxy.rs` is the conversion — one `.into()` at the boundary, which is
399/// why that impl is `From` rather than a named function.
400///
401/// The plane sits behind an `Arc` rather than a reference because the minter must outlive
402/// the call that built the session: minting happens inside the request path on every later
403/// request, which is what makes it happen at all (TRAP-9).
404struct ControlPlaneMinter {
405 control: Arc<ControlPlane>,
406 microvm_id: String,
407}
408
409impl TokenMinter for ControlPlaneMinter {
410 fn mint(
411 &self,
412 ) -> futures_util::future::BoxFuture<'_, Result<crate::session::ProxyToken, Error>> {
413 Box::pin(async move {
414 let minted = self.control.mint_auth_token(&self.microvm_id).await?;
415 Ok(minted.into())
416 })
417 }
418
419 /// Overrides the default, which ignores the ports and delegates.
420 ///
421 /// This is the minter that has a control plane behind it, so it is the one that can
422 /// actually widen a token's scope — and without this override
423 /// `Session::connect_headers(8080)` would keep answering a header pair behind a token
424 /// scoped to 9000 only, which the proxy refuses with 403 `Access to port denied`. See
425 /// [`TokenMinter::mint_for_ports`] for the measurement.
426 fn mint_for_ports(
427 &self,
428 ports: &[u16],
429 ) -> futures_util::future::BoxFuture<'_, Result<crate::session::ProxyToken, Error>> {
430 let specs: Vec<crate::control::ops::PortSpecification> = ports
431 .iter()
432 .map(|port| crate::control::ops::PortSpecification::port(*port))
433 .collect();
434 Box::pin(async move {
435 let minted = self
436 .control
437 .mint_auth_token_for(&self.microvm_id, &specs)
438 .await?;
439 Ok(minted.into())
440 })
441 }
442}
443
444/// One MicroVM's whole life.
445///
446/// See the module docs for the state machine, the window, and why teardown is explicit.
447pub struct Sandbox {
448 control: Arc<ControlPlane>,
449 image: Option<Image>,
450 microvm: Option<Microvm>,
451 session: Option<Session>,
452 /// A backend for the session [`Sandbox::run`] builds, or `None` for the real HTTP one.
453 ///
454 /// The daemon-side sibling of `with_control_plane`'s transport seam: a test that
455 /// scripts the control plane can launch, but the session `run` then builds would dial
456 /// a real endpoint. This lets the same test script the daemon too. Never set in
457 /// production — `Session::builder` picks reqwest when no backend is given.
458 session_backend: Option<crate::session::SharedBackend>,
459
460 // ── the symspec's five variables ─────────────────────────────────────────
461 lifecycle: Lifecycle,
462 token_installed: bool,
463 image_exists: bool,
464 was_terminated: bool,
465 bootstrap_count: u32,
466
467 /// The window from *our own* `RunMicrovm` request. `GetMicrovm` does not return it.
468 suspended_window: Option<Duration>,
469 /// The clock reading when the suspend call was accepted, or `None` when not suspended.
470 suspended_at: Option<Duration>,
471 /// Set by [`Sandbox::terminate`], so `Drop` can tell an abandoned VM from a torn-down
472 /// one.
473 torn_down: bool,
474 /// The launch's tunnel identity, when [`RunRequest::identity`] asked for one.
475 ///
476 /// Holds the host secret and the VM's *public* pin — the VM's own secret was dropped
477 /// the moment the payload was built ([`crate::identity::LaunchIdentity::keep`]), so
478 /// nothing on the host side can impersonate the VM it launched.
479 tunnel_identity: Option<crate::identity::TunnelIdentity>,
480}
481
482impl std::fmt::Debug for Sandbox {
483 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
484 // No agent token: it is a credential, and a `Debug` that printed it would put it in
485 // every log line that formats a sandbox.
486 f.debug_struct("Sandbox")
487 .field("lifecycle", &self.lifecycle)
488 .field("microvm", &self.microvm.as_ref().map(|vm| &vm.id))
489 .field("image", &self.image.as_ref().map(|image| &image.identifier))
490 .field("token_installed", &self.token_installed)
491 .field("bootstrap_count", &self.bootstrap_count)
492 .field("was_terminated", &self.was_terminated)
493 .field("suspended_window", &self.suspended_window)
494 .finish_non_exhaustive()
495 }
496}
497
498impl Sandbox {
499 /// Resolves credentials for `region` and returns a sandbox with nothing launched.
500 ///
501 /// TRAP-6 is closed by [`Region`] before this is reached, which is why there is no
502 /// region check here.
503 pub async fn new(region: Region) -> Result<Self, Error> {
504 Ok(Self::with_control_plane(ControlPlane::new(region).await?))
505 }
506
507 /// A sandbox over an already-built [`ControlPlane`].
508 ///
509 /// The seam every test uses, and public for the same reason `ControlPlane::with_transport`
510 /// is: a caller who wants a non-default port, or a fake transport, has already built the
511 /// plane, and a sandbox constructible only from a [`Region`] would be a sandbox no test
512 /// can drive without AWS.
513 ///
514 /// The plane's own clock is what times the suspended window, rather than a second one
515 /// this type would own. Two clocks in one lifecycle is the trap the daemon's turmoil
516 /// tests record: a window measured on one clock while the poll loop sleeps on another
517 /// calls a closed window open.
518 pub fn with_control_plane(control: ControlPlane) -> Self {
519 Self {
520 control: Arc::new(control),
521 image: None,
522 microvm: None,
523 session: None,
524 session_backend: None,
525 lifecycle: Lifecycle::Pending,
526 token_installed: false,
527 image_exists: false,
528 was_terminated: false,
529 bootstrap_count: 0,
530 suspended_window: None,
531 suspended_at: None,
532 torn_down: false,
533 tunnel_identity: None,
534 }
535 }
536
537 /// Routes the session [`Sandbox::run`] builds through `backend` instead of real HTTP.
538 ///
539 /// The daemon-side half of the test seam `with_control_plane` opens: scripting the
540 /// control plane gets a test through the launch, and this gets it through everything
541 /// the launched session then does — uploads, execs, downloads — without a daemon.
542 pub fn with_session_backend(mut self, backend: crate::session::SharedBackend) -> Self {
543 self.session_backend = Some(backend);
544 self
545 }
546
547 // ── the symspec's five variables, readable ───────────────────────────────
548
549 /// The lifecycle state, which is the symspec's `vm_state`.
550 pub fn lifecycle(&self) -> Lifecycle {
551 self.lifecycle
552 }
553
554 /// Whether the agent token has been installed (STATE-2).
555 pub fn token_installed(&self) -> bool {
556 self.token_installed
557 }
558
559 /// Whether an image is recorded as existing (STATE-1).
560 pub fn image_exists(&self) -> bool {
561 self.image_exists
562 }
563
564 /// Whether this VM was ever terminated (STATE-11).
565 pub fn was_terminated(&self) -> bool {
566 self.was_terminated
567 }
568
569 /// How many times the token has been installed. Never above one (STATE-3).
570 pub fn bootstrap_count(&self) -> u32 {
571 self.bootstrap_count
572 }
573
574 /// The image, once built.
575 pub fn image(&self) -> Option<&Image> {
576 self.image.as_ref()
577 }
578
579 /// The VM as the service last described it.
580 pub fn microvm(&self) -> Option<&Microvm> {
581 self.microvm.as_ref()
582 }
583
584 /// The session, once launched.
585 pub fn session(&self) -> Option<&Session> {
586 self.session.as_ref()
587 }
588
589 /// The suspended window this sandbox asked for at launch, once it has launched.
590 pub fn suspended_window(&self) -> Option<Duration> {
591 self.suspended_window
592 }
593
594 /// The tunnel identity, when the launch asked for one ([`RunRequest::identity`]).
595 ///
596 /// What `tunnel --verify-identity` verifies with: the host's secret and the VM's public
597 /// pin. `None` on a launch that did not ask, and the tunnel route then refuses an
598 /// identity request with close code 4401 rather than downgrading.
599 pub fn tunnel_identity(&self) -> Option<&crate::identity::TunnelIdentity> {
600 self.tunnel_identity.as_ref()
601 }
602
603 // ── build ────────────────────────────────────────────────────────────────
604
605 /// Builds an image and waits for it to become usable.
606 ///
607 /// Every local guard runs inside [`ControlPlane::create_image`], before the call —
608 /// which matters because the create happens *after* the caller's artifact upload, so a
609 /// rejection AWS raises costs the upload first.
610 pub async fn build_image(&mut self, request: CreateImageRequest) -> Result<&Image, Error> {
611 let size = request.size;
612 let created = self.control.create_image(request).await?;
613 let mut built = self
614 .control
615 .wait_for_image(&created.identifier, size, WaitOpts::default())
616 .await?;
617 // The logging config survives the wait from the create's own record, because the
618 // readback cannot carry it: `GetMicrovmImage` reports no logging member, and the
619 // resolved log stream's discriminator was minted inside `create_image` — this is
620 // the only copy, and dropping it here would leave the caller unable to name the
621 // stream their build wrote to.
622 built.log_group = created.log_group;
623 built.log_stream = created.log_stream;
624 // Recorded before any launch, because a built image exists whether or not anything
625 // is ever run from it — and the teardown has to be able to name it either way.
626 self.image_exists = true;
627 self.image = Some(built);
628 Ok(self.image.as_ref().expect("just assigned"))
629 }
630
631 /// The artifact bytes to upload to the request's `code_artifact_uri`.
632 ///
633 /// The upload is the caller's: S3 is not in this crate's dependency set.
634 pub fn build_artifact_for(&self, request: &CreateImageRequest) -> Result<Vec<u8>, Error> {
635 self.control.build_artifact_for(request)
636 }
637
638 /// Every local guard [`Self::build_image`] runs, callable **before** the artifact upload.
639 ///
640 /// A delegation to [`ControlPlane::preflight`], on this type so the CLI's build path
641 /// reaches it through the one sandbox it already holds. Local; zero calls. The point is
642 /// ordering: `build_image`'s guards run after the caller's upload, so a request this
643 /// client itself refuses would still cost the S3 PUT unless the caller checks first.
644 pub fn preflight(&self, request: &CreateImageRequest) -> Result<(), Error> {
645 self.control.preflight(request)
646 }
647
648 /// The ARN for `identifier`: an ARN passes through with zero calls, a bare name is
649 /// resolved through the image listing by exact match.
650 ///
651 /// A read-only delegation to [`ControlPlane::resolve_image_arn`], on this type so the
652 /// CLI's launch path reaches it through the one sandbox it already holds. It touches
653 /// none of the five state-machine variables — resolution is a question about the
654 /// account, not about this VM's lifecycle.
655 pub async fn resolve_image_arn(&self, identifier: &str) -> Result<String, Error> {
656 self.control.resolve_image_arn(identifier).await
657 }
658
659 /// The image with exactly `name`, or `None`. Read-only; see
660 /// [`ControlPlane::find_image_by_name`] for the pagination and exact-match rules.
661 pub async fn find_image_by_name(
662 &self,
663 name: &str,
664 ) -> Result<Option<crate::control::ops::MicrovmImageSummaryWire>, Error> {
665 self.control.find_image_by_name(name).await
666 }
667
668 /// The content hash `build --reuse` keys an image name to. Local; zero calls.
669 pub fn artifact_content_hash_for(&self, request: &CreateImageRequest) -> String {
670 self.control.artifact_content_hash_for(request)
671 }
672
673 /// The versions of a managed base image, for pinning
674 /// [`CreateImageRequest::base_image_version`].
675 ///
676 /// A read-only delegation to [`crate::control::ControlPlane::managed_base_versions`], on
677 /// this type for the reason [`Self::resolve_image_arn`] gives: it touches none of the five
678 /// state-machine variables, because a question about AWS's published bases is not a
679 /// question about this VM's lifecycle.
680 pub async fn managed_base_versions(
681 &self,
682 base_image_arn: &str,
683 ) -> Result<Vec<crate::control::ops::ManagedMicrovmImageVersionWire>, Error> {
684 self.control.managed_base_versions(base_image_arn).await
685 }
686
687 /// One version's configuration, state, and availability status. Read-only.
688 pub async fn image_version(
689 &self,
690 identifier: &str,
691 version: &str,
692 ) -> Result<crate::control::ops::MicrovmImageVersionSummaryWire, Error> {
693 self.control.get_image_version(identifier, version).await
694 }
695
696 // ── run (STATE-1, STATE-2, STATE-3) ──────────────────────────────────────
697
698 /// Launches a MicroVM, waits for RUNNING, and returns its session.
699 ///
700 /// # The three state requirements this is
701 ///
702 /// STATE-1: the accepted launch moves the lifecycle to PENDING and records the image as
703 /// existing. STATE-2: the platform reporting RUNNING is what marks the token installed
704 /// — not the launch call, because the run hook is what delivers it and a launch that
705 /// dies during startup delivered nothing. STATE-3: `bootstrap_count` is incremented
706 /// exactly here, and a second `run` on the same sandbox is refused, which is what makes
707 /// "at most once per VM lifetime" a property of the type rather than of a caller's
708 /// discipline.
709 ///
710 /// The agent token rides in `runHookPayload`, which is what keeps it out of the shared
711 /// image snapshot. That is safe because the platform forwards no external traffic until
712 /// the run hook returns 200, so a per-VM secret delivered at launch wins the
713 /// first-writer race through the endpoint.
714 pub async fn run(&mut self, request: RunRequest) -> Result<&mut Session, Error> {
715 // STATE-3's local half. A sandbox that has already bootstrapped cannot bootstrap
716 // again, and the refusal is here rather than in a comment because `run` twice is
717 // the plausible mistake — a retry loop around a launch that timed out.
718 if self.bootstrap_count > 0 || self.microvm.is_some() {
719 return Err(Error::invalid_arg(format!(
720 "this sandbox has already launched a VM ({} bootstrap(s), lifecycle {}), and the \
721 agent token is installed at most once per VM lifetime (STATE-3). A second VM \
722 needs a second Sandbox — reusing this one would either re-deliver a run-hook \
723 payload to a daemon whose one-shot bootstrap refuses it, or silently address \
724 two guests through one handle.",
725 self.bootstrap_count, self.lifecycle,
726 )));
727 }
728
729 let Some(identifier) = request
730 .image_identifier
731 .clone()
732 .or_else(|| self.image.as_ref().map(|image| image.identifier.clone()))
733 else {
734 return Err(Error::new(
735 ErrorKind::Precondition,
736 "no image to launch: pass RunRequest::with_image or call build_image first."
737 .to_string(),
738 ));
739 };
740
741 let agent_token = request.agent_token.clone().unwrap_or_else(mint_agent_token);
742 // Generated before the payload because the payload carries its two public-facing
743 // fields. The VM's secret half lives exactly as long as this binding: `keep()` below
744 // drops it before the launch call returns.
745 let launch_identity = if request.identity {
746 Some(crate::identity::LaunchIdentity::generate()?)
747 } else {
748 None
749 };
750 // Checked even though this builds the JSON itself, because neither half is ours:
751 // the token may be caller-supplied, so someone passing a signed blob rather than a
752 // bearer token is exactly who this catches (TRAP-5), and the launch env is entirely
753 // the caller's. This is the pre-flight refusal — over-ceiling fails here with the
754 // byte count, before the launch, rather than as a `ValidationException` on a member
755 // the caller did not know they were filling.
756 let payload = RunHookPayload::for_launch_with_identity(
757 &agent_token,
758 &request.launch_env,
759 launch_identity.as_ref(),
760 )?;
761
762 let mut wire = RunMicrovmRequest::new(&identifier, payload);
763 wire.image_version = request.image_version.clone();
764 wire.execution_role_arn = request.execution_role_arn.clone();
765 wire.max_idle_sec = request.max_idle_sec;
766 wire.suspended_sec = request.suspended_sec;
767 wire.auto_resume = request.auto_resume;
768 wire.max_duration_sec = request.max_duration_sec;
769 wire.token_scope = request.token_scope.clone();
770 if request.egress {
771 wire = wire.with_egress();
772 }
773
774 let launched = self.control.run_microvm(wire).await?;
775
776 // The durable half of the identity, kept the moment the launch is accepted: the host
777 // secret and the VM's public pin. The VM's own secret ends here — `keep` drops it —
778 // so from this line on the host can verify its VM and impersonate it never.
779 self.tunnel_identity = launch_identity.map(crate::identity::LaunchIdentity::keep);
780
781 // STATE-1: the launch was accepted.
782 self.lifecycle = Lifecycle::Pending;
783 self.image_exists = true;
784 // Recorded here rather than after the wait, because the window the idlePolicy
785 // enforces was set by *this* request and a launch that then fails still leaves a VM
786 // the caller may have to reason about.
787 self.suspended_window = Some(Duration::from_secs(u64::from(request.suspended_sec)));
788 let id = launched.id.clone();
789 self.microvm = Some(launched);
790
791 let running = self
792 .control
793 .wait_for_running(
794 &id,
795 WaitOpts {
796 timeout: request.ready_timeout,
797 poll_interval: LIFECYCLE_POLL_INTERVAL,
798 stall_grace: Duration::MAX,
799 },
800 )
801 .await?;
802
803 // STATE-2. The platform reported the run hook succeeded, so the token is in the
804 // guest's memory — and this is the one place that counts it (STATE-3).
805 self.lifecycle = Lifecycle::Running;
806 self.token_installed = true;
807 self.bootstrap_count += 1;
808 let endpoint = running.endpoint.clone();
809 self.microvm = Some(running);
810
811 let minter = Arc::new(ControlPlaneMinter {
812 control: Arc::clone(&self.control),
813 microvm_id: id,
814 });
815 let mut builder = Session::builder(endpoint, agent_token)
816 .with_minter(minter)
817 .with_port(self.control.port());
818 if let Some(backend) = &self.session_backend {
819 builder = builder.with_backend(Arc::clone(backend));
820 }
821 self.session = Some(builder.build()?);
822 Ok(self.session.as_mut().expect("just assigned"))
823 }
824
825 // ── suspend (STATE-4, STATE-5, STATE-6) ──────────────────────────────────
826
827 /// Freezes the VM and waits for the platform to report it.
828 ///
829 /// A freeze and restore rather than a stop and start: the guest keeps its memory, so the
830 /// token, the filesystem, and every exec record survive. The one thing that does not is
831 /// the guest's view of time — it observes the whole suspension as a single jump, so any
832 /// timeout, lease, or TLS session a running command holds expires at once on resume.
833 ///
834 /// # STATE-5 is checked before the wire, not after
835 ///
836 /// A suspend from anything but RUNNING is refused here with **zero** control-plane
837 /// calls. That is the observable difference between this and a client that lets AWS
838 /// answer, and it is what the test asserts on.
839 pub async fn suspend(&mut self) -> Result<(), Error> {
840 let id = self.require_microvm("suspend")?;
841
842 // STATE-5.
843 if self.lifecycle != Lifecycle::Running {
844 return Err(Error::invalid_arg(format!(
845 "microvm {id} is {} and a suspend is only issued from RUNNING (STATE-5). Refused \
846 here rather than by the service, because the service's answer about a \
847 non-running id does not say which of the two things went wrong — and a suspend \
848 issued from SUSPENDED is a caller who believes they resumed.",
849 self.lifecycle,
850 )));
851 }
852
853 // STATE-4: accepted, so the lifecycle moves before the wait. Acceptance is the
854 // wire call succeeding, so the assignment comes after it: moving to SUSPENDING
855 // first would leave a failed call (a throttle, a dead transport) stuck in a state
856 // neither suspend nor resume accepts, bricking the handle over one bad request.
857 self.control.suspend(&id).await?;
858 self.lifecycle = Lifecycle::Suspending;
859 // Stamped after the call and before the wait, not after the wait: the idlePolicy's
860 // window starts when the platform begins suspending, so timing it from SUSPENDED
861 // would under-count the transition and call a closed window open.
862 self.suspended_at = Some(self.control.clock().elapsed());
863
864 let settled = self
865 .control
866 .wait_for_state(
867 &id,
868 &crate::control::microvm::SUSPEND_WANTED,
869 &[],
870 self.lifecycle_wait(),
871 )
872 .await?;
873
874 // STATE-6, and the TERMINATED case beside it. A VM that dies while suspending is a
875 // state to report rather than an exception out of the middle of a teardown, so the
876 // wait *wants* TERMINATED — and recording it here is what stops a resume from being
877 // offered afterwards (STATE-11).
878 self.lifecycle = match settled.state.as_str() {
879 "SUSPENDED" => Lifecycle::Suspended,
880 "TERMINATED" => {
881 self.was_terminated = true;
882 Lifecycle::Terminated
883 }
884 other => {
885 return Err(Error::new(
886 ErrorKind::Platform,
887 format!(
888 "the suspend wait returned {other}, which is neither SUSPENDED nor \
889 TERMINATED — and those two are what this client asked for."
890 ),
891 ));
892 }
893 };
894 self.microvm = Some(settled);
895 Ok(())
896 }
897
898 // ── resume (STATE-7, STATE-8, STATE-12) ──────────────────────────────────
899
900 /// Thaws the VM and returns a usable session.
901 ///
902 /// # What is deliberately not re-delivered (STATE-7)
903 ///
904 /// Nothing. No run-hook payload, no token, no bootstrap. The in-memory token survived
905 /// the freeze, and re-delivering it would hit the daemon's one-shot bootstrap and be
906 /// refused — a 409 that reads like a broken VM.
907 ///
908 /// # The window is checked first (STATE-12)
909 ///
910 /// Before any wire call, because the answer is already known and calling costs the poll
911 /// timeout to learn something worse. The falsification is a service reporting
912 /// TERMINATED: without this check the resume burns the full deadline and then reports a
913 /// state the client could have named at once.
914 ///
915 /// # The proxy token is dropped (STATE-8)
916 ///
917 /// [`Session::rebind`] invalidates it. The endpoint URL does not change across
918 /// suspend/resume, so the rebind is usually a no-op on the URL — but a token minted
919 /// against the pre-suspend instance may no longer validate, and that rejection reads
920 /// exactly like a dead daemon.
921 pub async fn resume(&mut self) -> Result<&mut Session, Error> {
922 let id = self.require_microvm("resume")?;
923
924 // STATE-11's local half: a terminated VM never returns to RUNNING, so the refusal
925 // comes before the window check and before any call.
926 if self.was_terminated || self.lifecycle == Lifecycle::Terminated {
927 return Err(Error::invalid_arg(format!(
928 "microvm {id} was terminated, and a terminated VM never returns to RUNNING \
929 (STATE-11). There is nothing to resume: the guest's memory is gone, so even a \
930 call the service accepted would hand back a different machine."
931 )));
932 }
933 if self.lifecycle != Lifecycle::Suspended {
934 return Err(Error::invalid_arg(format!(
935 "microvm {id} is {} and a resume is only issued from SUSPENDED (STATE-7).",
936 self.lifecycle,
937 )));
938 }
939
940 // STATE-12, first and locally.
941 self.require_open_suspended_window(&id)?;
942
943 self.control.resume(&id).await?;
944 // `fail_on` is the *dead* states rather than the terminal ones: SUSPENDED is the
945 // state this call was made from, so failing on it would fail every resume. A VM the
946 // idlePolicy terminated during suspension never reaches RUNNING, and waiting only
947 // for RUNNING there burns the full timeout and then reports a timeout message
948 // hiding a cause the service had already stated in `stateReason`.
949 let running = self
950 .control
951 .wait_for_state(
952 &id,
953 &["RUNNING"],
954 &crate::constants::DEAD_STATES,
955 self.lifecycle_wait(),
956 )
957 .await?;
958
959 self.lifecycle = Lifecycle::Running;
960 // STATE-8, through the endpoint the service just reported rather than the one held:
961 // the URL is measured not to change, and reading it from the response is what makes
962 // that a fact this code depends on rather than an assumption it encodes.
963 let endpoint = running.endpoint.clone();
964 self.microvm = Some(running);
965 if let Some(session) = self.session.as_mut() {
966 session.rebind(endpoint);
967 }
968 // Cleared on success so the next cycle's window is measured from the next suspend.
969 // Leaving it set would accumulate every suspension's elapsed time into one total and
970 // reject a resume whose own window is wide open.
971 self.suspended_at = None;
972
973 self.session.as_mut().ok_or_else(|| {
974 Error::new(
975 ErrorKind::Unexpected,
976 "the VM resumed but this sandbox holds no session, which run() always builds"
977 .to_string(),
978 )
979 })
980 }
981
982 /// Rejects a resume the launch-time `idlePolicy` has already made impossible (STATE-12).
983 ///
984 /// The message names the elapsed time, the window, and the `idlePolicy` finding, because
985 /// "cannot resume" alone sends a reader looking for the flag that reopens it.
986 fn require_open_suspended_window(&self, id: &str) -> Result<(), Error> {
987 let (Some(window), Some(since)) = (self.suspended_window, self.suspended_at) else {
988 // No window recorded means this sandbox did not send the launch — the attach
989 // path — and guessing a default would refuse a resume the service would honour.
990 return Ok(());
991 };
992 let elapsed = self.control.clock().elapsed().saturating_sub(since);
993 if elapsed <= window {
994 return Ok(());
995 }
996 Err(Error::new(
997 ErrorKind::WindowClosed,
998 format!(
999 "microvm {id} has been suspended {}s, past the {}s suspendedDurationSeconds \
1000 window set at launch — the idlePolicy terminates a suspended VM once that window \
1001 passes, so there is nothing left to resume (docs/PLATFORM.md, '`idlePolicy`'). \
1002 Refused before ResumeMicrovm because suspendedDurationSeconds exists only in the \
1003 RunMicrovm request: GetMicrovm does not return it, so this client is the only \
1004 party that can name the number. A longer window has to be set at launch on the \
1005 next VM; there is no call that extends this one.",
1006 elapsed.as_secs(),
1007 window.as_secs(),
1008 ),
1009 ))
1010 }
1011
1012 // ── terminate (STATE-9, STATE-10) ────────────────────────────────────────
1013
1014 /// Tears down, best-effort, never erroring.
1015 ///
1016 /// Order: VM, then image, then the log group **last**. The log group is last because the
1017 /// service can recreate a group deleted before its image — and see
1018 /// [`TeardownReport::undeleted`] for why this crate names it rather than deleting it.
1019 pub async fn terminate(&mut self, opts: TeardownOpts) -> TeardownReport {
1020 let mut report = TeardownReport::default();
1021 self.torn_down = true;
1022
1023 // The session first: it holds a cached proxy token whose only remaining use would be
1024 // a request against a VM that is going away.
1025 self.session = None;
1026
1027 // 1. The VM.
1028 if let Some(id) = self.microvm.as_ref().map(|vm| vm.id.clone()) {
1029 // STATE-9. Recorded before the call, so a terminate whose call fails still marks
1030 // the VM as one this client asked to destroy — which is what stops a later
1031 // resume (STATE-11) rather than leaving the sandbox looking resumable.
1032 self.lifecycle = Lifecycle::Terminating;
1033 self.was_terminated = true;
1034
1035 match self.control.terminate(&id).await {
1036 Ok(()) => report.terminate_accepted = true,
1037 Err(error) => {
1038 report.failures.push(format!("terminate {id}: {error}"));
1039 report.undeleted.push(id.clone());
1040 }
1041 }
1042
1043 if report.terminate_accepted
1044 && let Some(timeout) = opts.wait_for_terminated
1045 {
1046 let wait = WaitOpts {
1047 timeout,
1048 poll_interval: LIFECYCLE_POLL_INTERVAL,
1049 stall_grace: Duration::MAX,
1050 };
1051 match self
1052 .control
1053 .wait_for_state(&id, &["TERMINATED"], &[], wait)
1054 .await
1055 {
1056 // STATE-10.
1057 Ok(settled) => {
1058 self.lifecycle = Lifecycle::Terminated;
1059 self.microvm = Some(settled);
1060 }
1061 // Not a leak: the platform accepted the terminate, so the VM is on its
1062 // way out and the lifecycle stays TERMINATING honestly.
1063 Err(error) => report
1064 .failures
1065 .push(format!("waiting for {id} to reach TERMINATED: {error}")),
1066 }
1067 }
1068 }
1069
1070 // 2. The image, retrying — an image in CREATING refuses deletion and a VM still
1071 // terminating holds a reference.
1072 if opts.delete_image {
1073 match self.image.as_ref().map(|image| image.identifier.clone()) {
1074 Some(identifier) => {
1075 let deleted = self
1076 .control
1077 .delete_image(&identifier, opts.delete_attempts, opts.delete_backoff)
1078 .await;
1079 report.image_deleted = Some(deleted);
1080 if deleted {
1081 self.image_exists = false;
1082 } else {
1083 report.failures.push(format!(
1084 "the image {identifier} survived {} delete attempts",
1085 opts.delete_attempts.max(1)
1086 ));
1087 report.undeleted.push(identifier);
1088 }
1089 }
1090 None => report.image_deleted = Some(false),
1091 }
1092 }
1093
1094 // 3. The log group, LAST. Named rather than deleted; see TeardownReport::undeleted.
1095 if opts.delete_log_group
1096 && let Some(group) = self.image.as_ref().map(Image::build_log_group)
1097 {
1098 report.failures.push(format!(
1099 "the build log group {group} was not deleted: CloudWatch Logs is not in this \
1100 crate's dependency set, so it is reported rather than removed. It is \
1101 service-created, which means no Terraform stack owns it and `terraform destroy` \
1102 leaves it behind — six accumulated before anyone noticed."
1103 ));
1104 report.undeleted.push(group);
1105 }
1106
1107 report.lifecycle = Some(self.lifecycle);
1108 report
1109 }
1110
1111 // ── internals ────────────────────────────────────────────────────────────
1112
1113 /// The VM id, or a precondition error naming what was attempted.
1114 fn require_microvm(&self, what: &str) -> Result<String, Error> {
1115 self.microvm
1116 .as_ref()
1117 .map(|vm| vm.id.clone())
1118 .ok_or_else(|| {
1119 Error::new(
1120 ErrorKind::Precondition,
1121 format!("nothing to {what}: this sandbox has not launched a VM."),
1122 )
1123 })
1124 }
1125
1126 /// Five minutes at five-second polls, for suspend, resume, and terminate.
1127 fn lifecycle_wait(&self) -> WaitOpts {
1128 WaitOpts {
1129 timeout: DEFAULT_LIFECYCLE_TIMEOUT,
1130 poll_interval: LIFECYCLE_POLL_INTERVAL,
1131 stall_grace: Duration::MAX,
1132 }
1133 }
1134}
1135
1136/// Warns about a live VM rather than tearing it down.
1137///
1138/// See the module docs: `Drop` cannot await, so a teardown here would either deadlock
1139/// inside a runtime or race the process exit. The warning names the id, because the only
1140/// useful thing a drop can do is tell whoever reads stderr what to go delete.
1141///
1142/// `eprintln!` rather than a log macro because this crate has no logging dependency, and
1143/// taking one on to warn about a leak would be a dependency for a diagnostic.
1144impl Drop for Sandbox {
1145 fn drop(&mut self) {
1146 if self.torn_down {
1147 return;
1148 }
1149 if let Some(vm) = self.microvm.as_ref()
1150 && self.lifecycle.is_live()
1151 {
1152 eprintln!(
1153 "warning: the Sandbox for microvm {} was dropped in {} without terminate(). \
1154 Nothing was torn down — Drop cannot await, so a teardown here would deadlock \
1155 inside a runtime. The VM bills until its maximumDurationInSeconds ceiling: \
1156 terminate it with `microvm terminate {}`.",
1157 vm.id, self.lifecycle, vm.id,
1158 );
1159 }
1160 }
1161}
1162
1163/// A fresh per-VM bearer token: 32 bytes of randomness as 64 hex characters.
1164///
1165/// `getrandom` reaches the kernel CSPRNG directly. The hand-rolled `/dev/urandom`
1166/// read this replaces carried a clock-mixing fallback for a failed read; getrandom
1167/// fails only when the OS pool is genuinely unavailable, and minting a bearer token
1168/// from a clock in that state would be worse than refusing the launch.
1169fn mint_agent_token() -> String {
1170 let mut bytes = [0u8; 32];
1171 getrandom::fill(&mut bytes).expect("the OS random pool is available");
1172 const_hex::encode(bytes)
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177 use super::*;
1178 use crate::control::fake::{self as fake, Answer, FakeControlPlane, TestClock};
1179 use crate::control::transport::Method;
1180
1181 /// A sandbox over the contract recorder, plus the two handles a test asserts through.
1182 ///
1183 /// The recorder is T-W2-4's, deliberately: its answers are literal JSON in the service
1184 /// model's spelling rather than values serialized from this crate's types, so a member
1185 /// this lane misreads cannot be misread identically by the fake.
1186 fn planted() -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
1187 let recorder = Arc::new(FakeControlPlane::new());
1188 let clock = Arc::new(TestClock::new());
1189 let plane = ControlPlane::with_transport(
1190 Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
1191 Region::UsEast1,
1192 Arc::clone(&clock) as Arc<dyn crate::control::Clock>,
1193 );
1194 (Sandbox::with_control_plane(plane), recorder, clock)
1195 }
1196
1197 /// Queues everything a launch to RUNNING needs.
1198 fn answer_launch(recorder: &FakeControlPlane) {
1199 recorder
1200 .answer(
1201 "RunMicrovm",
1202 Answer::ok(fake::microvm_response("PENDING", None)),
1203 )
1204 .answer(
1205 "GetMicrovm",
1206 Answer::ok(fake::microvm_response("RUNNING", None)),
1207 )
1208 .answer(
1209 "CreateMicrovmAuthToken",
1210 Answer::ok(fake::auth_token_response("proxy-token")),
1211 );
1212 }
1213
1214 /// A launched sandbox in RUNNING, which is where four of the twelve keys start.
1215 async fn launched() -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
1216 let (mut sandbox, recorder, clock) = planted();
1217 answer_launch(&recorder);
1218 sandbox
1219 .run(RunRequest::new().with_image("arn:image"))
1220 .await
1221 .expect("the launch reaches RUNNING");
1222 (sandbox, recorder, clock)
1223 }
1224
1225 /// Drives a launched sandbox to SUSPENDED, which is where resume starts.
1226 ///
1227 /// Both `GetMicrovm` answers are queued **before** the launch rather than one before
1228 /// each wait, and that is not a style choice. The recorder repeats its last queued
1229 /// answer, so a queue left at `[RUNNING]` after the launch and then appended to becomes
1230 /// `[RUNNING, SUSPENDED]` — the suspend wait pops the stale RUNNING, sleeps a poll
1231 /// interval, and the fake's `sleep` **advances the clock**. That five seconds is
1232 /// invisible until it lands in the middle of the STATE-12 window arithmetic, which is
1233 /// exactly where it first showed up. Queueing both up front means every wait matches on
1234 /// its first poll and no test clock moves except when a test moves it.
1235 async fn suspended_with_window(
1236 suspended_sec: u32,
1237 ) -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
1238 let (mut sandbox, recorder, clock) = planted();
1239 recorder
1240 .answer(
1241 "RunMicrovm",
1242 Answer::ok(fake::microvm_response("PENDING", None)),
1243 )
1244 .answer(
1245 "GetMicrovm",
1246 Answer::ok(fake::microvm_response("RUNNING", None)),
1247 )
1248 .answer(
1249 "GetMicrovm",
1250 Answer::ok(fake::microvm_response("SUSPENDED", None)),
1251 )
1252 .answer(
1253 "CreateMicrovmAuthToken",
1254 Answer::ok(fake::auth_token_response("proxy-token")),
1255 )
1256 .answer("SuspendMicrovm", Answer::ok(fake::empty_response()));
1257
1258 sandbox
1259 .run(
1260 RunRequest::new()
1261 .with_image("arn:image")
1262 .with_suspended_sec(suspended_sec),
1263 )
1264 .await
1265 .expect("launches");
1266 sandbox.suspend().await.expect("suspends");
1267 assert_eq!(
1268 clock.now(),
1269 Duration::ZERO,
1270 "no wait may have slept, or the window arithmetic below is measuring the fake's \
1271 poll interval as well as the elapsed suspension"
1272 );
1273 (sandbox, recorder, clock)
1274 }
1275
1276 /// A suspended sandbox at the default ten-minute window.
1277 async fn suspended() -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
1278 suspended_with_window(600).await
1279 }
1280
1281 /// **STATE-1 and STATE-2.** A launch accepted is PENDING with the image recorded as
1282 /// existing; the platform reporting the run hook succeeded is what marks the token
1283 /// installed.
1284 ///
1285 /// The two halves are asserted with the *same* fake because they are the same call, and
1286 /// what distinguishes them is which fact is recorded when: `image_exists` is true from
1287 /// the accepted launch, `token_installed` only from the RUNNING report. A client that
1288 /// set both at the launch call would pass an end-state assertion and be wrong about a
1289 /// VM that died during startup — which is the next test.
1290 #[tokio::test]
1291 async fn a_launch_records_the_image_and_the_running_report_installs_the_token() {
1292 let (mut sandbox, recorder, _) = planted();
1293 assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
1294 assert!(
1295 !sandbox.image_exists(),
1296 "nothing is recorded before a launch"
1297 );
1298 assert!(!sandbox.token_installed());
1299
1300 answer_launch(&recorder);
1301 let session = sandbox
1302 .run(RunRequest::new().with_image("arn:image"))
1303 .await
1304 .expect("launches");
1305 assert_eq!(
1306 session.endpoint(),
1307 "https://mvm-abc123.microvm.us-east-1.amazonaws.com"
1308 );
1309
1310 assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
1311 assert!(sandbox.image_exists(), "STATE-1: the image is recorded");
1312 assert!(sandbox.token_installed(), "STATE-2: the token is installed");
1313 assert_eq!(sandbox.bootstrap_count(), 1);
1314 assert_eq!(sandbox.microvm().expect("launched").id, "mvm-abc123");
1315
1316 // The payload really carried the token, read off the wire member rather than from
1317 // the request type — a field on a struct proves nothing about what was emitted.
1318 let body = recorder.first_body("RunMicrovm");
1319 let payload = body["runHookPayload"].as_str().expect("a string");
1320 assert!(payload.starts_with(r#"{"agent_token":"#), "{payload}");
1321 assert_eq!(body["idlePolicy"]["suspendedDurationSeconds"], 600);
1322 }
1323
1324 /// A launch env reaches the wire member the daemon parses, and it is the only thing
1325 /// that changes about the request.
1326 ///
1327 /// Read off `runHookPayload` rather than off the request struct: a field on a struct
1328 /// proves nothing about what was emitted, which is the same argument the test above
1329 /// makes about the token.
1330 #[tokio::test]
1331 async fn a_launch_env_reaches_the_run_hook_payload_on_the_wire() {
1332 let (mut sandbox, recorder, _) = planted();
1333 answer_launch(&recorder);
1334 sandbox
1335 .run(
1336 RunRequest::new()
1337 .with_image("arn:image")
1338 .with_launch_env("ANTHROPIC_BASE_URL", "https://gateway.example")
1339 .with_launch_env("PATH", "/usr/local/bin:/usr/bin:/bin"),
1340 )
1341 .await
1342 .expect("launches");
1343
1344 let body = recorder.first_body("RunMicrovm");
1345 let payload = body["runHookPayload"].as_str().expect("a string");
1346 // One parse deeper, because that is where the daemon reads it from too.
1347 let inner: serde_json::Value =
1348 serde_json::from_str(payload).expect("the payload is itself JSON");
1349 assert!(
1350 inner["agent_token"].as_str().is_some_and(|t| !t.is_empty()),
1351 "the token still rides alongside: {payload}"
1352 );
1353 assert_eq!(
1354 inner["env"]["ANTHROPIC_BASE_URL"],
1355 "https://gateway.example"
1356 );
1357 assert_eq!(inner["env"]["PATH"], "/usr/local/bin:/usr/bin:/bin");
1358 }
1359
1360 /// **A pinned `imageVersion` reaches the wire through the sandbox**, and an unpinned
1361 /// launch omits the member entirely.
1362 ///
1363 /// This is the layer a caller actually uses, so the forwarding is what needs asserting:
1364 /// [`RunRequest::image_version`] is a field on a struct and proves nothing about the
1365 /// emitted body until it is read off the wire member.
1366 ///
1367 /// **Falsification** — run 2026-08-16. Drop `wire.image_version = ...` from `run` and the
1368 /// pinned assertion goes red with the member absent, while every other launch test still
1369 /// passes — which is why this one is here.
1370 #[tokio::test]
1371 async fn a_pinned_image_version_is_forwarded_to_the_launch_request() {
1372 let (mut sandbox, recorder, _) = planted();
1373 answer_launch(&recorder);
1374 sandbox
1375 .run(
1376 RunRequest::new()
1377 .with_image("arn:image")
1378 .with_image_version("2.0"),
1379 )
1380 .await
1381 .expect("launches");
1382 assert_eq!(
1383 recorder.first_body("RunMicrovm")["imageVersion"],
1384 "2.0",
1385 "a canary has to launch against the version it means to test"
1386 );
1387
1388 let (mut sandbox, recorder, _) = planted();
1389 answer_launch(&recorder);
1390 sandbox
1391 .run(RunRequest::new().with_image("arn:image"))
1392 .await
1393 .expect("launches");
1394 assert!(
1395 recorder
1396 .first_body("RunMicrovm")
1397 .get("imageVersion")
1398 .is_none(),
1399 "an unpinned launch sends what this client always sent"
1400 );
1401 }
1402
1403 /// **The local refusal, with zero control-plane calls.**
1404 ///
1405 /// The observable difference between this client and one that lets AWS answer, and the
1406 /// same shape as STATE-5's suspend refusal: an over-budget launch env fails before the
1407 /// launch rather than as a `ValidationException` on a member the caller did not know
1408 /// they were filling. botocore does not enforce the ceiling client-side, so without
1409 /// this there is no local signal at all.
1410 ///
1411 /// **Falsification** — build the payload after `run_microvm` instead of before, and the
1412 /// call count assertion goes red.
1413 #[tokio::test]
1414 async fn an_over_budget_launch_env_is_refused_before_any_control_plane_call() {
1415 let (mut sandbox, recorder, _) = planted();
1416 answer_launch(&recorder);
1417
1418 let error = sandbox
1419 .run(
1420 RunRequest::new()
1421 .with_image("arn:image")
1422 .with_launch_env("AWS_SESSION_TOKEN", "t".repeat(4096)),
1423 )
1424 .await
1425 .expect_err("a credential-scale launch env does not fit the payload");
1426
1427 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1428 let message = error.to_string();
1429 assert!(message.contains("ceiling of 4096"), "{message}");
1430 assert!(message.contains("launch env contributed"), "{message}");
1431 assert_eq!(
1432 recorder.calls().len(),
1433 0,
1434 "the refusal has to be local: a launch that reached AWS costs a VM and a bill"
1435 );
1436 // And the sandbox is left usable rather than half-launched, so a caller can trim
1437 // the env and retry through the same handle.
1438 assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
1439 assert_eq!(sandbox.bootstrap_count(), 0);
1440 assert!(sandbox.microvm().is_none());
1441 }
1442
1443 /// **Issue #24's guards reach through `Sandbox`, which is the layer both bindings use.**
1444 ///
1445 /// `microvms-py`'s `run` and `microvms-js`'s `run` both build a [`RunRequest`] and hand it to
1446 /// [`Sandbox::run`], which fills a `RunMicrovmRequest` and calls
1447 /// [`crate::control::ControlPlane::run_microvm`]. So the guards there cover the bindings — but
1448 /// "cover" is a claim about a call chain, and a chain is what a refactor breaks. This asserts
1449 /// it at the layer the bindings actually enter, so a `Sandbox::run` that stopped delegating
1450 /// (or a binding-side default that bypassed the request type) fails a test rather than shipping
1451 /// an unguarded surface to Python and Node.
1452 ///
1453 /// `max_idle_sec` is the case that matters most here, because it is a plain `u32` keyword
1454 /// argument on both bindings with no type narrowing it: `sandbox.run(max_idle_sec=59)` is what
1455 /// a Python caller writes, and before this it reached the wire.
1456 ///
1457 /// **Guard proof.** Delete `require_idle_duration` from `run_microvm` and the idle row goes red
1458 /// on the call count; delete `require_valid_role_arn` and the role row does. Neither guard is in
1459 /// this file, which is the point — the test is about the chain.
1460 #[tokio::test]
1461 async fn the_bindings_layer_refuses_an_illegal_launch_with_zero_calls() {
1462 let cases: [(&str, RunRequest, &str); 3] = [
1463 (
1464 "max_idle_sec=59, which is what a Python keyword argument passes",
1465 RunRequest {
1466 max_idle_sec: 59,
1467 ..RunRequest::new().with_image("arn:image")
1468 },
1469 "maxIdleDurationSeconds",
1470 ),
1471 (
1472 "an execution role that is a bare name",
1473 RunRequest {
1474 execution_role_arn: Some("execution-role".to_string()),
1475 ..RunRequest::new().with_image("arn:image")
1476 },
1477 "role *name*",
1478 ),
1479 (
1480 "a pinned version with a trailing newline",
1481 RunRequest::new()
1482 .with_image("arn:image")
1483 .with_image_version("2.0\n"),
1484 "contains whitespace",
1485 ),
1486 ];
1487
1488 for (label, request, expected) in cases {
1489 let (mut sandbox, recorder, _) = planted();
1490 // The launch answered, so a missing guard is a *successful* launch — a real VM and a
1491 // real bill — rather than a different failure.
1492 answer_launch(&recorder);
1493
1494 // `expect_err` needs the Ok type to be `Debug`, and `run` answers `&mut Session`
1495 // (which is not) — so the discriminant is matched instead. That is also the more
1496 // honest assertion: it says the launch produced no session at all.
1497 let Err(error) = sandbox.run(request).await else {
1498 panic!("{label} must be refused");
1499 };
1500 assert_eq!(error.kind(), ErrorKind::InvalidArg, "{label}");
1501 assert!(
1502 error.to_string().contains(expected),
1503 "{label}: wanted {expected:?}, got {error}"
1504 );
1505 assert_eq!(
1506 recorder.calls().len(),
1507 0,
1508 "{label}: the refusal has to be local, because a launch that reached AWS costs a \
1509 VM and a bill"
1510 );
1511 assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
1512 assert!(sandbox.microvm().is_none());
1513 }
1514 }
1515
1516 /// A launch whose VM dies during startup leaves the token **not** installed, because
1517 /// the run hook is what delivers it and a dead VM ran no hook.
1518 ///
1519 /// The distinction this pins is the one the test above cannot: both a correct client and
1520 /// one that installs the token at the launch call reach RUNNING with the token set, and
1521 /// only this case separates them.
1522 #[tokio::test]
1523 async fn a_launch_that_dies_during_startup_installs_no_token() {
1524 let (mut sandbox, recorder, _) = planted();
1525 recorder
1526 .answer(
1527 "RunMicrovm",
1528 Answer::ok(fake::microvm_response("PENDING", None)),
1529 )
1530 .answer(
1531 "GetMicrovm",
1532 Answer::ok(fake::microvm_response(
1533 "TERMINATED",
1534 Some("run hook returned 500"),
1535 )),
1536 );
1537
1538 let error = sandbox
1539 .run(RunRequest::new().with_image("arn:image"))
1540 .await
1541 .expect_err("a VM that died during startup is not a launch");
1542 assert_eq!(error.kind(), ErrorKind::LaunchDied);
1543 assert!(
1544 error.to_string().contains("run hook returned 500"),
1545 "{error}"
1546 );
1547
1548 assert!(
1549 !sandbox.token_installed(),
1550 "the run hook never answered, so nothing was installed"
1551 );
1552 assert_eq!(
1553 sandbox.bootstrap_count(),
1554 0,
1555 "a bootstrap counted here would make STATE-3's ceiling unreachable for a retry"
1556 );
1557 assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
1558 assert!(
1559 sandbox.image_exists(),
1560 "STATE-1 still holds: the launch was accepted against a real image"
1561 );
1562 }
1563
1564 /// **STATE-3, the guard proof.** A second `run` on one sandbox is refused, and it is
1565 /// refused with **zero** further control-plane calls.
1566 ///
1567 /// The call count is the assertion that matters. A client that let the second launch
1568 /// through would create a second VM and silently address two guests through one handle,
1569 /// and it would also deliver a second run-hook payload to a daemon whose one-shot
1570 /// bootstrap answers 409 — so "an error came back" is not enough to tell the two apart.
1571 ///
1572 /// **Falsification** — delete the `bootstrap_count > 0` branch from `run` and this test
1573 /// is red on both the count and the call total. Verified; see the packet's guard proofs.
1574 #[tokio::test]
1575 async fn a_second_run_on_one_sandbox_is_refused_before_any_call() {
1576 let (mut sandbox, recorder, _) = launched().await;
1577 assert_eq!(sandbox.bootstrap_count(), 1);
1578 let before = recorder.calls().len();
1579
1580 let error = sandbox
1581 .run(RunRequest::new().with_image("arn:image"))
1582 .await
1583 .expect_err("the token is installed at most once per VM lifetime");
1584 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1585 assert!(error.to_string().contains("STATE-3"), "{error}");
1586 assert!(
1587 error.to_string().contains("needs a second Sandbox"),
1588 "the remedy has to be nameable: {error}"
1589 );
1590
1591 assert_eq!(
1592 sandbox.bootstrap_count(),
1593 1,
1594 "bootstrap_count <= 1 is the Z3-proved invariant"
1595 );
1596 assert_eq!(
1597 recorder.calls().len(),
1598 before,
1599 "the refusal must cost no control-plane call"
1600 );
1601 assert_eq!(recorder.call_count("RunMicrovm"), 1);
1602 }
1603
1604 /// **STATE-4 and STATE-6.** A suspend from RUNNING moves to SUSPENDING before the wait,
1605 /// and the platform reporting SUSPENDED is what moves it to SUSPENDED.
1606 #[tokio::test]
1607 async fn a_suspend_from_running_passes_through_suspending_to_suspended() {
1608 let (sandbox, recorder, _) = suspended().await;
1609 assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended);
1610 assert!(
1611 sandbox.token_installed(),
1612 "a freeze keeps the guest's memory, so the token survives"
1613 );
1614 assert_eq!(sandbox.bootstrap_count(), 1, "no re-bootstrap on a freeze");
1615
1616 let calls = recorder.calls();
1617 let suspend = calls
1618 .iter()
1619 .find(|call| call.operation == "SuspendMicrovm")
1620 .expect("the suspend went out");
1621 assert_eq!(suspend.method, Method::Post);
1622 assert_eq!(suspend.path, "/2025-09-09/microvms/mvm-abc123/suspend");
1623 }
1624
1625 /// A suspend whose VM dies while suspending reports TERMINATED rather than raising, and
1626 /// records it — which is what stops a later resume.
1627 ///
1628 /// TERMINATED is *wanted* by the suspend wait for a reason: a VM that dies mid-suspend
1629 /// is a state to report, not an exception out of the middle of a teardown.
1630 #[tokio::test]
1631 async fn a_vm_that_dies_while_suspending_is_recorded_rather_than_raised() {
1632 let (mut sandbox, recorder, _) = launched().await;
1633 recorder
1634 .answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
1635 .answer(
1636 "GetMicrovm",
1637 Answer::ok(fake::microvm_response("TERMINATED", Some("idle policy"))),
1638 );
1639
1640 sandbox
1641 .suspend()
1642 .await
1643 .expect("a death mid-suspend is a state, not an error");
1644 assert_eq!(sandbox.lifecycle(), Lifecycle::Terminated);
1645 assert!(
1646 sandbox.was_terminated(),
1647 "STATE-11's precondition is recorded"
1648 );
1649 }
1650
1651 /// A suspend whose wire call fails leaves the sandbox in RUNNING, and a retry works.
1652 ///
1653 /// STATE-4's "accepted" is the wire call succeeding. A client that moved to SUSPENDING
1654 /// before the call would strand a failed call there — a state neither suspend nor
1655 /// resume accepts, so one throttled or dropped request would brick the handle.
1656 /// **Falsification** — move `self.lifecycle = Lifecycle::Suspending` back above the
1657 /// `control.suspend` call and the first assertion here reads SUSPENDING, and the retry
1658 /// is refused by the STATE-5 guard.
1659 #[tokio::test]
1660 async fn a_suspend_whose_call_fails_stays_running_and_can_be_retried() {
1661 let (mut sandbox, recorder, _) = planted();
1662 recorder
1663 .answer(
1664 "RunMicrovm",
1665 Answer::ok(fake::microvm_response("PENDING", None)),
1666 )
1667 .answer(
1668 "GetMicrovm",
1669 Answer::ok(fake::microvm_response("RUNNING", None)),
1670 )
1671 .answer(
1672 "GetMicrovm",
1673 Answer::ok(fake::microvm_response("SUSPENDED", None)),
1674 )
1675 .answer(
1676 "CreateMicrovmAuthToken",
1677 Answer::ok(fake::auth_token_response("proxy-token")),
1678 )
1679 // A 409 rather than a 429 or a transport cut, because those two are retried
1680 // inside `send_with_retry` and this test wants the call to fail once, fast.
1681 .answer("SuspendMicrovm", Answer::failure(409, "ConflictException"))
1682 .answer("SuspendMicrovm", Answer::ok(fake::empty_response()));
1683
1684 sandbox
1685 .run(RunRequest::new().with_image("arn:image"))
1686 .await
1687 .expect("launches");
1688
1689 sandbox
1690 .suspend()
1691 .await
1692 .expect_err("the control plane refused the suspend");
1693 assert_eq!(
1694 sandbox.lifecycle(),
1695 Lifecycle::Running,
1696 "a refused suspend must not move the lifecycle: SUSPENDING accepts neither a \
1697 suspend nor a resume, so recording it here would brick the handle"
1698 );
1699
1700 sandbox.suspend().await.expect("the retry suspends");
1701 assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended);
1702 assert_eq!(recorder.call_count("SuspendMicrovm"), 2);
1703 }
1704
1705 /// **STATE-5, the guard proof.** A suspend from anything but RUNNING is refused with
1706 /// **zero** control-plane calls.
1707 ///
1708 /// Every non-RUNNING state, so a state added to `Lifecycle` later is not silently
1709 /// exempt. The count is the load-bearing assertion: letting the call go and reading the
1710 /// service's answer also produces an error, and that error is about a non-running id
1711 /// rather than about which of two things the caller got wrong.
1712 ///
1713 /// **Falsification** — delete the `lifecycle != Running` branch from `suspend` and the
1714 /// SUSPENDED case emits a `SuspendMicrovm` call, turning the count assertion red.
1715 /// Verified; see the packet's guard proofs.
1716 #[tokio::test]
1717 async fn a_suspend_from_a_non_running_state_reaches_no_control_plane_call() {
1718 // From SUSPENDED — the caller who believes they resumed.
1719 let (mut sandbox, recorder, _) = suspended().await;
1720 let before = recorder.call_count("SuspendMicrovm");
1721
1722 let error = sandbox
1723 .suspend()
1724 .await
1725 .expect_err("a suspend is only issued from RUNNING");
1726 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1727 assert!(error.to_string().contains("STATE-5"), "{error}");
1728 assert!(error.to_string().contains("SUSPENDED"), "{error}");
1729 assert_eq!(
1730 recorder.call_count("SuspendMicrovm"),
1731 before,
1732 "the refusal must be local: no second suspend went to the wire"
1733 );
1734
1735 // And from PENDING, before anything launched at all.
1736 let (mut fresh, fresh_recorder, _) = planted();
1737 let error = fresh.suspend().await.expect_err("nothing to suspend");
1738 assert_eq!(error.kind(), ErrorKind::Precondition);
1739 assert_eq!(fresh_recorder.calls().len(), 0);
1740 }
1741
1742 /// **STATE-7 and STATE-8.** A resume from SUSPENDED returns to RUNNING, re-delivers
1743 /// **nothing**, and drops the cached proxy token.
1744 ///
1745 /// Three assertions, and each one is a different failure mode. The bootstrap count says
1746 /// no run-hook payload was re-delivered — which a daemon's one-shot bootstrap would
1747 /// answer 409 to, reading like a broken VM. The `RunMicrovm` count says no second launch
1748 /// happened. And `is_cached` says the token was invalidated, which is the only
1749 /// observable difference on a path where the endpoint URL does not change: a client that
1750 /// kept the token would produce identical requests until the pre-suspend token stopped
1751 /// validating, and that rejection reads exactly like a dead daemon.
1752 #[tokio::test]
1753 async fn a_resume_reuses_the_token_redelivers_nothing_and_drops_the_proxy_token() {
1754 let (mut sandbox, recorder, _) = suspended().await;
1755
1756 // The session mints once before the suspend, so there is a cached token to drop.
1757 let auth = Arc::clone(
1758 sandbox
1759 .session()
1760 .expect("launched")
1761 .proxy_auth()
1762 .expect("the launch wired a minter"),
1763 );
1764 auth.headers().await.expect("mints");
1765 assert!(
1766 auth.is_cached(),
1767 "there must be a token for the drop to matter"
1768 );
1769 assert_eq!(auth.mint_count(), 1);
1770
1771 recorder
1772 .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
1773 .answer(
1774 "GetMicrovm",
1775 Answer::ok(fake::microvm_response("RUNNING", None)),
1776 );
1777 let session = sandbox.resume().await.expect("resumes");
1778 assert_eq!(
1779 session.endpoint(),
1780 "https://mvm-abc123.microvm.us-east-1.amazonaws.com"
1781 );
1782
1783 assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
1784 assert!(
1785 sandbox.token_installed(),
1786 "STATE-7: the installed token is reused"
1787 );
1788 assert_eq!(
1789 sandbox.bootstrap_count(),
1790 1,
1791 "STATE-7: a resume re-delivers no run-hook payload"
1792 );
1793 assert_eq!(
1794 recorder.call_count("RunMicrovm"),
1795 1,
1796 "a resume is not a second launch"
1797 );
1798 assert!(
1799 !auth.is_cached(),
1800 "STATE-8: the cached proxy token survived the resume"
1801 );
1802 }
1803
1804 /// **STATE-8's guard proof, on the mint count.** The request after a resume mints a
1805 /// fresh token rather than reusing the pre-suspend one.
1806 ///
1807 /// Separate from the test above because `is_cached` is a fact about the cache and this is
1808 /// a fact about the wire: a client that dropped the cache but kept emitting the old
1809 /// header would pass the first assertion and fail every request.
1810 ///
1811 /// **Falsification** — delete the `proxy.invalidate()` line from `Session::rebind` and
1812 /// the mint count stays at 1 here. Verified; see the packet's guard proofs.
1813 #[tokio::test]
1814 async fn the_request_after_a_resume_mints_a_fresh_proxy_token() {
1815 let (mut sandbox, recorder, _) = suspended().await;
1816 let auth = Arc::clone(
1817 sandbox
1818 .session()
1819 .expect("launched")
1820 .proxy_auth()
1821 .expect("wired"),
1822 );
1823 auth.headers().await.expect("mints");
1824 assert_eq!(auth.mint_count(), 1);
1825
1826 recorder
1827 .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
1828 .answer(
1829 "GetMicrovm",
1830 Answer::ok(fake::microvm_response("RUNNING", None)),
1831 );
1832 sandbox.resume().await.expect("resumes");
1833
1834 // No clock movement at all, so a re-mint here is caused by the invalidation rather
1835 // than by the refresh window rolling over.
1836 auth.headers().await.expect("re-mints");
1837 assert_eq!(
1838 auth.mint_count(),
1839 2,
1840 "STATE-8: the resume did not force a fresh mint"
1841 );
1842 }
1843
1844 /// **STATE-12, the guard proof.** A resume past the launch-time suspended window is
1845 /// refused locally, with **zero** resume calls, and the message names the window.
1846 ///
1847 /// Four assertions, and the packet asks for all four because each rules out a different
1848 /// wrong implementation. `ErrorKind::WindowClosed` rather than `Timeout` separates this
1849 /// from the client that waits. Zero `ResumeMicrovm` calls is what "before any wire call"
1850 /// means. The elapsed reading rules out an implementation that polled to the deadline
1851 /// first — the fake's clock advances on every `sleep`, so a poll loop here would show up
1852 /// as time passed. And the message naming both numbers plus `idlePolicy` is what sends a
1853 /// reader to the finding rather than looking for the flag that reopens the window.
1854 ///
1855 /// **Falsification** — delete the `require_open_suspended_window` call from `resume` and
1856 /// the fake answers TERMINATED, so this test fails with an `ErrorKind::LaunchDied` after
1857 /// a `ResumeMicrovm` call, naming neither the window nor the seconds elapsed. Verified;
1858 /// see the packet's guard proofs.
1859 #[tokio::test]
1860 async fn a_resume_past_the_suspended_window_is_refused_before_the_wire() {
1861 // A short window, so the arithmetic is legible: sixty seconds asked for at launch.
1862 let (mut sandbox, recorder, clock) = suspended_with_window(60).await;
1863 assert_eq!(sandbox.suspended_window(), Some(Duration::from_secs(60)));
1864
1865 // The window closes. This is the whole of what the clock injection buys.
1866 clock.advance(Duration::from_secs(61));
1867
1868 // What a service says about a VM the idlePolicy already terminated — which is what a
1869 // client without the local check would spend its poll timeout discovering.
1870 recorder
1871 .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
1872 .answer(
1873 "GetMicrovm",
1874 Answer::ok(fake::microvm_response(
1875 "TERMINATED",
1876 Some("suspended window elapsed"),
1877 )),
1878 );
1879 let elapsed_before = clock.now();
1880 let resumes_before = recorder.call_count("ResumeMicrovm");
1881
1882 let error = sandbox
1883 .resume()
1884 .await
1885 .expect_err("the window the launch set has closed");
1886
1887 assert_eq!(error.kind(), ErrorKind::WindowClosed);
1888 assert_eq!(error.code(), "ERR_WINDOW_CLOSED");
1889 let message = error.to_string();
1890 assert!(message.contains("61s"), "the elapsed time: {message}");
1891 assert!(
1892 message.contains("60s suspendedDurationSeconds"),
1893 "the window has to be named: {message}"
1894 );
1895 assert!(message.contains("idlePolicy"), "the finding: {message}");
1896 assert!(
1897 message.contains("GetMicrovm does not return it"),
1898 "why the client is the only party that can say this: {message}"
1899 );
1900 assert_eq!(
1901 recorder.call_count("ResumeMicrovm"),
1902 resumes_before,
1903 "the refusal must come before ResumeMicrovm"
1904 );
1905 assert_eq!(
1906 clock.now(),
1907 elapsed_before,
1908 "the refusal must be immediate rather than polled to the deadline"
1909 );
1910 }
1911
1912 /// A resume **inside** the window goes through, so the guard is a comparison rather than
1913 /// a blanket refusal of every resume.
1914 ///
1915 /// The boundary is inclusive: elapsed exactly equal to the window is still open, matching
1916 /// the Python's `elapsed <= window`.
1917 #[tokio::test]
1918 async fn a_resume_inside_the_window_is_allowed_and_the_boundary_is_inclusive() {
1919 let (mut sandbox, recorder, clock) = suspended_with_window(60).await;
1920
1921 // Exactly at the window.
1922 clock.advance(Duration::from_secs(60));
1923 recorder
1924 .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
1925 .answer(
1926 "GetMicrovm",
1927 Answer::ok(fake::microvm_response("RUNNING", None)),
1928 );
1929 sandbox
1930 .resume()
1931 .await
1932 .expect("60s == the 60s window is open");
1933 assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
1934 assert_eq!(recorder.call_count("ResumeMicrovm"), 1);
1935 }
1936
1937 /// A successful resume clears the stamp, so the next cycle's window is measured from the
1938 /// next suspend rather than from the first one.
1939 ///
1940 /// The failure this rules out is subtle and would only show on a second cycle:
1941 /// accumulating every suspension's elapsed time into one total refuses a resume whose own
1942 /// window is wide open. The clock is advanced past the window *between* the two cycles,
1943 /// which is what makes the accumulating implementation fail here.
1944 #[tokio::test]
1945 async fn a_successful_resume_clears_the_stamp_so_a_second_cycle_measures_its_own_window() {
1946 let (mut sandbox, recorder, clock) = planted();
1947 // Every `GetMicrovm` answer for both cycles, in the order the waits consume them:
1948 // the launch's RUNNING, then SUSPENDED / RUNNING twice. Queued up front for the
1949 // reason `suspended_with_window` documents — a stale answer left at the head makes a
1950 // wait poll twice, and the fake's `sleep` moves the very clock this test is measuring.
1951 recorder
1952 .answer(
1953 "RunMicrovm",
1954 Answer::ok(fake::microvm_response("PENDING", None)),
1955 )
1956 .answer(
1957 "CreateMicrovmAuthToken",
1958 Answer::ok(fake::auth_token_response("proxy-token")),
1959 )
1960 .answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
1961 .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
1962 .answer(
1963 "GetMicrovm",
1964 Answer::ok(fake::microvm_response("RUNNING", None)),
1965 )
1966 .answer(
1967 "GetMicrovm",
1968 Answer::ok(fake::microvm_response("SUSPENDED", None)),
1969 )
1970 .answer(
1971 "GetMicrovm",
1972 Answer::ok(fake::microvm_response("RUNNING", None)),
1973 )
1974 .answer(
1975 "GetMicrovm",
1976 Answer::ok(fake::microvm_response("SUSPENDED", None)),
1977 )
1978 .answer(
1979 "GetMicrovm",
1980 Answer::ok(fake::microvm_response("RUNNING", None)),
1981 );
1982 sandbox
1983 .run(
1984 RunRequest::new()
1985 .with_image("arn:image")
1986 .with_suspended_sec(60),
1987 )
1988 .await
1989 .expect("launches");
1990
1991 for cycle in 0..2 {
1992 sandbox
1993 .suspend()
1994 .await
1995 .unwrap_or_else(|error| panic!("cycle {cycle} suspend: {error}"));
1996 assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended, "cycle {cycle}");
1997
1998 // Forty-five seconds each time — inside the sixty-second window on its own, and
1999 // ninety in total. An implementation that never cleared the stamp measures the
2000 // total and refuses the second resume, which is the whole point of the loop.
2001 clock.advance(Duration::from_secs(45));
2002
2003 sandbox.resume().await.unwrap_or_else(|error| {
2004 panic!("cycle {cycle} resume, whose own window is wide open: {error}")
2005 });
2006 assert_eq!(sandbox.lifecycle(), Lifecycle::Running, "cycle {cycle}");
2007 assert_eq!(
2008 sandbox.bootstrap_count(),
2009 1,
2010 "cycle {cycle}: no re-bootstrap"
2011 );
2012 }
2013
2014 assert_eq!(
2015 clock.now(),
2016 Duration::from_secs(90),
2017 "ninety seconds of accumulated suspension against a sixty-second window: this is \
2018 the total an implementation that never cleared the stamp would have compared"
2019 );
2020 assert_eq!(
2021 recorder.call_count("ResumeMicrovm"),
2022 2,
2023 "both cycles resumed"
2024 );
2025 }
2026
2027 /// **STATE-11, the resume-after-terminate case the packet names.** A terminated VM never
2028 /// returns to RUNNING, and the recorder sees **zero** resume wire calls.
2029 ///
2030 /// The zero count is the assertion the packet asks for, and it is the right one: a client
2031 /// that called and read the answer would also fail, with whatever the service says about
2032 /// a terminated id — which is a different statement from "this VM is gone and even a
2033 /// successful call would hand you a different machine".
2034 #[tokio::test]
2035 async fn a_resume_after_terminate_records_zero_resume_calls() {
2036 let (mut sandbox, recorder, _) = launched().await;
2037 recorder.answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
2038 let report = sandbox.terminate(TeardownOpts::default()).await;
2039 assert!(report.terminate_accepted);
2040 assert!(sandbox.was_terminated());
2041
2042 let error = sandbox
2043 .resume()
2044 .await
2045 .expect_err("a terminated VM never returns to RUNNING");
2046 assert_eq!(error.kind(), ErrorKind::InvalidArg);
2047 assert!(error.to_string().contains("STATE-11"), "{error}");
2048 assert_eq!(
2049 recorder.call_count("ResumeMicrovm"),
2050 0,
2051 "no resume may reach the wire once the VM was terminated"
2052 );
2053 assert_ne!(
2054 sandbox.lifecycle(),
2055 Lifecycle::Running,
2056 "the lifecycle must not return to RUNNING"
2057 );
2058 }
2059
2060 /// **STATE-9 and STATE-10.** A terminate accepted is TERMINATING with the VM recorded
2061 /// terminated; the platform reporting termination complete is what marks TERMINATED.
2062 ///
2063 /// The two are separate states rather than one because the default teardown does not
2064 /// wait — so TERMINATING is a state a report really ends in, and calling it TERMINATED
2065 /// would claim an observation nobody made.
2066 #[tokio::test]
2067 async fn a_terminate_records_terminating_and_the_completion_report_marks_terminated() {
2068 let (mut sandbox, recorder, _) = launched().await;
2069 recorder.answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
2070
2071 let report = sandbox.terminate(TeardownOpts::default()).await;
2072 assert!(report.terminate_accepted, "STATE-9: the call was accepted");
2073 assert!(sandbox.was_terminated(), "STATE-9: recorded terminated");
2074 assert_eq!(
2075 report.lifecycle,
2076 Some(Lifecycle::Terminating),
2077 "the default teardown does not wait, so TERMINATED is not claimed"
2078 );
2079 assert!(!report.leaked(), "{report:?}");
2080
2081 // And with the wait asked for, STATE-10 is observed.
2082 let (mut sandbox, recorder, _) = launched().await;
2083 recorder
2084 .answer("TerminateMicrovm", Answer::ok(fake::empty_response()))
2085 .answer(
2086 "GetMicrovm",
2087 Answer::ok(fake::microvm_response("TERMINATED", None)),
2088 );
2089 let report = sandbox
2090 .terminate(TeardownOpts::default().waiting_for_terminated())
2091 .await;
2092 assert_eq!(report.lifecycle, Some(Lifecycle::Terminated));
2093 assert_eq!(sandbox.lifecycle(), Lifecycle::Terminated);
2094 }
2095
2096 /// The teardown order is VM, then image, then the log group **last** — asserted on the
2097 /// recorder's ledger rather than on the report, because the order is a property of what
2098 /// was emitted.
2099 ///
2100 /// The log group is last because the service can recreate a group deleted before its
2101 /// image. This crate cannot delete it at all, so the assertion is that it is *named
2102 /// after* the image work rather than that a delete call went out — see
2103 /// `TeardownReport::undeleted`.
2104 #[tokio::test]
2105 async fn teardown_deletes_the_vm_then_the_image_and_names_the_log_group_last() {
2106 let (mut sandbox, recorder, _) = planted();
2107 recorder
2108 .answer(
2109 "CreateMicrovmImage",
2110 Answer::created(fake::create_image_response("agentd-conformance")),
2111 )
2112 .answer(
2113 "GetMicrovmImage",
2114 Answer::ok(fake::get_image_response("agentd-conformance", "CREATED")),
2115 );
2116 sandbox
2117 .build_image(CreateImageRequest::new(
2118 "agentd-conformance",
2119 b"binary".to_vec(),
2120 "s3://bucket/img.zip",
2121 "arn:aws:iam::123456789012:role/build",
2122 ))
2123 .await
2124 .expect("builds");
2125 answer_launch(&recorder);
2126 sandbox
2127 .run(RunRequest::new())
2128 .await
2129 .expect("launches from the built image");
2130
2131 recorder
2132 .answer("TerminateMicrovm", Answer::ok(fake::empty_response()))
2133 .answer(
2134 "ListMicrovmImageVersions",
2135 Answer::ok(fake::list_versions_response("1")),
2136 )
2137 .answer(
2138 "DeleteMicrovmImage",
2139 Answer::ok(fake::delete_image_response()),
2140 );
2141
2142 let report = sandbox
2143 .terminate(
2144 TeardownOpts::default()
2145 .deleting_image()
2146 .deleting_log_group(),
2147 )
2148 .await;
2149 assert!(report.terminate_accepted);
2150 assert_eq!(report.image_deleted, Some(true));
2151
2152 // The ledger, filtered to the three destructive operations.
2153 let order: Vec<&str> = recorder
2154 .operations()
2155 .into_iter()
2156 .filter(|operation| matches!(*operation, "TerminateMicrovm" | "DeleteMicrovmImage"))
2157 .collect();
2158 assert_eq!(
2159 order,
2160 ["TerminateMicrovm", "DeleteMicrovmImage"],
2161 "the VM goes before the image: a terminating VM holds a reference to it"
2162 );
2163
2164 // The log group is named, and named last.
2165 assert_eq!(
2166 report.undeleted,
2167 ["/aws/lambda-microvms/agentd-conformance"],
2168 "{report:?}"
2169 );
2170 assert!(report.leaked());
2171 assert!(
2172 report
2173 .failures
2174 .last()
2175 .expect("a failure")
2176 .contains("log group"),
2177 "the log group's failure has to be the last one recorded: {report:?}"
2178 );
2179 assert!(
2180 report
2181 .failures
2182 .last()
2183 .expect("a failure")
2184 .contains("terraform destroy"),
2185 "the reason it leaks has to be named: {report:?}"
2186 );
2187 }
2188
2189 /// An image delete that fails every attempt lands its identifier in the report rather
2190 /// than raising, so the CLI can emit what was left behind (CLI-6).
2191 ///
2192 /// The identifier rather than a flag is the whole point: a leak nobody can name is a leak
2193 /// nobody can clean up.
2194 #[tokio::test]
2195 async fn a_failing_image_delete_names_what_it_left_behind() {
2196 let (mut sandbox, recorder, _) = planted();
2197 recorder
2198 .answer(
2199 "CreateMicrovmImage",
2200 Answer::created(fake::create_image_response("img")),
2201 )
2202 .answer(
2203 "GetMicrovmImage",
2204 Answer::ok(fake::get_image_response("img", "CREATED")),
2205 );
2206 sandbox
2207 .build_image(CreateImageRequest::new(
2208 "img",
2209 b"binary".to_vec(),
2210 "s3://bucket/img.zip",
2211 "arn:aws:iam::123456789012:role/build",
2212 ))
2213 .await
2214 .expect("builds");
2215 answer_launch(&recorder);
2216 sandbox.run(RunRequest::new()).await.expect("launches");
2217
2218 recorder
2219 .answer("TerminateMicrovm", Answer::ok(fake::empty_response()))
2220 .answer(
2221 "ListMicrovmImageVersions",
2222 Answer::ok(fake::list_versions_response("1")),
2223 )
2224 .answer(
2225 "DeleteMicrovmImage",
2226 Answer::failure(409, "image is in CREATING"),
2227 );
2228
2229 let mut opts = TeardownOpts::default().deleting_image();
2230 opts.delete_attempts = 3;
2231 opts.delete_backoff = Duration::from_secs(1);
2232 let report = sandbox.terminate(opts).await;
2233
2234 assert_eq!(report.image_deleted, Some(false));
2235 assert_eq!(
2236 report.undeleted,
2237 ["arn:aws:lambda:us-east-1:123456789012:microvm-image:img"],
2238 "{report:?}"
2239 );
2240 assert!(
2241 sandbox.image_exists(),
2242 "the image really is still there, so the flag must say so"
2243 );
2244 assert_eq!(
2245 recorder.call_count("DeleteMicrovmImage"),
2246 3,
2247 "every attempt ran"
2248 );
2249 }
2250
2251 /// A terminate whose own call fails still records the VM as one this client asked to
2252 /// destroy, and names it as undeleted.
2253 ///
2254 /// Recording it is what stops a later resume from being offered against a VM the caller
2255 /// already tried to kill (STATE-11) — the alternative leaves the sandbox looking
2256 /// resumable, which is the worse of the two wrong answers.
2257 #[tokio::test]
2258 async fn a_terminate_whose_call_fails_still_records_the_intent_and_the_leak() {
2259 let (mut sandbox, recorder, _) = launched().await;
2260 recorder.answer(
2261 "TerminateMicrovm",
2262 Answer::failure(500, "InternalServerException"),
2263 );
2264
2265 let report = sandbox.terminate(TeardownOpts::default()).await;
2266 assert!(!report.terminate_accepted);
2267 assert_eq!(report.undeleted, ["mvm-abc123"], "{report:?}");
2268 assert!(sandbox.was_terminated());
2269 assert_eq!(report.lifecycle, Some(Lifecycle::Terminating));
2270 assert!(
2271 !report.failures.is_empty(),
2272 "the swallowed failure is recorded"
2273 );
2274 }
2275
2276 /// A teardown on a sandbox that never launched is a no-op report rather than a panic.
2277 ///
2278 /// The path a caller reaches by tearing down in a `finally` after a launch that failed
2279 /// before any VM existed, which is exactly when a teardown that assumed a VM would turn
2280 /// the real failure into a panic.
2281 #[tokio::test]
2282 async fn a_teardown_before_any_launch_is_an_empty_report() {
2283 let (mut sandbox, recorder, _) = planted();
2284 let report = sandbox.terminate(TeardownOpts::default()).await;
2285 assert!(!report.terminate_accepted);
2286 assert!(!report.leaked());
2287 assert_eq!(report.lifecycle, Some(Lifecycle::Pending));
2288 assert_eq!(recorder.calls().len(), 0);
2289 }
2290
2291 /// A run with no image at all is a precondition error before any call, rather than a
2292 /// launch of an empty identifier.
2293 #[tokio::test]
2294 async fn a_run_with_no_image_is_refused_before_any_call() {
2295 let (mut sandbox, recorder, _) = planted();
2296 let error = sandbox
2297 .run(RunRequest::new())
2298 .await
2299 .expect_err("there is nothing to launch");
2300 assert_eq!(error.kind(), ErrorKind::Precondition);
2301 assert!(error.to_string().contains("build_image first"), "{error}");
2302 assert_eq!(recorder.calls().len(), 0);
2303 }
2304
2305 /// The lifecycle's six states are the symspec's `vm_state` domain, spelled as the service
2306 /// spells them.
2307 ///
2308 /// Asserted rather than assumed because the spelling reaches an error message a reader
2309 /// compares against a `GetMicrovm` response: a lifecycle rendering `Suspended` beside a
2310 /// service saying `SUSPENDED` reads like two different facts.
2311 #[test]
2312 fn the_lifecycle_states_are_the_state_models_domain_in_the_services_spelling() {
2313 let all = [
2314 Lifecycle::Pending,
2315 Lifecycle::Running,
2316 Lifecycle::Suspending,
2317 Lifecycle::Suspended,
2318 Lifecycle::Terminating,
2319 Lifecycle::Terminated,
2320 ];
2321 assert_eq!(
2322 all.map(Lifecycle::as_str),
2323 [
2324 "PENDING",
2325 "RUNNING",
2326 "SUSPENDING",
2327 "SUSPENDED",
2328 "TERMINATING",
2329 "TERMINATED"
2330 ]
2331 );
2332 for state in all {
2333 assert_eq!(state.to_string(), state.as_str());
2334 }
2335 // The four live states are the ones a `Drop` warns about, and TERMINATING is not one
2336 // of them: the platform accepted the terminate, so nobody needs telling.
2337 assert_eq!(
2338 all.iter().filter(|state| state.is_live()).count(),
2339 4,
2340 "a state added to the enum defaults to not-live, which would silence the warning"
2341 );
2342 assert!(!Lifecycle::Terminating.is_live());
2343 assert!(!Lifecycle::Terminated.is_live());
2344 }
2345
2346 /// An agent token is 64 hex characters and never repeats.
2347 ///
2348 /// The distinctness matters because the token is the only thing separating one VM's
2349 /// control API from another's: two VMs sharing a token means either one's caller can
2350 /// drive the other's guest.
2351 #[test]
2352 fn a_minted_agent_token_is_sixty_four_hex_characters_and_never_repeats() {
2353 let minted: std::collections::HashSet<String> =
2354 (0..200).map(|_| mint_agent_token()).collect();
2355 assert_eq!(minted.len(), 200, "a repeated token is a shared guest");
2356 for token in &minted {
2357 assert_eq!(token.len(), 64, "{token}");
2358 assert!(token.chars().all(|c| c.is_ascii_hexdigit()), "{token}");
2359 assert_ne!(
2360 token,
2361 &"0".repeat(64),
2362 "an all-zero draw is a read that did nothing"
2363 );
2364 }
2365 }
2366
2367 /// A sandbox's `Debug` does not print the agent token.
2368 #[tokio::test]
2369 async fn a_sandbox_debug_does_not_print_the_agent_token() {
2370 let (mut sandbox, recorder, _) = planted();
2371 answer_launch(&recorder);
2372 sandbox
2373 .run(
2374 RunRequest::new()
2375 .with_image("arn:image")
2376 .with_agent_token("super-secret-agent-token"),
2377 )
2378 .await
2379 .expect("launches");
2380
2381 let rendered = format!("{sandbox:?}");
2382 assert!(rendered.contains("mvm-abc123"), "{rendered}");
2383 assert!(rendered.contains("Running"), "{rendered}");
2384 assert!(
2385 !rendered.contains("super-secret"),
2386 "the agent token reached a Debug string: {rendered}"
2387 );
2388 }
2389
2390 /// A torn-down sandbox does not warn on drop, and an abandoned one is the case the
2391 /// warning exists for.
2392 ///
2393 /// Asserted on the flag rather than on stderr — capturing another thread's stderr from a
2394 /// test is not something this crate can do without a dependency — so what is pinned is
2395 /// the condition the warning branches on. Both halves, so the branch cannot be
2396 /// vacuously true.
2397 #[tokio::test]
2398 async fn a_torn_down_sandbox_is_distinguishable_from_an_abandoned_one() {
2399 let (mut sandbox, recorder, _) = launched().await;
2400 assert!(
2401 sandbox.lifecycle().is_live() && !sandbox.torn_down,
2402 "an abandoned live VM is what the drop warning is for"
2403 );
2404
2405 recorder.answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
2406 sandbox.terminate(TeardownOpts::default()).await;
2407 assert!(
2408 sandbox.torn_down,
2409 "terminate must mark the sandbox torn down"
2410 );
2411 assert!(
2412 !sandbox.lifecycle().is_live(),
2413 "and the lifecycle must no longer read as live"
2414 );
2415 }
2416}