Skip to main content

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