Skip to main content

microvms_app/
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, a resume of a VM that ended
7//! before it (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. Those fields are private and transitions are guarded here.
17//! Adoption initializes an existing VM from service-observed state and is covered by
18//! the adoption tests; it does not replay the launch bootstrap.
19//!
20//! # Runtime-checked rather than typestate, deliberately
21//!
22//! The packet offered `Sandbox<Running>` returning a `Suspended` handle, which would make
23//! STATE-5's wrong call a compile error rather than a local refusal — strictly stronger on
24//! the ladder in [`crate`]. It is not what landed, for the reason the packet names as
25//! acceptable: T-W3-8 wraps **one** object for PyO3 and napi-rs, and a type whose Rust
26//! identity changes on every transition cannot be one `#[pyclass]`. A typestate sandbox
27//! would be re-erased into a runtime-checked enum at the binding boundary, so the check
28//! would exist twice with the binding's copy being the one most callers actually hit.
29//!
30//! What is kept from the typestate idea is the part that costs nothing: the check happens
31//! **before** the wire call, so a suspend from SUSPENDED is refused with zero
32//! control-plane calls rather than answered by AWS. The test asserts the call count, which
33//! is the observable that distinguishes the two.
34//!
35//! # The service decides whether a suspended VM resumes (STATE-12)
36//!
37//! The launch-time `idlePolicy` *terminates* a VM the idle policy suspended once
38//! `suspendedDurationSeconds` passes, and the service doesn't hold an explicit
39//! `SuspendMicrovm` to that window: measured 2026-10-12 in us-east-1, a VM this client
40//! suspended resumed 1283 s into a 60 s window (#597). So a resume is never refused here for
41//! the time it has spent suspended. It goes to the service, and the service's refusal for a
42//! VM that ended, whatever ended it, comes back from [`ControlPlane::resume`] as
43//! [`ErrorKind::WindowClosed`], which this sandbox records as a termination (STATE-11).
44//!
45//! A sandbox held as RUNNING reads `GetMicrovm` before deciding whether it can resume.
46//! This observes a suspend or termination made by the platform idle policy. A service
47//! state of SUSPENDED follows the normal resume path; an ended VM is `WindowClosed`.
48//!
49//! # Teardown never raises, and the log group is last
50//!
51//! [`Sandbox::terminate`] returns a [`TeardownReport`] rather than a `Result`. It runs
52//! where a caller's `finally` would, and an error raised there replaces the real failure
53//! with a teardown failure — the real one being the one worth reading.
54//!
55//! The order is VM, then image (retrying), then the log group **last**, because the
56//! service can recreate a group deleted before its image. See
57//! [`TeardownReport::undeleted`] for what this crate can and cannot delete.
58//!
59//! # There is no `Drop` that tears down
60//!
61//! Rust has no context manager and `Drop` cannot await. A `Drop` that blocked on a runtime
62//! would deadlock inside one; a `Drop` that spawned would race the process exit. So
63//! [`Sandbox`]'s `Drop` only **warns** about a live VM, naming the id, and the rule is
64//! that a caller calls [`Sandbox::terminate`] explicitly.
65
66use std::sync::Arc;
67use std::time::Duration;
68
69use crate::control::{
70    ControlPlane, CreateImageRequest, Image, Microvm, RunHookPayload, RunMicrovmRequest, WaitOpts,
71};
72use crate::error::{Error, ErrorKind};
73use crate::region::Region;
74use crate::session::{Session, TokenMinter};
75
76/// The default wait for a launch to reach RUNNING: five minutes, matching the Python client's
77/// `ready_timeout_sec`. The daemon wait after it is
78/// [`crate::session::DEFAULT_BOOTSTRAP_TIMEOUT`].
79pub const DEFAULT_RUNNING_TIMEOUT: Duration = Duration::from_secs(300);
80
81/// The old name of [`DEFAULT_RUNNING_TIMEOUT`], kept for one release.
82#[deprecated(
83    note = "renamed DEFAULT_RUNNING_TIMEOUT: `session::DEFAULT_READY_TIMEOUT` shared this name \
84            for a different wait, the daemon's"
85)]
86pub const DEFAULT_READY_TIMEOUT: Duration = DEFAULT_RUNNING_TIMEOUT;
87
88/// The default lifecycle wait for suspend, resume, and terminate, and for a state wait the
89/// caller gives no deadline (the bindings' `wait_for_state`, the CLI's `terminate --wait`).
90pub const DEFAULT_LIFECYCLE_TIMEOUT: Duration = Duration::from_secs(300);
91
92/// How many times a teardown retries the image delete.
93///
94/// Twenty, from the Python client: an image in `CREATING` refuses deletion and a VM still
95/// terminating holds a reference, so this is the difference between a clean account and a
96/// billed leak rather than politeness.
97pub const DEFAULT_DELETE_ATTEMPTS: u32 = 20;
98
99/// The gap between image-delete attempts.
100pub const DEFAULT_DELETE_BACKOFF: Duration = Duration::from_secs(15);
101
102/// Where the advisory deny points a well-behaved client: a loopback port nothing serves.
103///
104/// Loopback rather than an unroutable public address, because a refused connection is
105/// immediate and a black-holed one costs the workload a connect timeout per request. Port 1
106/// is privileged, so a demoted workload cannot answer it by accident.
107pub const DENY_EGRESS_PROXY_URL: &str = "http://127.0.0.1:1";
108
109/// The environment variables the advisory deny sets, in both spellings clients read.
110///
111/// Both cases on purpose: `curl` and most Unix clients read the lowercase names, Python's
112/// `requests`/`urllib3`, npm and the AWS SDKs read the uppercase ones, and a client that
113/// reads only the spelling this list omits is a hole in a mechanism that is advisory to
114/// begin with. `no_proxy` is deliberately absent: the launch environment starts empty
115/// (`agentd` clears it and applies only what the hook delivered), so there is no inherited
116/// exemption to overwrite, and each key spends payload budget.
117pub const DENY_EGRESS_ENV_KEYS: [&str; 6] = [
118    "http_proxy",
119    "https_proxy",
120    "all_proxy",
121    "HTTP_PROXY",
122    "HTTPS_PROXY",
123    "ALL_PROXY",
124];
125
126/// Default lifecycle polling interval. Public so an adapter that builds its own [`WaitOpts`]
127/// reuses the interval. Sandbox launches poll faster during their initial retries.
128pub const LIFECYCLE_POLL_INTERVAL: Duration = Duration::from_secs(5);
129
130/// The symspec's `vm_state`, verbatim.
131///
132/// Six states and no others, which is the S1 half of this module: a lifecycle held as a
133/// `String` would let `"RUNNING "` and `"Running"` both exist, and every guard below would
134/// have to decide which it meant.
135#[derive(Clone, Copy, Debug, Eq, PartialEq)]
136pub enum Lifecycle {
137    /// The initial state, and the state a launch is accepted into (STATE-1).
138    Pending,
139    /// The service reports RUNNING; launch has completed bootstrap, or adoption supplied
140    /// the existing token (STATE-2).
141    Running,
142    /// A suspend was accepted and the platform has not yet reported it complete (STATE-4).
143    Suspending,
144    /// The platform reported suspension complete (STATE-6).
145    Suspended,
146    /// A terminate was accepted (STATE-9).
147    Terminating,
148    /// The platform reported termination complete (STATE-10).
149    Terminated,
150}
151
152impl Lifecycle {
153    /// The name the service uses for this state, which is also what an error message says.
154    pub fn as_str(self) -> &'static str {
155        match self {
156            Lifecycle::Pending => "PENDING",
157            Lifecycle::Running => "RUNNING",
158            Lifecycle::Suspending => "SUSPENDING",
159            Lifecycle::Suspended => "SUSPENDED",
160            Lifecycle::Terminating => "TERMINATING",
161            Lifecycle::Terminated => "TERMINATED",
162        }
163    }
164
165    /// The lifecycle the service's `state` names, or `None` for a spelling this client does
166    /// not know. `constants::MICROVM_STATES` is the closed set, and a test ties the two.
167    pub fn from_service(state: &str) -> Option<Self> {
168        Some(match state {
169            "PENDING" => Lifecycle::Pending,
170            "RUNNING" => Lifecycle::Running,
171            "SUSPENDING" => Lifecycle::Suspending,
172            "SUSPENDED" => Lifecycle::Suspended,
173            "TERMINATING" => Lifecycle::Terminating,
174            "TERMINATED" => Lifecycle::Terminated,
175            _ => return None,
176        })
177    }
178
179    /// Whether a VM in this state is still billing, which is what a `Drop` warning is for.
180    pub fn is_live(self) -> bool {
181        matches!(
182            self,
183            Lifecycle::Pending | Lifecycle::Running | Lifecycle::Suspending | Lifecycle::Suspended
184        )
185    }
186}
187
188impl std::fmt::Display for Lifecycle {
189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190        f.write_str(self.as_str())
191    }
192}
193
194/// Everything a launch needs, with the defaults the Python client measured.
195///
196/// `agent_token` is optional because the common case is a per-VM secret nobody needs to
197/// see; a caller who has one already — a harness minting its own, or a retry that must
198/// reuse the first attempt's — passes it.
199#[derive(Clone, Debug)]
200pub struct RunRequest {
201    /// The image to launch, or `None` for the one [`Sandbox::build_image`] built.
202    ///
203    /// An image ARN, or a bare image name, which [`Sandbox::run`] resolves to its ARN with one
204    /// `ListMicrovmImages` read. A name no image carries is refused with `ERR_PRECONDITION`
205    /// before anything launches.
206    pub image_identifier: Option<String>,
207    /// `imageVersion`, or `None` for the image's own latest active version.
208    ///
209    /// Pinning is what makes a canary a canary: without it a launch takes whatever version is
210    /// latest at the moment the call lands, which is not necessarily the one the caller just
211    /// built. Paired with [`crate::control::ControlPlane::set_image_version_status`] it is also
212    /// the rollback — set the bad version INACTIVE, re-pin here to the good one — and a version
213    /// set INACTIVE refuses to launch when named here.
214    ///
215    /// See [`crate::control::RunMicrovmRequest::image_version`], which this forwards to.
216    pub image_version: Option<String>,
217    /// The execution role. Optional in the model; every real launch needs one.
218    pub execution_role_arn: Option<String>,
219    /// The bearer token the daemon will accept, or `None` to mint one.
220    pub agent_token: Option<String>,
221    /// Persist this unique launch key before sending a request; reuse only for that same
222    /// launch and identical parameters. None mints a fresh key. A stable key requires
223    /// an explicit agent_token and identity=false so retries carry identical payloads.
224    pub client_token: Option<String>,
225    /// Base environment for every exec in the launched VM, delivered in the same
226    /// `runHookPayload` as the token.
227    ///
228    /// The daemon applies this *under* each request's own `env`, so a per-exec value
229    /// wins on a key both set. Empty by default, and an empty map produces byte-for-byte
230    /// the payload this client always sent — a caller who never touches this field
231    /// cannot be affected by the field existing.
232    ///
233    /// It shares the token's 4096-byte payload budget, and the check is local:
234    /// [`crate::control::RunHookPayload::for_launch`] refuses an over-ceiling payload
235    /// before any call, naming the byte count and how much of it the env is. That
236    /// matters here more than for the token, because one bearer token has always fit
237    /// with room to spare and a map of credentials does not.
238    pub launch_env: std::collections::HashMap<String, String>,
239    /// Whether to generate and deliver a tunnel identity (#70 layer 3).
240    ///
241    /// On, the launch generates two fresh x25519 seeds, delivers the VM's seed and the
242    /// host's public key in the same payload as the token, and [`RunOutcome`]-equivalent
243    /// state on the session keeps the [`crate::identity::TunnelIdentity`] — the host secret
244    /// and the VM's public pin — for `tunnel --verify-identity` to prove the far end.
245    /// Off (the default) sends byte-for-byte the payload this client always sent.
246    ///
247    /// A flag rather than always-on, deliberately: the material spends 137 bytes of the
248    /// payload's measured 4096-byte budget, and a caller near the ceiling with a launch env
249    /// deserves to choose which feature gets the room.
250    pub identity: bool,
251    /// Whether to request the egress connector. Off omits it from the request; measured
252    /// 2026-09-12 the platform gave a connector-less VM outbound network anyway
253    /// (`docs/PLATFORM.md`).
254    pub egress: bool,
255    /// Customer-managed Lambda VPC egress connector ARNs. See
256    /// [`RunMicrovmRequest::egress_network_connectors`].
257    pub egress_network_connectors: Vec<String>,
258    /// Sets advisory proxy-deny environment variables for clients that honor them.
259    /// Workloads can bypass these variables. Internet isolation requires a VPC egress
260    /// connector using a VPC without an internet gateway or NAT gateway.
261    ///
262    /// Refused with [`RunRequest::egress`]. Existing caller-supplied proxy variables win;
263    /// the added variables share the 4096-byte run-hook payload budget.
264    pub deny_egress: bool,
265    /// Whether to launch shell-capable: the ingress set becomes the measured pair
266    /// `[HTTP_INGRESS, SHELL_INGRESS]` instead of `ALL_INGRESS`, which is what
267    /// `CreateMicrovmShellAuthToken` requires and what `microvm shell` attaches to.
268    /// Off (the default) launches byte-for-byte what this client always sent.
269    pub shell: bool,
270    /// `idlePolicy.maxIdleDurationSeconds`.
271    pub max_idle_sec: u32,
272    /// `idlePolicy.suspendedDurationSeconds`: how long a VM the idle policy suspended lasts
273    /// before the service terminates it. An explicit suspend isn't held to it (STATE-12).
274    pub suspended_sec: u32,
275    /// `idlePolicy.autoResumeEnabled`.
276    pub auto_resume: bool,
277    /// `maximumDurationInSeconds`, checked against 1..=28800 before the call.
278    pub max_duration_sec: u32,
279    /// How long to wait for RUNNING. The wait for the daemon to answer, after it, is
280    /// [`crate::session::DEFAULT_BOOTSTRAP_TIMEOUT`].
281    pub ready_timeout: Duration,
282    /// A label for the run token (TRAP-1). Never the token.
283    pub token_scope: Option<String>,
284    /// Per-VM `logging` (#201). See [`RunMicrovmRequest::logging`].
285    pub logging: Option<crate::control::ops::Logging>,
286    /// Whether [`Sandbox::run`] waits for RUNNING and for the daemon to answer before
287    /// returning (the default).
288    ///
289    /// Off returns as soon as `RunMicrovm` is accepted, with the lifecycle still PENDING:
290    /// the session is addressable, and [`Sandbox::wait_until_running`] finishes both waits
291    /// later, from this process or after a durable workflow's next step.
292    pub wait: bool,
293}
294
295impl Default for RunRequest {
296    fn default() -> Self {
297        Self {
298            image_identifier: None,
299            image_version: None,
300            execution_role_arn: None,
301            agent_token: None,
302            client_token: None,
303            launch_env: std::collections::HashMap::new(),
304            identity: false,
305            egress: false,
306            egress_network_connectors: Vec::new(),
307            deny_egress: false,
308            shell: false,
309            max_idle_sec: 600,
310            suspended_sec: 600,
311            auto_resume: false,
312            max_duration_sec: 3_600,
313            ready_timeout: DEFAULT_RUNNING_TIMEOUT,
314            token_scope: None,
315            logging: None,
316            wait: true,
317        }
318    }
319}
320
321impl RunRequest {
322    /// A launch with the measured defaults: ingress only, ten-minute idle and suspended
323    /// windows, a one-hour maximum duration, no auto-resume.
324    pub fn new() -> Self {
325        Self::default()
326    }
327
328    /// Launches `identifier`, an image ARN or a bare image name, rather than the built image.
329    #[must_use]
330    pub fn with_image(mut self, identifier: impl Into<String>) -> Self {
331        self.image_identifier = Some(identifier.into());
332        self
333    }
334
335    /// Requests the managed internet egress connector. Omission does not block internet access.
336    #[must_use]
337    pub fn with_egress(mut self) -> Self {
338        self.egress = true;
339        self
340    }
341
342    /// Routes egress through a customer-managed Lambda network connector.
343    #[must_use]
344    pub fn with_egress_network_connector(mut self, arn: impl Into<String>) -> Self {
345        self.egress_network_connectors.push(arn.into());
346        self
347    }
348
349    /// Replaces managed internet egress with customer-managed VPC connectors, when any are
350    /// given; an empty list leaves the request unchanged.
351    ///
352    /// The two cannot be combined, so a launch surface that requests managed egress by
353    /// default (an agent VM) uses this to switch rather than failing the launch.
354    #[must_use]
355    pub fn with_vpc_egress(mut self, arns: Vec<String>) -> Self {
356        if !arns.is_empty() {
357            self.egress = false;
358            self.egress_network_connectors = arns;
359        }
360        self
361    }
362
363    /// Applies the advisory in-guest deny. See [`RunRequest::deny_egress`] for what it is
364    /// and, more importantly, for what it is not.
365    #[must_use]
366    pub fn with_deny_egress(mut self) -> Self {
367        self.deny_egress = true;
368        self
369    }
370
371    /// What this launch's outbound network **is**, as opposed to what it asked for.
372    ///
373    /// The one derivation, so the CLI's envelope, the CLI's human line and any embedding
374    /// consumer cannot disagree about the same launch.
375    pub fn egress_posture(&self) -> crate::control::EgressPosture {
376        crate::control::EgressPosture::for_launch(self.egress, self.deny_egress)
377    }
378
379    /// The launch environment as the guest will see it: the caller's, plus the advisory
380    /// proxy deny when [`RunRequest::deny_egress`] is on.
381    ///
382    /// The caller's own value wins on a shared key. A launch that already routes through a
383    /// proxy of its own has said where its traffic goes, and overwriting that with a black
384    /// hole would break a working configuration in the name of a posture this client
385    /// already declines to call a seal.
386    pub fn effective_launch_env(&self) -> std::collections::HashMap<String, String> {
387        let mut env = self.launch_env.clone();
388        if self.deny_egress {
389            for key in DENY_EGRESS_ENV_KEYS {
390                env.entry(key.to_string())
391                    .or_insert_with(|| DENY_EGRESS_PROXY_URL.to_string());
392            }
393        }
394        env
395    }
396
397    /// Requests a shell-capable launch. See [`RunRequest::shell`].
398    #[must_use]
399    pub fn with_shell(mut self) -> Self {
400        self.shell = true;
401        self
402    }
403
404    /// Pins the launch to one `imageVersion`. See the field for why.
405    #[must_use]
406    pub fn with_image_version(mut self, version: impl Into<String>) -> Self {
407        self.image_version = Some(version.into());
408        self
409    }
410
411    /// Sets `idlePolicy.suspendedDurationSeconds`, how long a VM the idle policy suspended
412    /// lasts before the service terminates it. See [`RunRequest::suspended_sec`].
413    #[must_use]
414    pub fn with_suspended_sec(mut self, seconds: u32) -> Self {
415        self.suspended_sec = seconds;
416        self
417    }
418
419    /// Reuses a caller-supplied agent token rather than minting one.
420    #[must_use]
421    pub fn with_agent_token(mut self, token: impl Into<String>) -> Self {
422        self.agent_token = Some(token.into());
423        self
424    }
425
426    /// Generates and delivers a tunnel identity with the launch (#70 layer 3).
427    ///
428    /// After a `run` with this set, [`Sandbox::tunnel_identity`] holds what
429    /// `tunnel --verify-identity` needs: the host's secret and the VM's public pin.
430    #[must_use]
431    pub fn with_identity(mut self) -> Self {
432        self.identity = true;
433        self
434    }
435
436    /// Adds one launch-environment variable, which every exec in the VM starts with.
437    ///
438    /// One pair per call rather than a whole map, because that is how a caller builds
439    /// one — from flags, from a config file, one credential at a time — and a
440    /// map-taking setter makes the second call silently discard the first. The field is
441    /// public for a caller who really does hold a map.
442    #[must_use]
443    pub fn with_launch_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
444        self.launch_env.insert(key.into(), value.into());
445        self
446    }
447}
448
449/// What a teardown should delete beyond the VM itself.
450///
451/// Both deletions are opt-in, because both destroy something a caller may still want: the
452/// image is reusable across runs, and the log group is where a failed build's only evidence
453/// lives.
454#[derive(Clone, Copy, Debug)]
455pub struct TeardownOpts {
456    /// Whether to delete the image the sandbox built.
457    pub delete_image: bool,
458    /// Whether the build log group should be deleted.
459    ///
460    /// This crate **cannot** delete it — CloudWatch is not in the dependency set — so
461    /// asking names the group in [`TeardownReport::undeleted`] rather than removing it.
462    /// See that field for why naming is the honest answer rather than a silent success.
463    pub delete_log_group: bool,
464    /// How many times the image delete is retried.
465    pub delete_attempts: u32,
466    /// The gap between image-delete attempts.
467    pub delete_backoff: Duration,
468    /// How long to wait for TERMINATED, or `None` to return as soon as the terminate call
469    /// is accepted.
470    ///
471    /// `None` by default, matching the Python client: the caller is on the way out, and a
472    /// teardown that blocked five minutes on a state nobody reads is five minutes of a CI
473    /// job. A caller that needs STATE-10 *observed* passes
474    /// [`TeardownOpts::waiting_for_terminated`].
475    pub wait_for_terminated: Option<Duration>,
476}
477
478impl Default for TeardownOpts {
479    fn default() -> Self {
480        Self {
481            delete_image: false,
482            delete_log_group: false,
483            delete_attempts: DEFAULT_DELETE_ATTEMPTS,
484            delete_backoff: DEFAULT_DELETE_BACKOFF,
485            wait_for_terminated: None,
486        }
487    }
488}
489
490impl TeardownOpts {
491    /// Deletes the image as well as the VM.
492    #[must_use]
493    pub fn deleting_image(mut self) -> Self {
494        self.delete_image = true;
495        self
496    }
497
498    /// Asks for the log group too, which names it rather than deleting it.
499    #[must_use]
500    pub fn deleting_log_group(mut self) -> Self {
501        self.delete_log_group = true;
502        self
503    }
504
505    /// Waits for TERMINATED before returning (STATE-10).
506    #[must_use]
507    pub fn waiting_for_terminated(mut self) -> Self {
508        self.wait_for_terminated = Some(DEFAULT_LIFECYCLE_TIMEOUT);
509        self
510    }
511}
512
513/// What a teardown did, and what it left behind.
514///
515/// Returned rather than raised. See the module docs: this runs where a `finally` would.
516#[derive(Clone, Debug, Default, Eq, PartialEq)]
517pub struct TeardownReport {
518    /// Identifiers of everything a caller asked to have deleted that still exists.
519    ///
520    /// The CLI emits these (CLI-6), which is the whole reason they are identifiers rather
521    /// than a boolean: a leak nobody can name is a leak nobody can clean up.
522    ///
523    /// Two things land here. A delete that was attempted and failed — an image whose twenty
524    /// attempts all hit a conflict. And the build **log group**, which this crate cannot
525    /// delete at all: no CloudWatch client exists anywhere in this workspace, and a logs
526    /// API for one delete call is a bigger surface than the leak it would hide (an
527    /// `aws-sdk-cloudwatchlogs` edge is a reasonable future add if teardown grows more
528    /// log-group work). Naming it is strictly better than the
529    /// alternatives: deleting it is unavailable, and silently succeeding would report a
530    /// clean teardown over six accumulated log groups — which is how the leak was found in
531    /// the first place.
532    pub undeleted: Vec<String>,
533    /// Whether the terminate call was accepted.
534    pub terminate_accepted: bool,
535    /// Whether the image was deleted, or `None` when deletion was not asked for.
536    pub image_deleted: Option<bool>,
537    /// The lifecycle state the sandbox ended in.
538    pub lifecycle: Option<Lifecycle>,
539    /// Every failure the teardown swallowed, in the order it hit them.
540    ///
541    /// Kept because a teardown that never raises is a teardown whose failures are invisible
542    /// otherwise, and the first one is usually the cause of the rest.
543    pub failures: Vec<String>,
544}
545
546impl TeardownReport {
547    /// Whether anything a caller asked for was left behind.
548    pub fn leaked(&self) -> bool {
549        !self.undeleted.is_empty()
550    }
551}
552
553/// Mints proxy tokens for one MicroVM through the control plane.
554///
555/// The bridge between the two lanes: `ControlPlane::mint_auth_token` answers a
556/// `control::ProxyToken`, [`TokenMinter`] wants a `session::ProxyToken`, and the `From`
557/// impl at `session/proxy.rs` is the conversion — one `.into()` at the boundary, which is
558/// why that impl is `From` rather than a named function.
559///
560/// The plane sits behind an `Arc` rather than a reference because the minter must outlive
561/// the call that built the session: minting happens inside the request path on every later
562/// request, which is what makes it happen at all (TRAP-9).
563///
564/// Public so a driving adapter that builds its own session mints through this rather than a
565/// copy of it.
566pub struct ControlPlaneMinter {
567    control: Arc<ControlPlane>,
568    microvm_id: String,
569}
570
571impl ControlPlaneMinter {
572    /// A minter for `microvm_id`'s tokens, through `control`.
573    pub fn new(control: Arc<ControlPlane>, microvm_id: impl Into<String>) -> Self {
574        Self {
575            control,
576            microvm_id: microvm_id.into(),
577        }
578    }
579}
580
581impl std::fmt::Debug for ControlPlaneMinter {
582    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
583        f.debug_struct("ControlPlaneMinter")
584            .field("microvm_id", &self.microvm_id)
585            .finish_non_exhaustive()
586    }
587}
588
589impl TokenMinter for ControlPlaneMinter {
590    fn mint(
591        &self,
592    ) -> futures_util::future::BoxFuture<'_, Result<crate::session::ProxyToken, Error>> {
593        Box::pin(async move {
594            let minted = self.control.mint_auth_token(&self.microvm_id).await?;
595            Ok(minted.into())
596        })
597    }
598
599    /// Overrides the default, which ignores the ports and delegates.
600    ///
601    /// This is the minter that has a control plane behind it, so it is the one that can
602    /// actually widen a token's scope — and without this override
603    /// `Session::connect_headers(8080)` would keep answering a header pair behind a token
604    /// scoped to 9000 only, which the proxy refuses with 403 `Access to port denied`. See
605    /// [`TokenMinter::mint_for_ports`] for the measurement.
606    fn mint_for_ports(
607        &self,
608        ports: &[u16],
609    ) -> futures_util::future::BoxFuture<'_, Result<crate::session::ProxyToken, Error>> {
610        let specs: Vec<crate::control::ops::PortSpecification> = ports
611            .iter()
612            .map(|port| crate::control::ops::PortSpecification::port(*port))
613            .collect();
614        Box::pin(async move {
615            let minted = self
616                .control
617                .mint_auth_token_for(&self.microvm_id, &specs)
618                .await?;
619            Ok(minted.into())
620        })
621    }
622}
623
624/// One MicroVM's whole life.
625///
626/// See the module docs for the state machine, the resume of an ended VM, and why teardown is
627/// explicit.
628pub struct Sandbox {
629    control: Arc<ControlPlane>,
630    image: Option<Image>,
631    /// The image ARN [`Sandbox::run`] resolved and sent in `RunMicrovm`, set before the call.
632    launch_image_arn: Option<String>,
633    microvm: Option<Microvm>,
634    session: Option<Session>,
635    /// A backend for the session [`Sandbox::run`] builds, or `None` for the real HTTP one.
636    ///
637    /// The daemon-side sibling of `with_control_plane`'s transport seam: a test that
638    /// scripts the control plane can launch, but the session `run` then builds would dial
639    /// a real endpoint. This lets the same test script the daemon too. Never set in
640    /// production — `Session::builder` picks reqwest when no backend is given.
641    session_backend: Option<crate::session::SharedBackend>,
642
643    // ── the symspec's five variables ─────────────────────────────────────────
644    lifecycle: Lifecycle,
645    /// Every transition of `lifecycle`, for a reader that must not take the caller's lock
646    /// (a keepalive task running while the same sandbox is busy inside a long exec).
647    lifecycle_watch: tokio::sync::watch::Sender<Lifecycle>,
648    token_installed: bool,
649    image_exists: bool,
650    was_terminated: bool,
651    bootstrap_count: u32,
652
653    /// The suspended window from *our own* `RunMicrovm` request, or `None` for a sandbox that
654    /// launched nothing. `GetMicrovm` reports the service's in `idlePolicy`.
655    suspended_window: Option<Duration>,
656    /// Whether the accepted launch carried a caller client token, and so may have adopted
657    /// a VM an earlier attempt launched (#195).
658    launch_adoptable: bool,
659    /// The egress posture of this sandbox's own accepted launch, or `None` for a sandbox
660    /// that launched nothing (an adopted one never saw the launch options).
661    launch_posture: Option<crate::control::EgressPosture>,
662    /// The launch's agent token, held until the session that carries it is built. Kept out
663    /// of `Debug` like every other credential here.
664    pending_agent_token: Option<String>,
665    /// `maxIdleDurationSeconds` from our own `RunMicrovm` request: a keepalive's cadence
666    /// is checked against it.
667    idle_window: Option<Duration>,
668    /// Set by [`Sandbox::terminate`], so `Drop` can tell an abandoned VM from a torn-down
669    /// one.
670    torn_down: bool,
671    /// Built by [`Sandbox::adopt`] around a VM another process launched. That process owns
672    /// the VM's teardown, so dropping this handle is not a leak and `Drop` stays quiet.
673    adopted: bool,
674    /// Set by [`Sandbox::detach`]: the VM was handed to another process, which now owns its
675    /// lifecycle and teardown. Every transition is refused and `Drop` stays quiet.
676    detached: bool,
677    /// The launch's tunnel identity, when [`RunRequest::identity`] asked for one.
678    ///
679    /// Holds the host secret and the VM's *public* pin — the VM's own secret was dropped
680    /// the moment the payload was built ([`crate::identity::LaunchIdentity::keep`]), so
681    /// nothing on the host side can impersonate the VM it launched.
682    tunnel_identity: Option<crate::identity::TunnelIdentity>,
683    /// The STS and S3 calls [`Sandbox::ensure_image`] makes, or `None` until the first
684    /// call builds the real ones. The seam a test replaces them at.
685    build_services: Option<Arc<dyn crate::control::BuildServices>>,
686    /// The caller's account, resolved once per sandbox for image ARNs (IMAGE-8).
687    account: Option<String>,
688}
689
690impl std::fmt::Debug for Sandbox {
691    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
692        // No agent token: it is a credential, and a `Debug` that printed it would put it in
693        // every log line that formats a sandbox.
694        f.debug_struct("Sandbox")
695            .field("lifecycle", &self.lifecycle)
696            .field("microvm", &self.microvm.as_ref().map(|vm| &vm.id))
697            .field("image", &self.image.as_ref().map(|image| &image.identifier))
698            .field("token_installed", &self.token_installed)
699            .field("bootstrap_count", &self.bootstrap_count)
700            .field("was_terminated", &self.was_terminated)
701            .field("suspended_window", &self.suspended_window)
702            .field("adopted", &self.adopted)
703            .field("detached", &self.detached)
704            .finish_non_exhaustive()
705    }
706}
707
708/// What another process needs to adopt a VM this sandbox handed off with
709/// [`Sandbox::detach`]: pass the fields to [`Sandbox::adopt`] (or the prelude's `Sandbox::adopt_in`).
710///
711/// The agent token is a credential: readable through [`Detached::agent_token`] so it can be
712/// persisted, and absent from `Debug`, so a log line that formats the record cannot leak it.
713/// Store it the way [`crate::names::NameRecord`] asks: privately, encrypted.
714#[derive(Clone)]
715pub struct Detached {
716    /// The VM's identifier.
717    pub microvm_id: String,
718    /// The HTTPS endpoint its daemon answers on.
719    pub endpoint: String,
720    /// The region the VM runs in.
721    pub region: Region,
722    /// The daemon port the endpoint's proxy tokens are minted for.
723    pub port: u16,
724    agent_token: String,
725}
726
727impl Detached {
728    /// The bearer the VM's daemon accepts; required by [`Sandbox::adopt`].
729    pub fn agent_token(&self) -> &str {
730        &self.agent_token
731    }
732}
733
734impl std::fmt::Debug for Detached {
735    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
736        f.debug_struct("Detached")
737            .field("microvm_id", &self.microvm_id)
738            .field("endpoint", &self.endpoint)
739            .field("region", &self.region)
740            .field("port", &self.port)
741            .field("agent_token", &"<redacted>")
742            .finish()
743    }
744}
745
746impl Sandbox {
747    /// A sandbox over an already-built [`ControlPlane`].
748    ///
749    /// The seam every test uses, and public for the same reason `ControlPlane::from_ports`
750    /// is: a caller who wants a non-default port, or a fake transport, has already built the
751    /// plane, and a sandbox constructible only from a [`Region`] would be a sandbox no test
752    /// can drive without AWS. `Sandbox::new(region)`, `Sandbox::adopt_in` and
753    /// `Sandbox::from_name`, which resolve credentials for a region, are in
754    /// `microvms_core::prelude`.
755    ///
756    /// The plane's own clock is what every wait here sleeps on, rather than a second one
757    /// this type would own. Two clocks in one lifecycle is the trap the daemon's turmoil
758    /// tests record: a deadline measured on one clock while the poll loop sleeps on another
759    /// reads the wrong elapsed time.
760    pub fn with_control_plane(control: ControlPlane) -> Self {
761        Self {
762            control: Arc::new(control),
763            image: None,
764            launch_image_arn: None,
765            microvm: None,
766            session: None,
767            session_backend: None,
768            lifecycle: Lifecycle::Pending,
769            lifecycle_watch: tokio::sync::watch::Sender::new(Lifecycle::Pending),
770            token_installed: false,
771            image_exists: false,
772            was_terminated: false,
773            bootstrap_count: 0,
774            suspended_window: None,
775            launch_adoptable: false,
776            launch_posture: None,
777            pending_agent_token: None,
778            idle_window: None,
779            torn_down: false,
780            adopted: false,
781            detached: false,
782            tunnel_identity: None,
783            build_services: None,
784            account: None,
785        }
786    }
787
788    /// Routes [`Sandbox::ensure_image`]'s STS and S3 calls through `services`.
789    ///
790    /// The seam beside `with_control_plane`'s transport: a test that scripts the control
791    /// plane replaces the two calls outside it here, and production builds
792    /// [`crate::control::SignedBuildServices`] on the first `ensure_image`.
793    pub fn with_build_services(mut self, services: Arc<dyn crate::control::BuildServices>) -> Self {
794        self.build_services = Some(services);
795        self
796    }
797
798    /// Routes the session [`Sandbox::run`] builds through `backend` instead of real HTTP.
799    ///
800    /// The daemon-side half of the test seam `with_control_plane` opens: scripting the
801    /// control plane gets a test through the launch, and this gets it through everything
802    /// the launched session then does — uploads, execs, downloads — without a daemon.
803    pub fn with_session_backend(mut self, backend: crate::session::SharedBackend) -> Self {
804        self.session_backend = Some(backend);
805        self
806    }
807
808    // ── the symspec's five variables, readable ───────────────────────────────
809
810    /// The lifecycle state, which is the symspec's `vm_state`.
811    pub fn lifecycle(&self) -> Lifecycle {
812        self.lifecycle
813    }
814
815    /// Whether the agent token has been installed (STATE-2).
816    pub fn token_installed(&self) -> bool {
817        self.token_installed
818    }
819
820    /// Whether an image is recorded as existing (STATE-1).
821    pub fn image_exists(&self) -> bool {
822        self.image_exists
823    }
824
825    /// Whether this VM was ever terminated (STATE-11).
826    pub fn was_terminated(&self) -> bool {
827        self.was_terminated
828    }
829
830    /// How many times the token has been installed. Never above one (STATE-3).
831    pub fn bootstrap_count(&self) -> u32 {
832        self.bootstrap_count
833    }
834
835    /// The image, once built.
836    pub fn image(&self) -> Option<&Image> {
837        self.image.as_ref()
838    }
839
840    /// The image ARN [`Sandbox::run`] sent in `RunMicrovm`: the caller's identifier with a
841    /// bare name resolved, or the built image's.
842    ///
843    /// Recorded before the call rather than read back from [`Sandbox::microvm`], which holds
844    /// only what an accepted launch answered: a launch the service refused, or one a caller
845    /// interrupted, still names the image it asked for here. `None` until `run` has resolved
846    /// an image, and on an adopted sandbox. Not the image [`Sandbox::terminate`] deletes, which
847    /// is only ever one this sandbox built ([`Sandbox::image`]).
848    pub fn launch_image_arn(&self) -> Option<&str> {
849        self.launch_image_arn.as_deref()
850    }
851
852    /// The VM as the service last described it.
853    pub fn microvm(&self) -> Option<&Microvm> {
854        self.microvm.as_ref()
855    }
856
857    /// The session, once launched.
858    pub fn session(&self) -> Option<&Session> {
859        self.session.as_ref()
860    }
861
862    /// The suspended window this sandbox asked for at launch, once it has launched.
863    pub fn suspended_window(&self) -> Option<Duration> {
864        self.suspended_window
865    }
866
867    /// A receiver that sees every lifecycle transition without taking this sandbox's lock.
868    ///
869    /// A binding's keepalive reads it between polls: a sandbox busy inside a long exec
870    /// holds the lock the whole time, which is exactly when the keepalive must keep polling,
871    /// and a suspend or terminate must end the keepalive before its next poll auto-resumes
872    /// the VM.
873    pub fn watch_lifecycle(&self) -> tokio::sync::watch::Receiver<Lifecycle> {
874        self.lifecycle_watch.subscribe()
875    }
876
877    fn set_lifecycle(&mut self, lifecycle: Lifecycle) {
878        self.lifecycle = lifecycle;
879        self.lifecycle_watch.send_replace(lifecycle);
880    }
881
882    /// The idle window this sandbox asked for at launch, once it has launched.
883    pub fn idle_window(&self) -> Option<Duration> {
884        self.idle_window
885    }
886
887    /// The tunnel identity, when the launch asked for one ([`RunRequest::identity`]).
888    ///
889    /// What `tunnel --verify-identity` verifies with: the host's secret and the VM's public
890    /// pin. `None` on a launch that did not ask, and the tunnel route then refuses an
891    /// identity request with close code 4401 rather than downgrading.
892    pub fn tunnel_identity(&self) -> Option<&crate::identity::TunnelIdentity> {
893        self.tunnel_identity.as_ref()
894    }
895
896    /// The egress posture of this sandbox's launch (BIND-12), which its session carries.
897    ///
898    /// The launch's own [`RunRequest::egress_posture`] once [`Sandbox::run`] was accepted.
899    /// Otherwise [`EgressPosture::default`], `unsealed`: an adopted sandbox never saw the
900    /// launch options, and the weakest true claim is the only one it can make.
901    ///
902    /// [`EgressPosture::default`]: crate::control::EgressPosture::default
903    pub fn egress_posture(&self) -> crate::control::EgressPosture {
904        self.launch_posture.unwrap_or_default()
905    }
906
907    /// The agent port the control plane was built with: the hooks port on every image
908    /// this sandbox builds, and the port the daemon listens on in every VM it launches.
909    /// Read-only; `agents::AgentVm` needs it to derive a Dockerfile whose `AGENTD_PORT`
910    /// agrees with the launch.
911    pub fn port(&self) -> u16 {
912        self.control.port()
913    }
914
915    // ── build ────────────────────────────────────────────────────────────────
916
917    /// Builds an image and waits for it to become usable.
918    ///
919    /// Every local guard runs inside [`ControlPlane::create_image`], before the call —
920    /// which matters because the create happens *after* the caller's artifact upload, so a
921    /// rejection AWS raises costs the upload first.
922    pub async fn build_image(&mut self, request: CreateImageRequest) -> Result<&Image, Error> {
923        let size = request.size;
924        let created = self.control.create_image(request).await?;
925        let mut built = self
926            .control
927            .wait_for_image(&created.identifier, size, WaitOpts::default())
928            .await?;
929        // The logging config survives the wait from the create's own record, because the
930        // readback cannot carry it: `GetMicrovmImage` reports no logging member, and the
931        // resolved log stream's discriminator was minted inside `create_image` — this is
932        // the only copy, and dropping it here would leave the caller unable to name the
933        // stream their build wrote to.
934        built.log_group = created.log_group;
935        built.log_stream = created.log_stream;
936        // Recorded before any launch, because a built image exists whether or not anything
937        // is ever run from it — and the teardown has to be able to name it either way.
938        self.image_exists = true;
939        self.image = Some(built);
940        Ok(self.image.as_ref().expect("just assigned"))
941    }
942
943    /// Builds or reuses the content-addressed image for `request` (#221): the name, the
944    /// decision after each describe, the upload and the create race are
945    /// [`crate::control::ensure`]'s.
946    pub async fn ensure_image(
947        &mut self,
948        request: crate::control::EnsureImageRequest,
949    ) -> Result<crate::control::EnsuredImage, Error> {
950        // Everything local first: a request this client refuses costs no call at all, the
951        // caller-identity lookup included.
952        //
953        // On the blocking pool, not on this task: `prepare` hashes and zips the daemon and
954        // the build context, about a second of CPU for the 2 MB daemon in a debug build.
955        // Inline, it stalls every task on this worker, and a concurrent ensure's credential
956        // fetch parked behind it past the instance-metadata provider's one-second timeout
957        // fails as a missing identity (#309).
958        let control = Arc::clone(&self.control);
959        let prepared =
960            tokio::task::spawn_blocking(move || crate::control::ensure::prepare(&control, request))
961                .await
962                .map_err(|joined| {
963                    Error::new(
964                        ErrorKind::Unexpected,
965                        format!("preparing the image's artifact did not complete: {joined}"),
966                    )
967                })??;
968        let services = self.build_services().await?;
969        let account = match &self.account {
970            Some(account) => account.clone(),
971            None => {
972                let account = services.caller_account().await?;
973                self.account = Some(account.clone());
974                account
975            }
976        };
977        let ensured =
978            crate::control::ensure::ensure(&self.control, services.as_ref(), &account, prepared)
979                .await?;
980        self.image_exists = true;
981        self.image = Some(ensured.image.clone());
982        Ok(ensured)
983    }
984
985    /// The STS and S3 client `ensure_image` and `upload_artifact_for` reach AWS through: the one
986    /// `with_build_services` set, or the plane's adapters' for its region, built once.
987    async fn build_services(&mut self) -> Result<Arc<dyn crate::control::BuildServices>, Error> {
988        if let Some(services) = &self.build_services {
989            return Ok(Arc::clone(services));
990        }
991        let built = self
992            .control
993            .adapters()
994            .build_services(self.control.region().clone())
995            .await?;
996        self.build_services = Some(Arc::clone(&built));
997        Ok(built)
998    }
999
1000    /// The artifact bytes to upload to the request's `code_artifact_uri`.
1001    ///
1002    /// The upload is the caller's on this path; [`Sandbox::ensure_image`] uploads for
1003    /// itself.
1004    pub fn build_artifact_for(&self, request: &CreateImageRequest) -> Result<Vec<u8>, Error> {
1005        self.control.build_artifact_for(request)
1006    }
1007
1008    /// Builds the artifact for `request` and puts it at its `code_artifact_uri`, through the
1009    /// build services `ensure_image` uploads with (#258): for a build under a name the caller
1010    /// chose, where no ensure derives the key. The URI must be `s3://<bucket>/<key>`.
1011    ///
1012    /// Run [`Self::preflight`] first: a request this client refuses then costs no upload.
1013    pub async fn upload_artifact_for(&mut self, request: &CreateImageRequest) -> Result<(), Error> {
1014        let (bucket, key) = crate::control::ensure::s3_location(&request.code_artifact_uri)?;
1015        let bytes = self.control.build_artifact_for(request)?;
1016        let services = self.build_services().await?;
1017        services.put_object(bucket, key, bytes).await
1018    }
1019
1020    /// Every local guard [`Self::build_image`] runs, callable **before** the artifact upload.
1021    ///
1022    /// A delegation to [`ControlPlane::preflight`], on this type so the CLI's build path
1023    /// reaches it through the one sandbox it already holds. Local; zero calls. The point is
1024    /// ordering: `build_image`'s guards run after the caller's upload, so a request this
1025    /// client itself refuses would still cost the S3 PUT unless the caller checks first.
1026    pub fn preflight(&self, request: &CreateImageRequest) -> Result<(), Error> {
1027        self.control.preflight(request)
1028    }
1029
1030    /// The ARN for `identifier`: an ARN passes through with zero calls, a bare name is
1031    /// resolved through the image listing by exact match.
1032    ///
1033    /// A read-only delegation to [`ControlPlane::resolve_image_arn`], the resolution
1034    /// [`Sandbox::run`] makes itself, for a caller that wants the ARN without launching. It
1035    /// touches none of the five state-machine variables: resolution is a question about the
1036    /// account, not about this VM's lifecycle.
1037    pub async fn resolve_image_arn(&self, identifier: &str) -> Result<String, Error> {
1038        self.control.resolve_image_arn(identifier).await
1039    }
1040
1041    /// The image with exactly `name`, or `None`. Read-only; see
1042    /// [`ControlPlane::find_image_by_name`] for the pagination and exact-match rules.
1043    pub async fn find_image_by_name(
1044        &self,
1045        name: &str,
1046    ) -> Result<Option<crate::control::ops::MicrovmImageSummaryWire>, Error> {
1047        self.control.find_image_by_name(name).await
1048    }
1049
1050    /// The content hash `build --reuse` keys an image name to. Local; zero calls.
1051    pub fn artifact_content_hash_for(&self, request: &CreateImageRequest) -> String {
1052        self.control.artifact_content_hash_for(request)
1053    }
1054
1055    /// The Dockerfile `request` builds with; see [`ControlPlane::dockerfile_for`]. Local;
1056    /// zero calls.
1057    pub fn dockerfile_for(&self, request: &CreateImageRequest) -> String {
1058        self.control.dockerfile_for(request)
1059    }
1060
1061    /// The versions of a managed base image, for pinning
1062    /// [`CreateImageRequest::base_image_version`].
1063    ///
1064    /// A read-only delegation to [`crate::control::ControlPlane::managed_base_versions`], on
1065    /// this type for the reason [`Self::resolve_image_arn`] gives: it touches none of the five
1066    /// state-machine variables, because a question about AWS's published bases is not a
1067    /// question about this VM's lifecycle.
1068    pub async fn managed_base_versions(
1069        &self,
1070        base_image_arn: &str,
1071    ) -> Result<Vec<crate::control::ops::ManagedMicrovmImageVersionWire>, Error> {
1072        self.control.managed_base_versions(base_image_arn).await
1073    }
1074
1075    /// One version's configuration, state, and availability status. Read-only.
1076    pub async fn image_version(
1077        &self,
1078        identifier: &str,
1079        version: &str,
1080    ) -> Result<crate::control::ops::MicrovmImageVersionSummaryWire, Error> {
1081        self.control.get_image_version(identifier, version).await
1082    }
1083
1084    // ── run (STATE-1, STATE-2, STATE-3) ──────────────────────────────────────
1085
1086    /// Launches a MicroVM and returns its session. By default it waits for RUNNING
1087    /// and for the daemon to answer; setting [`RunRequest::wait`] to false skips
1088    /// those readiness waits.
1089    ///
1090    /// # The three state requirements this is
1091    ///
1092    /// STATE-1: the accepted launch moves the lifecycle to PENDING and records the image as
1093    /// existing. STATE-2: the platform reporting RUNNING is what marks the token installed
1094    /// — not the launch call, because the run hook is what delivers it and a launch that
1095    /// dies during startup delivered nothing. STATE-3: `bootstrap_count` is incremented
1096    /// exactly here, and a second `run` on the same sandbox is refused, which is what makes
1097    /// "at most once per VM lifetime" a property of the type rather than of a caller's
1098    /// discipline.
1099    ///
1100    /// The agent token rides in `runHookPayload`, which is what keeps it out of the shared
1101    /// image snapshot. That is safe because the platform forwards no external traffic until
1102    /// the run hook returns 200, so a per-VM secret delivered at launch wins the
1103    /// first-writer race through the endpoint.
1104    ///
1105    /// # A bare image name
1106    ///
1107    /// [`RunRequest::image_identifier`] may be a name: after the local refusals it is resolved
1108    /// through [`ControlPlane::resolve_image_arn`], and [`Sandbox::launch_image_arn`] records
1109    /// the ARN sent. A name that resolves to nothing fails with `ERR_PRECONDITION` and leaves
1110    /// the sandbox as it was, so a later `run` on it can still launch.
1111    pub async fn run(&mut self, request: RunRequest) -> Result<&mut Session, Error> {
1112        self.refuse_detached("run")?;
1113        // STATE-3's local half. A sandbox that has already bootstrapped cannot bootstrap
1114        // again, and the refusal is here rather than in a comment because `run` twice is
1115        // the plausible mistake — a retry loop around a launch that timed out.
1116        if self.bootstrap_count > 0 || self.microvm.is_some() {
1117            return Err(Error::invalid_arg(format!(
1118                "this sandbox has already launched a VM ({} bootstrap(s), lifecycle {}), and the \
1119                 agent token is installed at most once per VM lifetime (STATE-3). A second VM \
1120                 needs a second Sandbox — reusing this one would either re-deliver a run-hook \
1121                 payload to a daemon whose one-shot bootstrap refuses it, or silently address \
1122                 two guests through one handle.",
1123                self.bootstrap_count, self.lifecycle,
1124            )));
1125        }
1126
1127        // The network options, refused and classified by the one function a harness asks
1128        // before a launch (BIND-13), so its answer and this launch cannot disagree. Opposite
1129        // intents are refused rather than resolved by a precedence rule nobody would find:
1130        // `--egress` asks the platform for outbound network and `--deny-egress` asks the
1131        // guest's own clients to refuse it, so a launch carrying both would report `open`
1132        // while its workload's tools failed closed.
1133        let posture = crate::control::egress_posture_for(
1134            request.egress,
1135            &request.egress_network_connectors,
1136            request.deny_egress,
1137            Some(self.control.region()),
1138        )?;
1139
1140        let Some(identifier) = request
1141            .image_identifier
1142            .clone()
1143            .or_else(|| self.image.as_ref().map(|image| image.identifier.clone()))
1144        else {
1145            return Err(Error::new(
1146                ErrorKind::Precondition,
1147                "no image to launch: pass RunRequest::with_image or call build_image first."
1148                    .to_string(),
1149            ));
1150        };
1151
1152        if request.client_token.is_some() && (request.agent_token.is_none() || request.identity) {
1153            return Err(Error::invalid_arg(
1154                "a stable client_token requires an explicit agent_token and identity=false; persist identical launch parameters before retrying",
1155            ));
1156        }
1157        let agent_token = match request.agent_token.clone() {
1158            Some(token) => token,
1159            None => mint_agent_token(self.control.entropy())?,
1160        };
1161        // Generated before the payload because the payload carries its two public-facing
1162        // fields. The VM's secret half lives exactly as long as this binding: `keep()` below
1163        // drops it before the launch call returns.
1164        let launch_identity = if request.identity {
1165            Some(crate::entropy::launch_identity(self.control.entropy())?)
1166        } else {
1167            None
1168        };
1169        // Checked even though this builds the JSON itself, because neither half is ours:
1170        // the token may be caller-supplied, so someone passing a signed blob rather than a
1171        // bearer token is exactly who this catches (TRAP-5), and the launch env is entirely
1172        // the caller's. This is the pre-flight refusal — over-ceiling fails here with the
1173        // byte count, before the launch, rather than as a `ValidationException` on a member
1174        // the caller did not know they were filling.
1175        let payload = RunHookPayload::for_launch_with_identity(
1176            &agent_token,
1177            &request.effective_launch_env(),
1178            launch_identity.as_ref(),
1179        )?;
1180
1181        let mut wire = RunMicrovmRequest::new(identifier, payload);
1182        wire.image_version = request.image_version.clone();
1183        wire.execution_role_arn = request.execution_role_arn.clone();
1184        wire.egress_network_connectors = request.egress_network_connectors.clone();
1185        wire.max_idle_sec = request.max_idle_sec;
1186        wire.suspended_sec = request.suspended_sec;
1187        wire.auto_resume = request.auto_resume;
1188        wire.max_duration_sec = request.max_duration_sec;
1189        wire.token_scope = request.token_scope.clone();
1190        wire.client_token = request.client_token.clone();
1191        wire.logging = request.logging.clone();
1192        if request.egress {
1193            wire = wire.with_egress();
1194        }
1195        if request.shell {
1196            wire = wire.with_shell();
1197        }
1198
1199        // `imageIdentifier` takes an ARN, and the service answers a bare name with HTTP 400
1200        // "Malformed ARN", so a name is resolved here, where every surface's launch passes
1201        // (the CLI's `run --image`, both bindings' `Sandbox.run` and `AgentVm.launch`). The
1202        // launch's local refusals go first: the listing a name costs is a call, and a launch
1203        // `run_microvm` would refuse anyway costs none. An ARN passes through with no call.
1204        self.control.launch_connectors(&wire)?;
1205        wire.image_identifier = self
1206            .control
1207            .resolve_image_arn(&wire.image_identifier)
1208            .await?;
1209        self.launch_image_arn = Some(wire.image_identifier.clone());
1210
1211        let launched = self.control.run_microvm(wire).await?;
1212
1213        // The durable half of the identity, kept the moment the launch is accepted: the host
1214        // secret and the VM's public pin. The VM's own secret ends here — `keep` drops it —
1215        // so from this line on the host can verify its VM and impersonate it never.
1216        self.tunnel_identity = launch_identity.map(crate::identity::LaunchIdentity::keep);
1217
1218        // STATE-1: the launch was accepted.
1219        self.set_lifecycle(Lifecycle::Pending);
1220        self.image_exists = true;
1221        // Recorded here rather than after the wait, because the window the idlePolicy
1222        // enforces was set by *this* request and a launch that then fails still leaves a VM
1223        // the caller may have to reason about.
1224        self.suspended_window = Some(Duration::from_secs(u64::from(request.suspended_sec)));
1225        self.idle_window = Some(Duration::from_secs(u64::from(request.max_idle_sec)));
1226        self.microvm = Some(launched);
1227        // A caller-supplied client token can adopt the VM an earlier attempt launched, which
1228        // may have idle-suspended since (#195); a minted token always launches afresh.
1229        self.launch_adoptable = request.client_token.is_some();
1230        self.launch_posture = Some(posture);
1231        self.pending_agent_token = Some(agent_token);
1232
1233        if request.wait {
1234            return self.wait_until_running(request.ready_timeout).await;
1235        }
1236        // Not waiting: the endpoint is in the launch reply, so the session is addressable
1237        // now, and a daemon request before RUNNING fails like any other unready request.
1238        self.build_session()?;
1239        Ok(self.session.as_mut().expect("just assigned"))
1240    }
1241
1242    /// The session for the launched VM, from its endpoint and the launch's agent token.
1243    fn build_session(&mut self) -> Result<(), Error> {
1244        let (Some(vm), Some(agent_token)) = (&self.microvm, &self.pending_agent_token) else {
1245            return Err(Error::new(
1246                ErrorKind::Precondition,
1247                "no launch to build a session for",
1248            ));
1249        };
1250        let minter = Arc::new(ControlPlaneMinter::new(
1251            Arc::clone(&self.control),
1252            vm.id.clone(),
1253        ));
1254        // The plane's clock, so the session's exec ids and token refreshes read the same time
1255        // source as the lifecycle that launched it.
1256        let mut builder = Session::builder(vm.endpoint.clone(), agent_token.clone())
1257            .with_minter(minter)
1258            .with_port(self.control.port())
1259            .with_egress_posture(self.egress_posture())
1260            .with_clock(self.control.shared_clock());
1261        if let Some(backend) = &self.session_backend {
1262            builder = builder.with_backend(Arc::clone(backend));
1263        }
1264        self.session = Some(builder.build_with(self.control.adapters())?);
1265        Ok(())
1266    }
1267
1268    /// Waits for a launch accepted by [`Sandbox::run`] to reach RUNNING, up to `timeout`, and
1269    /// then for its daemon to answer, up to [`crate::session::DEFAULT_BOOTSTRAP_TIMEOUT`].
1270    ///
1271    /// `run` calls this itself unless [`RunRequest::wait`] was off. A launch that adopted an
1272    /// existing VM through its client token resumes it if it idle-suspended (#195); a fresh
1273    /// launch that reaches any terminal state first fails fast with `stateReason` (TRAP-8).
1274    ///
1275    /// # Why RUNNING isn't enough
1276    ///
1277    /// RUNNING says the run hook answered, so the daemon is up and the token installed
1278    /// (STATE-2), but the endpoint's proxy path commonly refuses a connection or two just
1279    /// after. The session is handed back once one health poll through it has answered, so a
1280    /// first exec after a launch doesn't meet that window, on any surface (#254). A daemon that
1281    /// never answers fails this with `ERR_TIMEOUT`, and the lifecycle stays RUNNING: the VM is
1282    /// there and billing, and [`Sandbox::session`] can still wait for it.
1283    pub async fn wait_until_running(&mut self, timeout: Duration) -> Result<&mut Session, Error> {
1284        self.refuse_detached("wait until running")?;
1285        let id = self.require_microvm("wait_until_running")?;
1286        if self.lifecycle != Lifecycle::Pending {
1287            return Err(Error::invalid_arg(format!(
1288                "microvm {id} is {}; wait_until_running finishes a launch that is still PENDING",
1289                self.lifecycle,
1290            )));
1291        }
1292        let opts = WaitOpts::for_lifecycle(timeout);
1293        let running = self
1294            .control
1295            .wait_for_sandbox_launch(&id, opts, self.launch_adoptable)
1296            .await?;
1297
1298        // STATE-2. The platform reported the run hook succeeded, so the token is in the
1299        // guest's memory — and this is the one place that counts it (STATE-3).
1300        self.set_lifecycle(Lifecycle::Running);
1301        self.token_installed = true;
1302        self.bootstrap_count += 1;
1303        self.microvm = Some(running);
1304        if self.session.is_none() {
1305            self.build_session()?;
1306        }
1307        let session = self.session.as_mut().expect("just assigned");
1308        session
1309            .wait_until_ready(crate::session::DEFAULT_BOOTSTRAP_TIMEOUT)
1310            .await?;
1311        Ok(session)
1312    }
1313
1314    /// Waits until the VM this sandbox addresses answers, whatever a launch still has to wait
1315    /// for: from PENDING, [`Sandbox::wait_until_running`] with `running_timeout` (RUNNING, then
1316    /// the daemon); from RUNNING, the daemon alone, up to
1317    /// [`crate::session::DEFAULT_BOOTSTRAP_TIMEOUT`].
1318    ///
1319    /// The shape for a process that adopted a VM another one launched without waiting: it can't
1320    /// know which of the two waits is left, and the lifecycle [`Sandbox::adopt`] read from the
1321    /// service says. Any other lifecycle is refused, because a suspended or terminated VM isn't
1322    /// on its way to answering.
1323    pub async fn wait_until_ready(
1324        &mut self,
1325        running_timeout: Duration,
1326    ) -> Result<&mut Session, Error> {
1327        if self.lifecycle == Lifecycle::Running {
1328            self.refuse_detached("wait until ready")?;
1329            let session = self.session.as_mut().ok_or_else(|| {
1330                Error::new(ErrorKind::Precondition, "a RUNNING sandbox with no session")
1331            })?;
1332            session
1333                .wait_until_ready(crate::session::DEFAULT_BOOTSTRAP_TIMEOUT)
1334                .await?;
1335            return Ok(session);
1336        }
1337        self.wait_until_running(running_timeout).await
1338    }
1339
1340    // ── adopt (STATE-3, with the lifecycle read from the service) ────────────
1341
1342    /// A sandbox for a VM another process launched, rebuilt from its private record.
1343    ///
1344    /// The durable-workflow shape: every step runs in a fresh process, and each one needs
1345    /// suspend, resume, and terminate, not just the exec and file surface `Session::attach`
1346    /// (`microvms_core::prelude::SessionExt::attach`) gives. The lifecycle is read from `GetMicrovm`
1347    /// rather than assumed, so every guard below starts from what the service reports.
1348    ///
1349    /// # Bootstrap is counted, never repeated (STATE-3)
1350    ///
1351    /// The VM was bootstrapped by the launch that created it, so an adopted sandbox refuses
1352    /// [`Sandbox::run`] and never sends a run-hook payload. A VM adopted while still PENDING
1353    /// finishes through [`Sandbox::wait_until_running`], which counts the bootstrap once
1354    /// when the service reports RUNNING, the same as a launch this sandbox made itself.
1355    ///
1356    /// `endpoint` must agree with the service's when the service reports one: a mismatch
1357    /// means the identifiers came from two different records. `agent_token` is the bearer
1358    /// credential the VM was launched with; it never appears in `Debug` or an error.
1359    pub async fn adopt(
1360        control: ControlPlane,
1361        microvm_id: impl Into<String>,
1362        endpoint: impl Into<String>,
1363        agent_token: impl Into<String>,
1364    ) -> Result<Self, Error> {
1365        let microvm_id = microvm_id.into();
1366        let endpoint = endpoint.into();
1367        let agent_token = agent_token.into();
1368        if agent_token.is_empty() {
1369            return Err(Error::invalid_arg(
1370                "adopt needs the agent token the VM was launched with: its daemon accepts only \
1371                 that bearer, and adopting without it would build a handle every exec refuses.",
1372            ));
1373        }
1374        let mut vm = control.get_microvm(&microvm_id).await?;
1375        if !endpoint.is_empty() && !vm.endpoint.is_empty() && vm.endpoint != endpoint {
1376            return Err(Error::invalid_arg(format!(
1377                "microvm {microvm_id} reports endpoint {}, not {endpoint}: the id and endpoint \
1378                 came from different records, and a session built from them would address one \
1379                 VM while its lifecycle calls reached another.",
1380                vm.endpoint,
1381            )));
1382        }
1383        if vm.endpoint.is_empty() {
1384            vm.endpoint = endpoint;
1385        }
1386        let Some(lifecycle) = Lifecycle::from_service(&vm.state) else {
1387            return Err(Error::new(
1388                ErrorKind::Platform,
1389                format!(
1390                    "microvm {microvm_id} reports state {}, which this client does not know; \
1391                     refusing to guess which lifecycle guards apply.",
1392                    vm.state,
1393                ),
1394            ));
1395        };
1396
1397        let mut sandbox = Self::with_control_plane(control);
1398        sandbox.adopted = true;
1399        sandbox.set_lifecycle(lifecycle);
1400        // The window the VM was launched with, so a keepalive on the adopted session paces
1401        // itself against the real idle policy rather than the platform minimum.
1402        sandbox.idle_window = vm
1403            .idle_policy
1404            .as_ref()
1405            .map(|policy| Duration::from_secs(u64::from(policy.max_idle_duration_seconds)));
1406        // A VM exists, so the image it was launched from did (STATE-1).
1407        sandbox.image_exists = true;
1408        // PENDING may still idle-suspend before this handle sees RUNNING (#195).
1409        sandbox.launch_adoptable = true;
1410        sandbox.pending_agent_token = Some(agent_token);
1411        match lifecycle {
1412            Lifecycle::Pending => {}
1413            Lifecycle::Running | Lifecycle::Suspending | Lifecycle::Suspended => {
1414                sandbox.token_installed = true;
1415                sandbox.bootstrap_count = 1;
1416            }
1417            Lifecycle::Terminating | Lifecycle::Terminated => {
1418                sandbox.bootstrap_count = 1;
1419                sandbox.was_terminated = true;
1420            }
1421        }
1422        sandbox.microvm = Some(vm);
1423        if lifecycle.is_live() {
1424            sandbox.build_session()?;
1425        }
1426        Ok(sandbox)
1427    }
1428
1429    /// A [`crate::names::NameRecord`] for this VM, to register under `name`.
1430    ///
1431    /// The egress posture is left unknown: the sandbox does not keep its launch request, and
1432    /// a record must not claim a network it cannot vouch for. The tunnel identity is kept when
1433    /// the sandbox holds one, launched with it or adopted from a record that carried it: a
1434    /// record without it can't verify the VM later, which is what the pair is for (#263).
1435    pub fn name_record(&self, name: &str) -> Result<crate::names::NameRecord, Error> {
1436        let Some(vm) = self.microvm() else {
1437            return Err(Error::new(
1438                ErrorKind::Precondition,
1439                "there is no VM to name yet: launch or adopt one first",
1440            ));
1441        };
1442        let Some(session) = self.session() else {
1443            return Err(Error::new(
1444                ErrorKind::Precondition,
1445                format!(
1446                    "microvm {} has no session to take its agent token from",
1447                    vm.id
1448                ),
1449            ));
1450        };
1451        // Stamped on the plane's clock, the one every other time this sandbox reads comes from.
1452        let mut record = crate::names::NameRecord::new_at(
1453            name,
1454            vm.id.as_str(),
1455            vm.endpoint.as_str(),
1456            session.agent_token(),
1457            self.control.region().as_str(),
1458            self.control.clock().unix_now().as_secs(),
1459        )?;
1460        record.set_tunnel_identity(self.tunnel_identity.as_ref());
1461        Ok(record)
1462    }
1463
1464    /// [`Sandbox::adopt`] from a [`crate::names::NameRecord`] kept in any store.
1465    ///
1466    /// Keeps the record's tunnel identity, so [`Sandbox::tunnel_identity`] and a later
1467    /// [`Sandbox::name_record`] carry it. A record holding one half of the pair, or a pair that
1468    /// doesn't decode, is refused before any AWS call rather than adopted without it: the
1469    /// record claims a verifiable VM, and dropping the claim would hide that it's broken.
1470    pub async fn adopt_record(
1471        control: ControlPlane,
1472        record: crate::names::NameRecord,
1473    ) -> Result<Self, Error> {
1474        let identity = record.tunnel_identity()?;
1475        let mut sandbox = Self::adopt(
1476            control,
1477            record.microvm_id,
1478            record.endpoint,
1479            record.agent_token,
1480        )
1481        .await?;
1482        sandbox.tunnel_identity = identity;
1483        Ok(sandbox)
1484    }
1485
1486    /// Hands the VM off to another process and returns what that process needs to adopt it.
1487    ///
1488    /// For a workflow whose steps run in different processes (a durable function's launch
1489    /// step, then later steps that [`Sandbox::adopt`]): the launching process calls this
1490    /// instead of dropping the sandbox, which would warn that a live VM was abandoned. The
1491    /// VM keeps running and nothing is sent to AWS. From here on this sandbox is inert — its
1492    /// session is dropped and `run`, `wait_until_running`, `suspend`, `resume`, and
1493    /// `terminate` are refused — because the adopter now owns the lifecycle, and a second
1494    /// handle driving it would bypass the adopter's guards.
1495    ///
1496    /// Refused (`Precondition`) when there is no live VM to hand off: nothing launched yet,
1497    /// already torn down or terminated, or already detached.
1498    pub fn detach(&mut self) -> Result<Detached, Error> {
1499        self.refuse_detached("detach")?;
1500        let Some(vm) = self.microvm.as_ref() else {
1501            return Err(Error::new(
1502                ErrorKind::Precondition,
1503                "nothing to detach: this sandbox has not launched a VM.",
1504            ));
1505        };
1506        if self.torn_down || !self.lifecycle.is_live() {
1507            return Err(Error::new(
1508                ErrorKind::Precondition,
1509                format!(
1510                    "microvm {} is {} and there is no live VM to hand off; only a PENDING, \
1511                     RUNNING, or SUSPENDED VM can be adopted.",
1512                    vm.id, self.lifecycle,
1513                ),
1514            ));
1515        }
1516        let agent_token = self
1517            .session
1518            .as_ref()
1519            .map(|session| session.agent_token().to_string())
1520            .or_else(|| self.pending_agent_token.clone())
1521            .ok_or_else(|| {
1522                Error::new(
1523                    ErrorKind::Precondition,
1524                    format!(
1525                        "microvm {} has no agent token to hand off; an adopter could not \
1526                         reach its daemon.",
1527                        vm.id
1528                    ),
1529                )
1530            })?;
1531        let detached = Detached {
1532            microvm_id: vm.id.clone(),
1533            endpoint: vm.endpoint.clone(),
1534            region: self.control.region().clone(),
1535            port: self.control.port(),
1536            agent_token,
1537        };
1538        self.detached = true;
1539        self.session = None;
1540        self.pending_agent_token = None;
1541        Ok(detached)
1542    }
1543
1544    /// Whether [`Sandbox::detach`] handed this sandbox's VM to another process.
1545    pub fn detached(&self) -> bool {
1546        self.detached
1547    }
1548
1549    /// Refuses `what` on a sandbox whose VM was handed off.
1550    fn refuse_detached(&self, what: &str) -> Result<(), Error> {
1551        if !self.detached {
1552            return Ok(());
1553        }
1554        let id = self.microvm.as_ref().map_or("?", |vm| vm.id.as_str());
1555        Err(Error::new(
1556            ErrorKind::Precondition,
1557            format!(
1558                "cannot {what}: microvm {id} was detached and belongs to whoever adopts it. \
1559                 Adopt it with `Sandbox::adopt` and {what} through that handle."
1560            ),
1561        ))
1562    }
1563
1564    /// Whether this sandbox was built by [`Sandbox::adopt`] rather than by its own launch.
1565    pub fn adopted(&self) -> bool {
1566        self.adopted
1567    }
1568
1569    // ── suspend (STATE-4, STATE-5, STATE-6) ──────────────────────────────────
1570
1571    /// Freezes the VM and waits for the platform to report it.
1572    ///
1573    /// A freeze and restore rather than a stop and start: the guest keeps its memory, so the
1574    /// token, the filesystem, and every exec record survive. The one thing that does not is
1575    /// the guest's view of time — it observes the whole suspension as a single jump, so any
1576    /// timeout, lease, or TLS session a running command holds expires at once on resume.
1577    ///
1578    /// # STATE-5 is checked before the wire, not after
1579    ///
1580    /// A suspend from anything but RUNNING is refused here with **zero** control-plane
1581    /// calls. That is the observable difference between this and a client that lets AWS
1582    /// answer, and it is what the test asserts on.
1583    pub async fn suspend(&mut self) -> Result<(), Error> {
1584        self.refuse_detached("suspend")?;
1585        let id = self.require_microvm("suspend")?;
1586
1587        // STATE-5.
1588        if self.lifecycle != Lifecycle::Running {
1589            return Err(Error::invalid_arg(format!(
1590                "microvm {id} is {} and a suspend is only issued from RUNNING (STATE-5). Refused \
1591                 here rather than by the service, because the service's answer about a \
1592                 non-running id does not say which of the two things went wrong — and a suspend \
1593                 issued from SUSPENDED is a caller who believes they resumed.",
1594                self.lifecycle,
1595            )));
1596        }
1597
1598        // STATE-4: accepted, so the lifecycle moves before the wait. Acceptance is the
1599        // wire call succeeding, so the assignment comes after it: moving to SUSPENDING
1600        // first would leave a failed call (a throttle, a dead transport) stuck in a state
1601        // neither suspend nor resume accepts, bricking the handle over one bad request.
1602        self.control.suspend(&id).await?;
1603        self.set_lifecycle(Lifecycle::Suspending);
1604
1605        let settled = self
1606            .control
1607            .wait_for_state(
1608                &id,
1609                &crate::control::microvm::SUSPEND_WANTED,
1610                &[],
1611                self.lifecycle_wait(),
1612            )
1613            .await?;
1614
1615        // STATE-6, and the TERMINATED case beside it. A VM that dies while suspending is a
1616        // state to report rather than an exception out of the middle of a teardown, so the
1617        // wait *wants* TERMINATED — and recording it here is what stops a resume from being
1618        // offered afterwards (STATE-11).
1619        let settled_lifecycle = match settled.state.as_str() {
1620            "SUSPENDED" => Lifecycle::Suspended,
1621            "TERMINATED" => {
1622                self.was_terminated = true;
1623                Lifecycle::Terminated
1624            }
1625            other => {
1626                return Err(Error::new(
1627                    ErrorKind::Platform,
1628                    format!(
1629                        "the suspend wait returned {other}, which is neither SUSPENDED nor \
1630                         TERMINATED — and those two are what this client asked for."
1631                    ),
1632                ));
1633            }
1634        };
1635        self.set_lifecycle(settled_lifecycle);
1636        self.microvm = Some(settled);
1637        Ok(())
1638    }
1639
1640    // ── resume (STATE-7, STATE-8, STATE-12) ──────────────────────────────────
1641
1642    /// Thaws the VM and returns a usable session.
1643    ///
1644    /// # What is deliberately not re-delivered (STATE-7)
1645    ///
1646    /// Nothing. No run-hook payload, no token, no bootstrap. The in-memory token survived
1647    /// the freeze, and re-delivering it would hit the daemon's one-shot bootstrap and be
1648    /// refused — a 409 that reads like a broken VM.
1649    ///
1650    /// # The service decides, and a VM it ended is `WindowClosed` (STATE-12)
1651    ///
1652    /// No resume is refused here for the time the VM has spent suspended. The service ends a
1653    /// VM the idle policy suspended once `suspendedDurationSeconds` passes, and it kept a VM
1654    /// this client suspended resumable 1283 s into a 60 s window (measured 2026-10-12,
1655    /// us-east-1, #597). A resume the service refuses because the VM ended, whatever ended
1656    /// it, is [`ErrorKind::WindowClosed`] ([`ControlPlane::resume`]), and this records the VM
1657    /// as terminated, so a second resume is refused here with no call (STATE-11). A VM the
1658    /// idle policy suspended may still be RUNNING here, so resume first reads its service
1659    /// state. It resumes from SUSPENDED and reports `WindowClosed` for an ended VM.
1660    ///
1661    /// # The proxy token is dropped (STATE-8)
1662    ///
1663    /// [`Session::rebind`] invalidates it. The endpoint URL does not change across
1664    /// suspend/resume, so the rebind is usually a no-op on the URL — but a token minted
1665    /// against the pre-suspend instance may no longer validate, and that rejection reads
1666    /// exactly like a dead daemon.
1667    pub async fn resume(&mut self) -> Result<&mut Session, Error> {
1668        self.refuse_detached("resume")?;
1669        let id = self.require_microvm("resume")?;
1670
1671        // STATE-11's local half: a terminated VM never returns to RUNNING, so the refusal
1672        // comes before any call.
1673        if self.was_terminated || self.lifecycle == Lifecycle::Terminated {
1674            return Err(Error::invalid_arg(format!(
1675                "microvm {id} was terminated, and a terminated VM never returns to RUNNING \
1676                 (STATE-11). There is nothing to resume: the guest's memory is gone, so even a \
1677                 call the service accepted would hand back a different machine."
1678            )));
1679        }
1680        let mut resume_state = self.lifecycle;
1681        // Idle suspension happens without a client call. Refresh a RUNNING handle before
1682        // applying STATE-7, but keep STATE-11 above entirely local once termination is known.
1683        if self.lifecycle == Lifecycle::Running {
1684            let observed = self.control.get_microvm(&id).await?;
1685            resume_state = Lifecycle::from_service(&observed.state).ok_or_else(|| {
1686                Error::new(
1687                    ErrorKind::Platform,
1688                    format!("microvm {id} reports unknown state {}", observed.state),
1689                )
1690            })?;
1691            let ended = crate::constants::DEAD_STATES.contains(&observed.state.as_str());
1692            let error = ended.then(|| {
1693                Error::new(
1694                    ErrorKind::WindowClosed,
1695                    format!(
1696                        "microvm {id} can't be resumed: GetMicrovm reports the VM {} ({}). \
1697                         A VM that has ended doesn't come back; launch a new one.",
1698                        observed.state,
1699                        observed.reason(),
1700                    ),
1701                )
1702            });
1703            self.microvm = Some(observed);
1704            // A transient state must not strand the handle: only RUNNING handles refresh
1705            // here, so leave it eligible to observe the service again on the next call.
1706            if resume_state == Lifecycle::Suspended {
1707                self.set_lifecycle(resume_state);
1708            }
1709            if let Some(error) = error {
1710                self.was_terminated = true;
1711                self.set_lifecycle(Lifecycle::Terminated);
1712                return Err(error);
1713            }
1714        }
1715        if resume_state != Lifecycle::Suspended {
1716            return Err(Error::invalid_arg(format!(
1717                "microvm {id} is {} and a resume is only issued from SUSPENDED (STATE-7).",
1718                resume_state,
1719            )));
1720        }
1721
1722        // STATE-12: a `WindowClosed` refusal is a VM that ended before this resume. It's
1723        // recorded as TERMINATED whichever of TERMINATING or TERMINATED `GetMicrovm` read,
1724        // because the service has said the VM's state can't change, and as a termination, so
1725        // the next resume is refused before any call (STATE-11). Any other refusal leaves the
1726        // sandbox SUSPENDED, and a retry goes to the service again.
1727        if let Err(refused) = self.control.resume(&id).await {
1728            if refused.kind() == ErrorKind::WindowClosed {
1729                self.was_terminated = true;
1730                self.set_lifecycle(Lifecycle::Terminated);
1731            }
1732            return Err(refused);
1733        }
1734        // `fail_on` is the *dead* states rather than the terminal ones: SUSPENDED is the
1735        // state this call was made from, so failing on it would fail every resume. A VM that
1736        // terminates once the resume is accepted never reaches RUNNING, and waiting only for
1737        // RUNNING there burns the full timeout and then reports a timeout message hiding a
1738        // cause the service had already stated in `stateReason`.
1739        let running = self
1740            .control
1741            .wait_for_state(
1742                &id,
1743                &["RUNNING"],
1744                &crate::constants::DEAD_STATES,
1745                self.lifecycle_wait(),
1746            )
1747            .await?;
1748
1749        self.set_lifecycle(Lifecycle::Running);
1750        // STATE-8, through the endpoint the service just reported rather than the one held:
1751        // the URL is measured not to change, and reading it from the response is what makes
1752        // that a fact this code depends on rather than an assumption it encodes.
1753        let endpoint = running.endpoint.clone();
1754        self.microvm = Some(running);
1755        if let Some(session) = self.session.as_mut() {
1756            session.rebind(endpoint);
1757        }
1758
1759        self.session.as_mut().ok_or_else(|| {
1760            Error::new(
1761                ErrorKind::Unexpected,
1762                "the VM resumed but this sandbox holds no session, which run() always builds"
1763                    .to_string(),
1764            )
1765        })
1766    }
1767
1768    // ── terminate (STATE-9, STATE-10) ────────────────────────────────────────
1769
1770    /// Tears down, best-effort, never erroring.
1771    ///
1772    /// Order: VM, then image, then the log group **last**. The log group is last because the
1773    /// service can recreate a group deleted before its image — and see
1774    /// [`TeardownReport::undeleted`] for why this crate names it rather than deleting it.
1775    pub async fn terminate(&mut self, opts: TeardownOpts) -> TeardownReport {
1776        let mut report = TeardownReport::default();
1777        if let Err(error) = self.refuse_detached("terminate") {
1778            // Never erroring is `terminate`'s contract, so the refusal is reported rather
1779            // than raised; the VM is untouched and still belongs to its adopter.
1780            report.failures.push(error.to_string());
1781            report.lifecycle = Some(self.lifecycle);
1782            return report;
1783        }
1784        self.torn_down = true;
1785
1786        // The session first: it holds a cached proxy token whose only remaining use would be
1787        // a request against a VM that is going away.
1788        self.session = None;
1789
1790        // 1. The VM.
1791        if let Some(id) = self.microvm.as_ref().map(|vm| vm.id.clone()) {
1792            // STATE-9. Recorded before the call, so a terminate whose call fails still marks
1793            // the VM as one this client asked to destroy — which is what stops a later
1794            // resume (STATE-11) rather than leaving the sandbox looking resumable.
1795            self.set_lifecycle(Lifecycle::Terminating);
1796            self.was_terminated = true;
1797
1798            match self.control.terminate(&id).await {
1799                Ok(()) => report.terminate_accepted = true,
1800                Err(error) => {
1801                    report.failures.push(format!("terminate {id}: {error}"));
1802                    report.undeleted.push(id.clone());
1803                }
1804            }
1805
1806            if report.terminate_accepted
1807                && let Some(timeout) = opts.wait_for_terminated
1808            {
1809                let wait = WaitOpts::for_lifecycle(timeout);
1810                match self
1811                    .control
1812                    .wait_for_state(&id, &["TERMINATED"], &[], wait)
1813                    .await
1814                {
1815                    // STATE-10.
1816                    Ok(settled) => {
1817                        self.set_lifecycle(Lifecycle::Terminated);
1818                        self.microvm = Some(settled);
1819                    }
1820                    // Not a leak: the platform accepted the terminate, so the VM is on its
1821                    // way out and the lifecycle stays TERMINATING honestly.
1822                    Err(error) => report
1823                        .failures
1824                        .push(format!("waiting for {id} to reach TERMINATED: {error}")),
1825                }
1826            }
1827        }
1828
1829        // 2. The image, retrying — an image in CREATING refuses deletion and a VM still
1830        //    terminating holds a reference.
1831        if opts.delete_image {
1832            match self.image.as_ref().map(|image| image.identifier.clone()) {
1833                Some(identifier) => {
1834                    let deleted = self
1835                        .control
1836                        .delete_image(&identifier, opts.delete_attempts, opts.delete_backoff)
1837                        .await;
1838                    report.image_deleted = Some(deleted);
1839                    if deleted {
1840                        self.image_exists = false;
1841                    } else {
1842                        report.failures.push(format!(
1843                            "the image {identifier} survived {} delete attempts",
1844                            opts.delete_attempts.max(1)
1845                        ));
1846                        report.undeleted.push(identifier);
1847                    }
1848                }
1849                None => report.image_deleted = Some(false),
1850            }
1851        }
1852
1853        // 3. The log group, LAST. Named rather than deleted; see TeardownReport::undeleted.
1854        if opts.delete_log_group
1855            && let Some(group) = self.image.as_ref().map(Image::build_log_group)
1856        {
1857            report.failures.push(format!(
1858                "the build log group {group} was not deleted: CloudWatch Logs is not in this \
1859                 crate's dependency set, so it is reported rather than removed. It is \
1860                 service-created, which means no Terraform stack owns it and `terraform destroy` \
1861                 leaves it behind — six accumulated before anyone noticed."
1862            ));
1863            report.undeleted.push(group);
1864        }
1865
1866        report.lifecycle = Some(self.lifecycle);
1867        report
1868    }
1869
1870    // ── internals ────────────────────────────────────────────────────────────
1871
1872    /// The VM id, or a precondition error naming what was attempted.
1873    fn require_microvm(&self, what: &str) -> Result<String, Error> {
1874        self.microvm
1875            .as_ref()
1876            .map(|vm| vm.id.clone())
1877            .ok_or_else(|| {
1878                Error::new(
1879                    ErrorKind::Precondition,
1880                    format!("nothing to {what}: this sandbox has not launched a VM."),
1881                )
1882            })
1883    }
1884
1885    /// Five minutes at five-second polls, for suspend, resume, and terminate.
1886    fn lifecycle_wait(&self) -> WaitOpts {
1887        WaitOpts::for_lifecycle(DEFAULT_LIFECYCLE_TIMEOUT)
1888    }
1889}
1890
1891/// Warns about a live VM rather than tearing it down.
1892///
1893/// See the module docs: `Drop` cannot await, so a teardown here would either deadlock
1894/// inside a runtime or race the process exit. The warning names the id, because the only
1895/// useful thing a drop can do is tell whoever reads stderr what to go delete.
1896///
1897/// The warning goes through the plane's [`Adapters::warn`](crate::adapters::Adapters::warn),
1898/// which in production writes it to stderr.
1899impl Sandbox {
1900    /// The warning `Drop` writes for a live VM nobody took responsibility for, or `None`
1901    /// when dropping is not a leak: torn down, adopted (its launcher owns it), or detached
1902    /// (its adopter owns it).
1903    fn drop_warning(&self) -> Option<String> {
1904        if self.torn_down || self.adopted || self.detached {
1905            return None;
1906        }
1907        let vm = self.microvm.as_ref()?;
1908        self.lifecycle.is_live().then(|| {
1909            format!(
1910                "warning: the Sandbox for microvm {id} was dropped in {state} without \
1911                 terminate() or detach(). Nothing was torn down — Drop cannot await, so a \
1912                 teardown here would deadlock inside a runtime. {state} is the state this \
1913                 sandbox last saw, and the platform may have suspended or ended the VM since. A \
1914                 VM that's still live bills until it ends, at its maximumDurationInSeconds \
1915                 ceiling at the latest: terminate it with `microvm terminate {id}`.",
1916                id = vm.id,
1917                state = self.lifecycle,
1918            )
1919        })
1920    }
1921}
1922
1923impl Drop for Sandbox {
1924    fn drop(&mut self) {
1925        if let Some(warning) = self.drop_warning() {
1926            self.control.adapters().warn(&warning);
1927        }
1928    }
1929}
1930
1931/// A fresh per-VM bearer token: 32 bytes from `entropy` as 64 hex characters.
1932///
1933/// The hand-rolled `/dev/urandom` read this once replaced carried a clock-mixing fallback
1934/// for a failed read. An unavailable source refuses the launch instead: minting a bearer
1935/// token from a clock would be worse than not launching.
1936fn mint_agent_token(entropy: &dyn crate::entropy::Entropy) -> Result<String, Error> {
1937    let mut bytes = [0u8; 32];
1938    entropy.fill(&mut bytes)?;
1939    Ok(const_hex::encode(bytes))
1940}
1941
1942#[cfg(test)]
1943mod tests {
1944    use super::*;
1945    use crate::control::fake::{self as fake, Answer, FakeControlPlane, TestClock};
1946    use crate::control::transport::Method;
1947
1948    /// A sandbox over the contract recorder, plus the two handles a test asserts through.
1949    ///
1950    /// The recorder is T-W2-4's, deliberately: its answers are literal JSON in the service
1951    /// model's spelling rather than values serialized from this crate's types, so a member
1952    /// this lane misreads cannot be misread identically by the fake.
1953    fn planted() -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
1954        let recorder = Arc::new(FakeControlPlane::new());
1955        let clock = Arc::new(TestClock::new());
1956        let plane = crate::testing::control_plane(
1957            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
1958            Region::UsEast1,
1959            Arc::clone(&clock) as Arc<dyn crate::control::Clock>,
1960        );
1961        // A daemon that answers health, because a launch waits for one (#254).
1962        let sandbox = Sandbox::with_control_plane(plane)
1963            .with_session_backend(crate::testing::HealthyDaemon::new());
1964        (sandbox, recorder, clock)
1965    }
1966
1967    /// Suspend, resume and terminate wait five minutes at five-second polls, with no stall
1968    /// probe: core's lifecycle wait, not the image build's 45-minute default (#266).
1969    #[test]
1970    fn the_suspend_resume_and_terminate_waits_are_cores_lifecycle_wait() {
1971        let (sandbox, _, _) = planted();
1972        let wait = sandbox.lifecycle_wait();
1973        assert_eq!(
1974            (wait.timeout, wait.poll_interval, wait.stall_grace),
1975            (
1976                DEFAULT_LIFECYCLE_TIMEOUT,
1977                LIFECYCLE_POLL_INTERVAL,
1978                Duration::MAX
1979            )
1980        );
1981    }
1982
1983    /// Queues everything a launch to RUNNING needs.
1984    fn answer_launch(recorder: &FakeControlPlane) {
1985        recorder
1986            .answer(
1987                "RunMicrovm",
1988                Answer::ok(fake::microvm_response("PENDING", None)),
1989            )
1990            .answer(
1991                "GetMicrovm",
1992                Answer::ok(fake::microvm_response("RUNNING", None)),
1993            )
1994            .answer(
1995                "CreateMicrovmAuthToken",
1996                Answer::ok(fake::auth_token_response("proxy-token")),
1997            );
1998    }
1999
2000    #[tokio::test]
2001    async fn sandbox_launch_polls_at_one_second_then_backs_off() {
2002        for pending_polls in 0..=6 {
2003            let (mut sandbox, recorder, clock) = planted();
2004            recorder.answer(
2005                "RunMicrovm",
2006                Answer::ok(fake::microvm_response("PENDING", None)),
2007            );
2008            for _ in 0..pending_polls {
2009                recorder.answer(
2010                    "GetMicrovm",
2011                    Answer::ok(fake::microvm_response("PENDING", None)),
2012                );
2013            }
2014            recorder
2015                .answer(
2016                    "GetMicrovm",
2017                    Answer::ok(fake::microvm_response("RUNNING", None)),
2018                )
2019                .answer(
2020                    "CreateMicrovmAuthToken",
2021                    Answer::ok(fake::auth_token_response("proxy-token")),
2022                );
2023            sandbox
2024                .run(RunRequest::new().with_image("arn:image"))
2025                .await
2026                .expect("ready");
2027            let expected_seconds = [0, 1, 2, 3, 8, 13, 18][pending_polls];
2028            assert_eq!(clock.now(), Duration::from_secs(expected_seconds));
2029            assert_eq!(recorder.call_count("GetMicrovm"), pending_polls + 1);
2030            assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
2031            sandbox.detach().expect("hand the scripted VM off quietly");
2032        }
2033
2034        // The public control-plane wait still honors a fixed interval.
2035        let (sandbox, recorder, clock) = planted();
2036        recorder
2037            .answer(
2038                "GetMicrovm",
2039                Answer::ok(fake::microvm_response("PENDING", None)),
2040            )
2041            .answer(
2042                "GetMicrovm",
2043                Answer::ok(fake::microvm_response("RUNNING", None)),
2044            );
2045        sandbox
2046            .control
2047            .wait_for_launch("mvm-abc123", WaitOpts::for_launch())
2048            .await
2049            .expect("ready");
2050        assert_eq!(clock.now(), Duration::from_secs(5));
2051
2052        // Only client-token adoption can resume a suspended launch.
2053        let (mut sandbox, recorder, _) = planted();
2054        recorder
2055            .answer(
2056                "RunMicrovm",
2057                Answer::ok(fake::microvm_response("PENDING", None)),
2058            )
2059            .answer(
2060                "GetMicrovm",
2061                Answer::ok(fake::microvm_response("SUSPENDED", None)),
2062            );
2063        let error = sandbox
2064            .run(RunRequest::new().with_image("arn:image"))
2065            .await
2066            .expect_err("a fresh launch fails fast");
2067        assert_eq!(error.kind(), ErrorKind::LaunchDied);
2068        assert_eq!(recorder.call_count("ResumeMicrovm"), 0);
2069        sandbox.detach().expect("hand the scripted VM off quietly");
2070    }
2071
2072    #[tokio::test]
2073    async fn vpc_egress_configuration_survives_the_sandbox_launch() {
2074        let (mut sandbox, recorder, _) = planted();
2075        answer_launch(&recorder);
2076        let arn = "arn:aws:lambda:us-east-1:123456789012:network-connector:isolated-vpc";
2077        let request = RunRequest::new()
2078            .with_image("arn:image")
2079            .with_egress_network_connector(arn);
2080        assert_eq!(
2081            request.egress_posture(),
2082            crate::control::EgressPosture::Unsealed
2083        );
2084        sandbox.run(request).await.expect("launch");
2085        let body = recorder.first_body("RunMicrovm");
2086        assert_eq!(body["egressNetworkConnectors"], serde_json::json!([arn]));
2087    }
2088
2089    /// **A sandbox's session reads the plane's clock.** Its exec ids carry the plane's wall
2090    /// reading, so the lifecycle and the session it hands out share one time source.
2091    ///
2092    /// **Falsification**: drop `with_clock(self.control.shared_clock())` from `build_session`
2093    /// and the session takes the adapters' clock, whose wall reading is another instant.
2094    #[tokio::test]
2095    async fn a_sandbox_session_reads_the_planes_clock() {
2096        let (mut sandbox, recorder, clock) = planted();
2097        answer_launch(&recorder);
2098        let session = sandbox
2099            .run(RunRequest::new().with_image("arn:image"))
2100            .await
2101            .expect("the launch reaches RUNNING");
2102        let pinned = Duration::from_secs(1_767_225_600) + Duration::from_nanos(987_654_321);
2103        clock.set_unix_now(pinned);
2104        let id = session.mint_exec_id();
2105        let value =
2106            u64::from_str_radix(id.strip_prefix("x-").expect("the x- shape"), 16).expect("hex");
2107        let low_bits = (1_u64 << 40) - 1;
2108        assert_eq!(
2109            value & low_bits,
2110            (pinned.as_nanos() as u64) & low_bits,
2111            "{id} wasn't minted from the plane's clock"
2112        );
2113    }
2114
2115    /// **`ensure_image` builds its STS and S3 client through the plane's adapters**, so a
2116    /// plane over test adapters never reaches a real credential chain.
2117    ///
2118    /// **Falsification**: build `SignedBuildServices` inline again, and the refusal (or, with
2119    /// credentials in the environment, the call) is the real chain's rather than the
2120    /// adapters'.
2121    #[tokio::test]
2122    async fn ensure_image_builds_its_services_through_the_planes_adapters() {
2123        let (mut sandbox, recorder, _) = planted();
2124        let dockerfile = crate::control::artifact::wrap_dockerfile(
2125            "FROM python:3.12-slim\nWORKDIR /app\n",
2126            &crate::control::artifact::WrapOptions::default(),
2127        )
2128        .expect("a wrappable Dockerfile");
2129        let request = crate::control::EnsureImageRequest::new(
2130            "task",
2131            crate::testing::aarch64_daemon(b"daemon"),
2132            dockerfile,
2133            "artifact-bucket",
2134            "arn:aws:iam::123456789012:role/build",
2135        );
2136        let error = sandbox
2137            .ensure_image(request)
2138            .await
2139            .expect_err("the test adapters build no services");
2140        assert_eq!(error.kind(), ErrorKind::Credentials, "{error}");
2141        assert!(
2142            error
2143                .to_string()
2144                .contains("the test adapters build no STS or S3 client for us-east-1"),
2145            "{error}"
2146        );
2147        assert!(
2148            recorder.calls().is_empty(),
2149            "no control-plane call came first"
2150        );
2151    }
2152
2153    /// **A launch draws its agent token, identity seeds and client token from the plane's
2154    /// entropy**, in that order, so the one source a caller or a test swaps in decides all
2155    /// three.
2156    ///
2157    /// **Falsification**: mint any of the three from `OsEntropy` instead of
2158    /// `self.control.entropy()` and its assertion below reads a value the scripted source
2159    /// never produced.
2160    #[tokio::test]
2161    async fn a_launch_draws_every_random_value_from_the_planes_entropy() {
2162        use crate::entropy::testing::SequenceEntropy;
2163        use base64::Engine as _;
2164
2165        let recorder = Arc::new(FakeControlPlane::new());
2166        let entropy = Arc::new(SequenceEntropy::new());
2167        let plane = crate::testing::control_plane(
2168            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
2169            Region::UsEast1,
2170            Arc::new(TestClock::new()),
2171        )
2172        .with_entropy(Arc::clone(&entropy) as Arc<dyn crate::entropy::Entropy>);
2173        let mut sandbox = Sandbox::with_control_plane(plane)
2174            .with_session_backend(crate::testing::HealthyDaemon::new());
2175        answer_launch(&recorder);
2176        let session = sandbox
2177            .run(RunRequest::new().with_image("arn:image").with_identity())
2178            .await
2179            .expect("the launch reaches RUNNING");
2180
2181        assert_eq!(
2182            session.agent_token(),
2183            const_hex::encode(SequenceEntropy::draw(1, 32)),
2184            "the agent token"
2185        );
2186        let body = recorder.first_body("RunMicrovm");
2187        let payload: serde_json::Value =
2188            serde_json::from_str(body["runHookPayload"].as_str().expect("a string payload"))
2189                .expect("the payload is JSON");
2190        assert_eq!(
2191            payload[protocol::identity::SEED_KEY],
2192            base64::engine::general_purpose::STANDARD
2193                .encode(SequenceEntropy::draw(2, protocol::identity::SEED_BYTES)),
2194            "the VM seed"
2195        );
2196        let client_token = body["clientToken"].as_str().expect("a client token");
2197        assert!(
2198            client_token.ends_with(&const_hex::encode(SequenceEntropy::draw(4, 8))),
2199            "the client token's nonce: {client_token}"
2200        );
2201        assert_eq!(
2202            entropy.calls(),
2203            4,
2204            "one draw per value, the host seed included"
2205        );
2206        sandbox.detach().expect("hand the scripted VM off quietly");
2207    }
2208
2209    /// An unavailable entropy source refuses the launch before anything reaches the plane.
2210    #[tokio::test]
2211    async fn an_unavailable_entropy_source_refuses_the_launch() {
2212        use crate::entropy::testing::SequenceEntropy;
2213
2214        let recorder = Arc::new(FakeControlPlane::new());
2215        let plane = crate::testing::control_plane(
2216            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
2217            Region::UsEast1,
2218            Arc::new(TestClock::new()),
2219        )
2220        .with_entropy(Arc::new(SequenceEntropy::unavailable()));
2221        let mut sandbox = Sandbox::with_control_plane(plane)
2222            .with_session_backend(crate::testing::HealthyDaemon::new());
2223        answer_launch(&recorder);
2224        let err = sandbox
2225            .run(RunRequest::new().with_image("arn:image"))
2226            .await
2227            .expect_err("no pool, no bearer token");
2228        assert_eq!(err.kind(), ErrorKind::Unexpected, "{err}");
2229        assert_eq!(recorder.call_count("RunMicrovm"), 0);
2230    }
2231
2232    // ── a launch waits for the daemon (#254) ──────────────────────────────────
2233
2234    /// A sandbox whose daemon answers health from `replies`, over a scripted plane that
2235    /// answers a launch to RUNNING.
2236    fn launching_to(
2237        replies: Vec<crate::testing::Reply>,
2238    ) -> (
2239        Sandbox,
2240        Arc<FakeControlPlane>,
2241        Arc<crate::testing::Recorder>,
2242    ) {
2243        let recorder = Arc::new(FakeControlPlane::new());
2244        let plane = crate::testing::control_plane(
2245            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
2246            Region::UsEast1,
2247            Arc::new(TestClock::new()),
2248        );
2249        let daemon = crate::testing::Recorder::with(replies);
2250        let sandbox = Sandbox::with_control_plane(plane).with_session_backend(daemon.clone());
2251        answer_launch(&recorder);
2252        (sandbox, recorder, daemon)
2253    }
2254
2255    /// Not yet bootstrapped, then bootstrapped: the two health answers a launch waits through.
2256    fn not_ready_then_ready() -> Vec<crate::testing::Reply> {
2257        vec![
2258            crate::testing::Reply::Body(503, b"not bootstrapped".to_vec()),
2259            crate::testing::Reply::ok(crate::testing::health_body(true)),
2260        ]
2261    }
2262
2263    /// The paths a scripted daemon was asked for, in order.
2264    fn daemon_paths(daemon: &crate::testing::Recorder) -> Vec<String> {
2265        daemon
2266            .requests()
2267            .iter()
2268            .map(|request| format!("{} {}", request.method, request.path))
2269            .collect()
2270    }
2271
2272    /// **`run` returns once the daemon answers, not at RUNNING (#254).** The plane reports
2273    /// RUNNING and the daemon answers 503 and then 200 bootstrapped: `run` hands back the
2274    /// session after the second poll, as the CLI's `run` and `AgentVm.launch` did on their own.
2275    ///
2276    /// **Falsification**: drop the `wait_until_ready` call from `Sandbox::wait_until_running`
2277    /// and `run` returns at RUNNING having asked the daemon nothing.
2278    #[tokio::test(start_paused = true)]
2279    async fn a_launch_returns_once_its_daemon_answers() {
2280        let (mut sandbox, _recorder, daemon) = launching_to(not_ready_then_ready());
2281        sandbox
2282            .run(RunRequest::new().with_image("arn:image"))
2283            .await
2284            .expect("the launch reaches RUNNING and its daemon answers");
2285        assert_eq!(
2286            daemon_paths(&daemon),
2287            ["GET /v1/health", "GET /v1/health"],
2288            "one poll refused, one bootstrapped, and nothing after"
2289        );
2290        sandbox.detach().expect("hand the scripted VM off quietly");
2291    }
2292
2293    /// **A launch that didn't wait is finished the same way (#254):** `wait_until_running`
2294    /// after `run(wait = false)` returns once the daemon answers too, and the accepted launch
2295    /// itself asked the daemon nothing.
2296    #[tokio::test(start_paused = true)]
2297    async fn wait_until_running_returns_once_the_daemon_answers() {
2298        let (mut sandbox, _recorder, daemon) = launching_to(not_ready_then_ready());
2299        let mut request = RunRequest::new().with_image("arn:image");
2300        request.wait = false;
2301        sandbox.run(request).await.expect("the launch is accepted");
2302        assert!(
2303            daemon_paths(&daemon).is_empty(),
2304            "an accepted launch doesn't wait"
2305        );
2306        sandbox
2307            .wait_until_running(DEFAULT_RUNNING_TIMEOUT)
2308            .await
2309            .expect("RUNNING, then the daemon answers");
2310        assert_eq!(daemon_paths(&daemon), ["GET /v1/health", "GET /v1/health"]);
2311        sandbox.detach().expect("hand the scripted VM off quietly");
2312    }
2313
2314    /// **A daemon that never answers fails the launch with `ERR_TIMEOUT` (#254),** after the
2315    /// bootstrap wait, rather than the first exec failing later. The VM did reach RUNNING, so
2316    /// the lifecycle says so and the token counts as installed (STATE-2).
2317    #[tokio::test(start_paused = true)]
2318    async fn a_launch_whose_daemon_never_answers_times_out_running() {
2319        let never = (0..128)
2320            .map(|_| crate::testing::Reply::Body(503, b"not bootstrapped".to_vec()))
2321            .collect();
2322        let (mut sandbox, _recorder, daemon) = launching_to(never);
2323        let error = sandbox
2324            .run(RunRequest::new().with_image("arn:image"))
2325            .await
2326            .expect_err("the daemon never answered");
2327        assert_eq!(error.kind(), ErrorKind::Timeout, "{error}");
2328        assert!(daemon.requests().len() > 1, "it kept asking");
2329        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
2330        assert!(sandbox.token_installed());
2331        sandbox.detach().expect("hand the scripted VM off quietly");
2332    }
2333
2334    // ── a launch by bare image name (#253) ───────────────────────────────────
2335
2336    /// The ARN the fake's listing gives `wanted-image`.
2337    const WANTED_ARN: &str = "arn:aws:lambda:us-east-1:123456789012:microvm-image:wanted-image";
2338
2339    /// A listing that holds `wanted-image` beside a name it's a prefix of.
2340    fn answer_listing(recorder: &FakeControlPlane) {
2341        recorder.answer(
2342            "ListMicrovmImages",
2343            Answer::ok(fake::list_images_response(
2344                &["wanted-image-old", "wanted-image"],
2345                None,
2346            )),
2347        );
2348    }
2349
2350    /// **A launch by bare image name sends the listed ARN**, resolved before `RunMicrovm`, as
2351    /// `run --image NAME` did. Every surface's launch is this `run`, and the SDKs used to send
2352    /// the name verbatim, which the service answers with HTTP 400 "Malformed ARN".
2353    ///
2354    /// **Falsification**: drop the `resolve_image_arn` call from `Sandbox::run` and the calls
2355    /// start at `RunMicrovm`, whose body carries `wanted-image`.
2356    #[tokio::test]
2357    async fn a_launch_by_bare_image_name_sends_the_listed_arn() {
2358        let (mut sandbox, recorder, _) = planted();
2359        answer_listing(&recorder);
2360        answer_launch(&recorder);
2361        sandbox
2362            .run(RunRequest::new().with_image("wanted-image"))
2363            .await
2364            .expect("the launch reaches RUNNING");
2365
2366        let operations = recorder.operations();
2367        assert_eq!(
2368            operations.get(..2),
2369            Some(&["ListMicrovmImages", "RunMicrovm"][..]),
2370            "the name is resolved, once, before the launch: {operations:?}"
2371        );
2372        assert_eq!(recorder.call_count("ListMicrovmImages"), 1);
2373        assert_eq!(
2374            recorder.first_body("RunMicrovm")["imageIdentifier"],
2375            WANTED_ARN,
2376            "the launch carries the exact match's ARN, never the name"
2377        );
2378        sandbox.detach().expect("hand the scripted VM off quietly");
2379    }
2380
2381    /// **An image ARN launches with no listing call**, and is the ARN the sandbox records.
2382    #[tokio::test]
2383    async fn a_launch_by_image_arn_makes_no_listing_call() {
2384        let (mut sandbox, recorder, _) = planted();
2385        answer_launch(&recorder);
2386        sandbox
2387            .run(RunRequest::new().with_image(WANTED_ARN))
2388            .await
2389            .expect("the launch reaches RUNNING");
2390
2391        assert_eq!(recorder.call_count("ListMicrovmImages"), 0);
2392        assert_eq!(recorder.operations().first(), Some(&"RunMicrovm"));
2393        assert_eq!(
2394            recorder.first_body("RunMicrovm")["imageIdentifier"],
2395            WANTED_ARN
2396        );
2397        assert_eq!(sandbox.launch_image_arn(), Some(WANTED_ARN));
2398        sandbox.detach().expect("hand the scripted VM off quietly");
2399    }
2400
2401    /// **The resolved ARN is recorded before `RunMicrovm`, so a launch the service refuses
2402    /// still names the image it asked for.** The CLI's failure envelope reads it from here:
2403    /// `microvm()` holds only what an accepted launch answered.
2404    ///
2405    /// **Falsification**: drop the `launch_image_arn` assignment from `Sandbox::run` and the
2406    /// accessor reads `None` after the refusal.
2407    #[tokio::test]
2408    async fn a_refused_launch_by_name_still_records_the_resolved_arn() {
2409        let (mut sandbox, recorder, _) = planted();
2410        answer_listing(&recorder);
2411        recorder.answer("RunMicrovm", Answer::failure(400, "scripted refusal"));
2412        sandbox
2413            .run(RunRequest::new().with_image("wanted-image"))
2414            .await
2415            .expect_err("the service refused the launch");
2416
2417        assert_eq!(
2418            sandbox.launch_image_arn(),
2419            Some(WANTED_ARN),
2420            "the ARN the refused launch asked for"
2421        );
2422        assert!(sandbox.microvm().is_none(), "no launch was accepted");
2423        assert_eq!(recorder.call_count("RunMicrovm"), 1);
2424    }
2425
2426    /// **A name no image carries is `ERR_PRECONDITION` before any launch, and the sandbox is
2427    /// left as it was**: nothing recorded (STATE-1 counts only an accepted launch), so the
2428    /// same sandbox launches once the caller passes an image that exists.
2429    #[tokio::test]
2430    async fn an_unknown_image_name_is_refused_before_the_launch_and_the_sandbox_still_runs() {
2431        let (mut sandbox, recorder, _) = planted();
2432        recorder.answer(
2433            "ListMicrovmImages",
2434            Answer::ok(fake::list_images_response(&[], None)),
2435        );
2436        let error = sandbox
2437            .run(RunRequest::new().with_image("no-such-image"))
2438            .await
2439            .expect_err("nothing to launch from");
2440        assert_eq!(error.code(), "ERR_PRECONDITION");
2441        assert!(error.to_string().contains("no-such-image"), "{error}");
2442        assert_eq!(recorder.call_count("RunMicrovm"), 0);
2443        assert_eq!(sandbox.launch_image_arn(), None);
2444        assert!(!sandbox.image_exists(), "STATE-1: no launch was accepted");
2445        assert!(sandbox.microvm().is_none());
2446        assert_eq!(sandbox.bootstrap_count(), 0);
2447
2448        answer_launch(&recorder);
2449        sandbox
2450            .run(RunRequest::new().with_image(WANTED_ARN))
2451            .await
2452            .expect("a failed resolution doesn't use up the sandbox's one launch");
2453        assert_eq!(sandbox.bootstrap_count(), 1);
2454        sandbox.detach().expect("hand the scripted VM off quietly");
2455    }
2456
2457    /// **A launch this client refuses costs no call, a bare name included**: the local
2458    /// refusals come before the listing a name costs.
2459    ///
2460    /// **Falsification**: drop the `launch_connectors` call from `Sandbox::run` and the
2461    /// out-of-range duration is refused by `run_microvm` only after the listing went out.
2462    #[tokio::test]
2463    async fn a_launch_refused_locally_makes_no_listing_call_for_a_name() {
2464        let (mut sandbox, recorder, _) = planted();
2465        answer_listing(&recorder);
2466        let mut request = RunRequest::new().with_image("wanted-image");
2467        request.max_duration_sec = 0;
2468        let error = sandbox
2469            .run(request)
2470            .await
2471            .expect_err("a zero maximum duration is refused locally");
2472        assert_eq!(error.kind(), ErrorKind::InvalidArg, "{error}");
2473        assert!(
2474            recorder.calls().is_empty(),
2475            "the refusal came after a call: {:?}",
2476            recorder.operations()
2477        );
2478        assert_eq!(sandbox.launch_image_arn(), None);
2479    }
2480
2481    /// **BIND-12: the launched session carries its request's posture**, the value
2482    /// `egress_posture_for` answers for the same options and the CLI envelope reports
2483    /// (the CLI's `guards/run.rs` holds that half). Each of the four launchable shapes.
2484    ///
2485    /// **Falsification** — 2026-09-24. Build the session without `with_egress_posture` and
2486    /// the `open` and `best-effort` rows read `unsealed`; restored.
2487    #[tokio::test]
2488    async fn a_launched_session_reports_its_requests_posture() {
2489        use crate::control::EgressPosture;
2490        let arn = "arn:aws:lambda:us-east-1:123456789012:network-connector:isolated-vpc";
2491        let rows = [
2492            (RunRequest::new(), EgressPosture::Unsealed),
2493            (RunRequest::new().with_egress(), EgressPosture::Open),
2494            (
2495                RunRequest::new().with_deny_egress(),
2496                EgressPosture::BestEffort,
2497            ),
2498            (
2499                RunRequest::new().with_egress_network_connector(arn),
2500                EgressPosture::Unsealed,
2501            ),
2502        ];
2503        for (request, expected) in rows {
2504            let answered = crate::control::egress_posture_for(
2505                request.egress,
2506                &request.egress_network_connectors,
2507                request.deny_egress,
2508                Some(&Region::UsEast1),
2509            )
2510            .expect("a launchable request");
2511            assert_eq!(answered, expected);
2512            let (mut sandbox, recorder, _) = planted();
2513            answer_launch(&recorder);
2514            let session = sandbox
2515                .run(request.with_image("arn:image"))
2516                .await
2517                .expect("the launch reaches RUNNING");
2518            assert_eq!(session.egress_posture(), expected, "BIND-12");
2519            assert_eq!(sandbox.egress_posture(), expected);
2520            sandbox.detach().expect("hand the scripted VM off quietly");
2521        }
2522    }
2523
2524    /// **BIND-12: a session that does not hold its launch options reports `unsealed`**, the
2525    /// weakest true claim, whatever the VM was launched with: an adopted VM and a session
2526    /// attached directly both lack the request.
2527    #[tokio::test]
2528    async fn a_session_without_its_launch_options_reports_unsealed() {
2529        use crate::control::EgressPosture;
2530        let (sandbox, _recorder, _clock) = adopted_in("RUNNING").await;
2531        assert_eq!(
2532            sandbox.session().expect("RUNNING").egress_posture(),
2533            EgressPosture::Unsealed
2534        );
2535        assert_eq!(sandbox.egress_posture(), EgressPosture::Unsealed);
2536        let direct = Session::builder(ADOPT_ENDPOINT, ADOPT_TOKEN)
2537            .build_with(&crate::testing::TestAdapters::new())
2538            .expect("a direct session");
2539        assert_eq!(direct.egress_posture(), EgressPosture::Unsealed);
2540    }
2541
2542    /// A launched sandbox in RUNNING, which is where four of the twelve keys start.
2543    async fn launched() -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
2544        let (mut sandbox, recorder, clock) = planted();
2545        answer_launch(&recorder);
2546        sandbox
2547            .run(RunRequest::new().with_image("arn:image"))
2548            .await
2549            .expect("the launch reaches RUNNING");
2550        (sandbox, recorder, clock)
2551    }
2552
2553    /// **A dropped live sandbox warns through the plane's adapters**, not a stream of its
2554    /// own, so the driving adapter decides where the warning goes (ARCH-7). The warning names
2555    /// the state as the one the sandbox last saw, since the platform can suspend or end the VM
2556    /// without telling it, and says only that a VM still live bills.
2557    ///
2558    /// **Falsification**: write the warning straight to stderr in `Drop` and the recorded
2559    /// list comes back empty (and the crate's `clippy.toml` refuses `std::io::stderr`).
2560    #[tokio::test]
2561    async fn a_dropped_live_sandbox_warns_through_the_planes_adapters() {
2562        let recorder = Arc::new(FakeControlPlane::new());
2563        let clock = Arc::new(TestClock::new());
2564        let adapters = Arc::new(crate::testing::TestAdapters::new());
2565        let plane = crate::control::ControlPlane::from_ports(
2566            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
2567            Region::UsEast1,
2568            Arc::clone(&clock) as Arc<dyn crate::control::Clock>,
2569            Arc::new(crate::testing::SequenceEntropy::new()),
2570            Arc::clone(&adapters) as Arc<dyn crate::adapters::Adapters>,
2571        );
2572        let mut sandbox = Sandbox::with_control_plane(plane)
2573            .with_session_backend(crate::testing::HealthyDaemon::new());
2574        answer_launch(&recorder);
2575        sandbox
2576            .run(RunRequest::new().with_image("arn:image"))
2577            .await
2578            .expect("the launch reaches RUNNING");
2579        let id = sandbox.microvm().expect("launched").id.clone();
2580        drop(sandbox);
2581        let warnings = adapters.warnings();
2582        assert_eq!(warnings.len(), 1, "{warnings:?}");
2583        assert!(warnings[0].contains(&id), "{warnings:?}");
2584        assert!(
2585            warnings[0].contains("RUNNING is the state this sandbox last saw")
2586                && warnings[0].contains("A VM that's still live bills"),
2587            "{warnings:?}"
2588        );
2589    }
2590
2591    /// **Detach hands off, and nothing warns or moves afterwards.** A launched sandbox
2592    /// warns on drop; once detached it returns what an adopter needs (with the token kept
2593    /// out of `Debug`), stops warning, makes no further control-plane call, and refuses every
2594    /// transition — including `terminate`, which reports the refusal instead of raising.
2595    ///
2596    /// **Falsification** — 2026-09-24. Leave `detached` out of `drop_warning`'s early
2597    /// return and the "no warning after detach" assertion goes red; drop the
2598    /// `refuse_detached` guard from `suspend` and the zero-calls assertion goes red (the
2599    /// suspend reaches `SuspendMicrovm`). Both restored.
2600    #[tokio::test]
2601    async fn a_detached_sandbox_hands_off_its_vm_and_stays_quiet() {
2602        let (mut sandbox, recorder, _clock) = launched().await;
2603        assert!(
2604            sandbox.drop_warning().is_some(),
2605            "a launched, live VM warns on drop"
2606        );
2607        let token = sandbox
2608            .session()
2609            .expect("launched")
2610            .agent_token()
2611            .to_string();
2612        let vm = sandbox.microvm().expect("launched").clone();
2613
2614        let detached = sandbox.detach().expect("a RUNNING VM detaches");
2615        assert_eq!(detached.microvm_id, vm.id);
2616        assert_eq!(detached.endpoint, vm.endpoint);
2617        assert_eq!(detached.agent_token(), token);
2618        assert_eq!(detached.region, Region::UsEast1);
2619        let printed = format!("{detached:?} {sandbox:?}");
2620        assert!(!printed.contains(&token), "{printed}");
2621        assert!(printed.contains("detached: true"), "{printed}");
2622
2623        assert!(sandbox.detached());
2624        assert!(
2625            sandbox.drop_warning().is_none(),
2626            "detached is not abandoned"
2627        );
2628        assert!(
2629            sandbox.session().is_none(),
2630            "the session went to the adopter"
2631        );
2632
2633        let before = recorder.calls().len();
2634        for error in [
2635            sandbox.suspend().await.expect_err("detached"),
2636            sandbox.resume().await.map(|_| ()).expect_err("detached"),
2637            sandbox
2638                .run(RunRequest::new().with_image("arn:image"))
2639                .await
2640                .map(|_| ())
2641                .expect_err("detached"),
2642            sandbox
2643                .wait_until_running(Duration::from_secs(1))
2644                .await
2645                .map(|_| ())
2646                .expect_err("detached"),
2647            sandbox.detach().map(|_| ()).expect_err("already detached"),
2648        ] {
2649            assert_eq!(error.kind(), ErrorKind::Precondition, "{error}");
2650            assert!(error.to_string().contains("detached"), "{error}");
2651            assert!(!error.to_string().contains(&token), "{error}");
2652        }
2653        let report = sandbox.terminate(TeardownOpts::default()).await;
2654        assert!(!report.terminate_accepted);
2655        assert!(report.failures[0].contains("detached"), "{report:?}");
2656        assert_eq!(recorder.calls().len(), before, "detached makes no AWS call");
2657        assert!(
2658            sandbox.drop_warning().is_none(),
2659            "a refused terminate is still quiet"
2660        );
2661    }
2662
2663    /// Detach needs a live VM: nothing launched, or already torn down, is refused.
2664    #[tokio::test]
2665    async fn detach_refuses_without_a_live_vm() {
2666        let (mut unlaunched, _recorder, _clock) = planted();
2667        let error = unlaunched.detach().expect_err("nothing launched");
2668        assert_eq!(error.kind(), ErrorKind::Precondition);
2669        assert!(!unlaunched.detached());
2670
2671        let (mut sandbox, recorder, _clock) = launched().await;
2672        recorder
2673            .answer("TerminateMicrovm", Answer::ok("{}"))
2674            .answer(
2675                "GetMicrovm",
2676                Answer::ok(fake::microvm_response("TERMINATED", None)),
2677            );
2678        sandbox.terminate(TeardownOpts::default()).await;
2679        let error = sandbox.detach().expect_err("torn down");
2680        assert_eq!(error.kind(), ErrorKind::Precondition, "{error}");
2681        assert!(!sandbox.detached());
2682    }
2683
2684    /// Drives a launched sandbox to SUSPENDED, which is where resume starts.
2685    ///
2686    /// Both `GetMicrovm` answers are queued **before** the launch rather than one before
2687    /// each wait, and that is not a style choice. The recorder repeats its last queued
2688    /// answer, so a queue left at `[RUNNING]` after the launch and then appended to becomes
2689    /// `[RUNNING, SUSPENDED]` — the suspend wait pops the stale RUNNING, sleeps a poll
2690    /// interval, and the fake's `sleep` **advances the clock**. That five seconds is
2691    /// invisible until a test reads the clock, which then counts the fake's poll interval as
2692    /// time the VM spent suspended. Queueing both up front means every wait matches on its
2693    /// first poll and no test clock moves except when a test moves it.
2694    async fn suspended_with_window(
2695        suspended_sec: u32,
2696    ) -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
2697        let (mut sandbox, recorder, clock) = planted();
2698        recorder
2699            .answer(
2700                "RunMicrovm",
2701                Answer::ok(fake::microvm_response("PENDING", None)),
2702            )
2703            .answer(
2704                "GetMicrovm",
2705                Answer::ok(fake::microvm_response("RUNNING", None)),
2706            )
2707            .answer(
2708                "GetMicrovm",
2709                Answer::ok(fake::microvm_response("SUSPENDED", None)),
2710            )
2711            .answer(
2712                "CreateMicrovmAuthToken",
2713                Answer::ok(fake::auth_token_response("proxy-token")),
2714            )
2715            .answer("SuspendMicrovm", Answer::ok(fake::empty_response()));
2716
2717        sandbox
2718            .run(
2719                RunRequest::new()
2720                    .with_image("arn:image")
2721                    .with_suspended_sec(suspended_sec),
2722            )
2723            .await
2724            .expect("launches");
2725        sandbox.suspend().await.expect("suspends");
2726        assert_eq!(
2727            clock.now(),
2728            Duration::ZERO,
2729            "no wait may have slept, or a test that reads the clock is measuring the fake's \
2730             poll interval as well as the elapsed suspension"
2731        );
2732        (sandbox, recorder, clock)
2733    }
2734
2735    /// A suspended sandbox at the default ten-minute window.
2736    async fn suspended() -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
2737        suspended_with_window(600).await
2738    }
2739
2740    // ── adopt (#196) ─────────────────────────────────────────────────────────
2741
2742    /// A canary agent token, so a test can assert it appears in no `Debug` or error.
2743    const ADOPT_TOKEN: &str = "adopt-canary-token-9f1c";
2744    const ADOPT_ENDPOINT: &str = "https://mvm-abc123.microvm.us-east-1.amazonaws.com";
2745
2746    /// A plane over the recorder, whose `GetMicrovm` answers the caller queues.
2747    fn adopt_plane() -> (ControlPlane, Arc<FakeControlPlane>, Arc<TestClock>) {
2748        let recorder = Arc::new(FakeControlPlane::new());
2749        let clock = Arc::new(TestClock::new());
2750        let plane = crate::testing::control_plane(
2751            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
2752            Region::UsEast1,
2753            Arc::clone(&clock) as Arc<dyn crate::control::Clock>,
2754        );
2755        (plane, recorder, clock)
2756    }
2757
2758    async fn adopted_in(state: &str) -> (Sandbox, Arc<FakeControlPlane>, Arc<TestClock>) {
2759        let (plane, recorder, clock) = adopt_plane();
2760        recorder.answer(
2761            "GetMicrovm",
2762            Answer::ok(fake::microvm_response(state, None)),
2763        );
2764        let sandbox = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, ADOPT_TOKEN)
2765            .await
2766            .expect("adopts");
2767        (sandbox, recorder, clock)
2768    }
2769
2770    /// **An adopted sandbox feeds its keepalive.** The idle window is the one `GetMicrovm`
2771    /// reports, and the lifecycle watch starts at the adopted state, so a keepalive on an
2772    /// adopted session paces against the real policy and ends when that sandbox suspends.
2773    ///
2774    /// **Falsification** — 2026-09-24. Assign `sandbox.lifecycle` directly instead of
2775    /// through `set_lifecycle`, or drop the `idle_window` line, and this goes red; restored.
2776    #[tokio::test]
2777    async fn an_adopted_sandbox_reports_the_services_idle_window_and_watches_its_lifecycle() {
2778        let (sandbox, _recorder, _clock) = adopted_in("RUNNING").await;
2779        assert_eq!(sandbox.idle_window(), Some(Duration::from_secs(1800)));
2780        assert_eq!(*sandbox.watch_lifecycle().borrow(), Lifecycle::Running);
2781    }
2782
2783    /// Every service state has a lifecycle, and nothing else parses.
2784    #[test]
2785    fn every_service_state_maps_onto_one_lifecycle() {
2786        for state in crate::constants::MICROVM_STATES {
2787            let lifecycle = Lifecycle::from_service(state).expect("a known state");
2788            assert_eq!(lifecycle.as_str(), state);
2789        }
2790        assert_eq!(Lifecycle::from_service("Running"), None);
2791    }
2792
2793    /// **STATE-3 for an adopted VM.** The lifecycle is the service's, the bootstrap is
2794    /// counted once, and `run` is refused before any wire call, so no run-hook payload is
2795    /// ever sent.
2796    ///
2797    /// **Falsification** — 2026-09-24. Leave the adopted lifecycle at PENDING instead of
2798    /// reading it from `GetMicrovm` and the lifecycle and `token_installed` assertions here
2799    /// go red, as does the suspend in the next test; restored after.
2800    #[tokio::test]
2801    async fn an_adopted_vm_takes_its_lifecycle_from_the_service_and_refuses_run() {
2802        let (mut sandbox, recorder, _) = adopted_in("RUNNING").await;
2803        assert!(sandbox.adopted());
2804        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
2805        assert!(sandbox.token_installed());
2806        assert_eq!(sandbox.bootstrap_count(), 1);
2807        assert!(sandbox.image_exists());
2808        let session = sandbox.session().expect("a live VM gets a session");
2809        assert_eq!(session.endpoint(), ADOPT_ENDPOINT);
2810        assert_eq!(session.agent_token(), ADOPT_TOKEN);
2811
2812        let error = sandbox
2813            .run(RunRequest::new().with_image("arn:image"))
2814            .await
2815            .expect_err("an adopted VM was bootstrapped by its own launch");
2816        assert_eq!(error.kind(), ErrorKind::InvalidArg);
2817        assert!(error.to_string().contains("STATE-3"), "{error}");
2818        assert_eq!(recorder.call_count("RunMicrovm"), 0);
2819        assert_eq!(recorder.operations(), vec!["GetMicrovm"]);
2820    }
2821
2822    /// A name resolves to the record's VM and adopts it; a missing name or a record from
2823    /// another region is refused before any AWS call.
2824    ///
2825    /// `Sandbox::from_name` itself builds a production plane, so its refusals are pinned in
2826    /// the prelude's tests. What's here is the resolve it runs first, and the adopt after.
2827    #[tokio::test]
2828    async fn a_name_adopts_its_records_vm_and_foreign_names_are_refused_locally() {
2829        struct One(crate::names::NameRecord);
2830        impl crate::names::NameStore for One {
2831            fn get(&self, name: &str) -> Result<Option<crate::names::NameRecord>, Error> {
2832                Ok((name == self.0.name).then(|| self.0.clone()))
2833            }
2834            fn put(&self, _: &crate::names::NameRecord) -> Result<(), Error> {
2835                unreachable!()
2836            }
2837            fn delete(&self, _: &str) -> Result<bool, Error> {
2838                unreachable!()
2839            }
2840            fn list(&self) -> Result<Vec<crate::names::NameRecord>, Error> {
2841                Ok(vec![self.0.clone()])
2842            }
2843        }
2844        let record = crate::names::NameRecord::new_at(
2845            "ci",
2846            "mvm-abc123",
2847            ADOPT_ENDPOINT,
2848            ADOPT_TOKEN,
2849            "us-west-2",
2850            1_767_225_600,
2851        )
2852        .expect("record");
2853        let store = One(record.clone());
2854        let foreign = crate::names::resolve(&store, "ci", Some(&Region::UsEast1))
2855            .expect_err("registered in another region");
2856        assert_eq!(foreign.kind(), ErrorKind::InvalidArg);
2857        let missing = crate::names::resolve(&store, "nope", None).expect_err("no such name");
2858        assert_eq!(missing.kind(), ErrorKind::Precondition);
2859        assert!(!format!("{foreign} {missing}").contains(ADOPT_TOKEN));
2860
2861        let (plane, recorder, _) = adopt_plane();
2862        recorder.answer(
2863            "GetMicrovm",
2864            Answer::ok(fake::microvm_response("RUNNING", None)),
2865        );
2866        let resolved = crate::names::resolve(&store, "ci", Some(&Region::UsWest2)).expect("ok");
2867        let sandbox = Sandbox::adopt_record(plane, resolved)
2868            .await
2869            .expect("adopts");
2870        assert!(sandbox.adopted());
2871        assert_eq!(
2872            sandbox.microvm().map(|vm| vm.id.as_str()),
2873            Some("mvm-abc123")
2874        );
2875        assert_eq!(
2876            sandbox.session().expect("session").agent_token(),
2877            ADOPT_TOKEN
2878        );
2879        let named = sandbox
2880            .name_record("again")
2881            .expect("an adopted VM can be named");
2882        assert_eq!(
2883            (
2884                named.microvm_id.as_str(),
2885                named.agent_token.as_str(),
2886                named.region.as_str()
2887            ),
2888            ("mvm-abc123", ADOPT_TOKEN, "us-east-1")
2889        );
2890        let unlaunched = Sandbox::with_control_plane(adopt_plane().0);
2891        assert_eq!(
2892            unlaunched
2893                .name_record("x")
2894                .expect_err("nothing to name")
2895                .kind(),
2896            ErrorKind::Precondition
2897        );
2898    }
2899
2900    /// **A record's tunnel identity survives adoption and naming** (#263).
2901    ///
2902    /// `adopt_record` used to drop the pair and `name_record` never wrote it, so a VM named
2903    /// through the SDKs lost what `tunnel --verify-identity` needs to check it. A record with
2904    /// half the pair is refused before any AWS call.
2905    #[tokio::test]
2906    async fn a_records_tunnel_identity_survives_adoption_and_naming() {
2907        let identity = crate::identity::LaunchIdentity::from_seeds([7; 32], [9; 32])
2908            .expect("valid seeds")
2909            .keep();
2910        let mut record = crate::names::NameRecord::new_at(
2911            "ci",
2912            "mvm-abc123",
2913            ADOPT_ENDPOINT,
2914            ADOPT_TOKEN,
2915            "us-east-1",
2916            1_767_225_600,
2917        )
2918        .expect("record");
2919        record.identity_host_seed = Some(identity.host_seed_base64());
2920        record.identity_vm_public_key = Some(identity.vm_public_key_base64());
2921
2922        let (plane, recorder, _) = adopt_plane();
2923        recorder.answer(
2924            "GetMicrovm",
2925            Answer::ok(fake::microvm_response("RUNNING", None)),
2926        );
2927        let sandbox = Sandbox::adopt_record(plane, record.clone())
2928            .await
2929            .expect("adopts");
2930        let kept = sandbox
2931            .tunnel_identity()
2932            .expect("the record's pair is kept");
2933        assert_eq!(kept.host_seed_base64(), identity.host_seed_base64());
2934        assert_eq!(kept.vm_public_key_base64(), identity.vm_public_key_base64());
2935        let named = sandbox.name_record("again").expect("names");
2936        assert_eq!(named.identity_host_seed, record.identity_host_seed);
2937        assert_eq!(named.identity_vm_public_key, record.identity_vm_public_key);
2938
2939        let (plane, recorder, _) = adopt_plane();
2940        let mut torn = record;
2941        torn.identity_vm_public_key = None;
2942        let refused = Sandbox::adopt_record(plane, torn)
2943            .await
2944            .expect_err("half a pair is refused");
2945        assert_eq!(refused.kind(), ErrorKind::InvalidArg);
2946        assert!(refused.to_string().contains("one half"), "{refused}");
2947        assert!(recorder.calls().is_empty(), "refused before any AWS call");
2948    }
2949
2950    /// Suspend, resume, and terminate all work through an adopted handle with the usual
2951    /// guards, and nothing about the launch is re-delivered (STATE-7).
2952    #[tokio::test]
2953    async fn an_adopted_vm_suspends_resumes_and_terminates_through_its_handle() {
2954        let (plane, recorder, _) = adopt_plane();
2955        recorder
2956            .answer(
2957                "GetMicrovm",
2958                Answer::ok(fake::microvm_response("RUNNING", None)),
2959            )
2960            .answer(
2961                "GetMicrovm",
2962                Answer::ok(fake::microvm_response("SUSPENDED", None)),
2963            )
2964            .answer(
2965                "GetMicrovm",
2966                Answer::ok(fake::microvm_response("RUNNING", None)),
2967            )
2968            .answer(
2969                "GetMicrovm",
2970                Answer::ok(fake::microvm_response("TERMINATED", None)),
2971            )
2972            .answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
2973            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
2974            .answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
2975        let mut sandbox = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, ADOPT_TOKEN)
2976            .await
2977            .expect("adopts");
2978
2979        sandbox.suspend().await.expect("suspends from RUNNING");
2980        assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended);
2981        sandbox.resume().await.expect("resumes from SUSPENDED");
2982        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
2983        let report = sandbox
2984            .terminate(TeardownOpts::default().waiting_for_terminated())
2985            .await;
2986        assert!(report.terminate_accepted, "{report:?}");
2987        assert_eq!(sandbox.lifecycle(), Lifecycle::Terminated);
2988        assert!(sandbox.was_terminated());
2989
2990        assert_eq!(recorder.call_count("RunMicrovm"), 0);
2991        assert!(
2992            recorder
2993                .bodies_as_text()
2994                .iter()
2995                .all(|body| !body.contains("runHookPayload") && !body.contains(ADOPT_TOKEN)),
2996            "no launch payload or agent token may reach the control plane"
2997        );
2998        assert_eq!(sandbox.bootstrap_count(), 1, "STATE-3: never above one");
2999    }
3000
3001    /// **STATE-12 for an adopted VM.** An adopted VM this sandbox suspended resumes past the
3002    /// 600 s `idlePolicy` window `GetMicrovm` reported: the resume goes to the service, which
3003    /// doesn't hold an explicit suspend to that window (#597).
3004    #[tokio::test]
3005    async fn an_adopted_vm_resumes_past_the_reported_window_through_the_service() {
3006        let (plane, recorder, clock) = adopt_plane();
3007        recorder
3008            .answer(
3009                "GetMicrovm",
3010                Answer::ok(fake::microvm_response("RUNNING", None)),
3011            )
3012            .answer(
3013                "GetMicrovm",
3014                Answer::ok(fake::microvm_response("SUSPENDED", None)),
3015            )
3016            .answer(
3017                "GetMicrovm",
3018                Answer::ok(fake::microvm_response("RUNNING", None)),
3019            )
3020            .answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
3021            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()));
3022        let mut sandbox = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, ADOPT_TOKEN)
3023            .await
3024            .expect("adopts");
3025        assert_eq!(sandbox.suspended_window(), None, "no request of its own");
3026        sandbox.suspend().await.expect("suspends");
3027
3028        clock.advance(Duration::from_secs(601));
3029        sandbox
3030            .resume()
3031            .await
3032            .expect("past the 600 s window the service reported, the service resumes it");
3033        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
3034        assert_eq!(recorder.call_count("ResumeMicrovm"), 1);
3035    }
3036
3037    /// A VM adopted while already SUSPENDED has no locally observed suspend time, so the
3038    /// resume goes to the service rather than being refused on a guess.
3039    #[tokio::test]
3040    async fn an_adopted_suspended_vm_resumes_through_the_service() {
3041        let (plane, recorder, _) = adopt_plane();
3042        recorder
3043            .answer(
3044                "GetMicrovm",
3045                Answer::ok(fake::microvm_response("SUSPENDED", None)),
3046            )
3047            .answer(
3048                "GetMicrovm",
3049                Answer::ok(fake::microvm_response("RUNNING", None)),
3050            )
3051            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()));
3052        let mut sandbox = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, ADOPT_TOKEN)
3053            .await
3054            .expect("adopts");
3055        assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended);
3056        let session = sandbox
3057            .resume()
3058            .await
3059            .expect("the service answers the resume");
3060        assert_eq!(session.endpoint(), ADOPT_ENDPOINT);
3061        assert_eq!(recorder.call_count("ResumeMicrovm"), 1);
3062    }
3063
3064    /// **STATE-11 for an adopted VM.** A terminated VM is offered neither a resume nor a
3065    /// suspend, and gets no session.
3066    #[tokio::test]
3067    async fn an_adopted_terminated_vm_refuses_every_transition_locally() {
3068        let (mut sandbox, recorder, _) = adopted_in("TERMINATED").await;
3069        assert!(sandbox.was_terminated());
3070        assert!(sandbox.session().is_none());
3071        let resume = sandbox.resume().await.expect_err("STATE-11");
3072        assert!(resume.to_string().contains("STATE-11"), "{resume}");
3073        let suspend = sandbox.suspend().await.expect_err("STATE-5");
3074        assert!(suspend.to_string().contains("STATE-5"), "{suspend}");
3075        assert_eq!(recorder.operations(), vec!["GetMicrovm"]);
3076    }
3077
3078    /// A sandbox adopted in `state` whose plane and session are scripted: `GetMicrovm` answers
3079    /// `state` and then RUNNING, and the daemon answers every health poll.
3080    async fn adopted_with_a_daemon(
3081        state: &str,
3082    ) -> (
3083        Sandbox,
3084        Arc<FakeControlPlane>,
3085        Arc<crate::testing::HealthyDaemon>,
3086    ) {
3087        let recorder = Arc::new(FakeControlPlane::new());
3088        let daemon = crate::testing::HealthyDaemon::new();
3089        let plane = crate::control::ControlPlane::from_ports(
3090            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
3091            Region::UsEast1,
3092            Arc::new(TestClock::new()),
3093            Arc::new(crate::testing::SequenceEntropy::new()),
3094            Arc::new(crate::testing::TestAdapters::new().with_backend(daemon.clone())),
3095        );
3096        recorder
3097            .answer(
3098                "GetMicrovm",
3099                Answer::ok(fake::microvm_response(state, None)),
3100            )
3101            .answer(
3102                "GetMicrovm",
3103                Answer::ok(fake::microvm_response("RUNNING", None)),
3104            )
3105            .answer(
3106                "CreateMicrovmAuthToken",
3107                Answer::ok(fake::auth_token_response("proxy-token")),
3108            );
3109        let sandbox = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, ADOPT_TOKEN)
3110            .await
3111            .expect("adopts");
3112        (sandbox, recorder, daemon)
3113    }
3114
3115    /// **`wait_until_ready` finishes whichever wait is left (#269):** from an adopted PENDING VM,
3116    /// RUNNING and then the daemon; from an adopted RUNNING one, the daemon alone, with no
3117    /// further control-plane read.
3118    ///
3119    /// **Falsification**: drop the RUNNING branch from `Sandbox::wait_until_ready`, and the
3120    /// RUNNING VM is refused as not PENDING.
3121    #[tokio::test]
3122    async fn wait_until_ready_finishes_whichever_wait_is_left() {
3123        let (mut pending, recorder, daemon) = adopted_with_a_daemon("PENDING").await;
3124        pending
3125            .wait_until_ready(Duration::from_secs(60))
3126            .await
3127            .expect("RUNNING, then the daemon");
3128        assert_eq!(pending.lifecycle(), Lifecycle::Running);
3129        assert_eq!(pending.bootstrap_count(), 1);
3130        assert_eq!(daemon.polls(), 1);
3131        assert_eq!(
3132            recorder.call_count("GetMicrovm"),
3133            2,
3134            "the adopt's read and the wait's"
3135        );
3136
3137        let (mut running, recorder, daemon) = adopted_with_a_daemon("RUNNING").await;
3138        running
3139            .wait_until_ready(Duration::from_secs(60))
3140            .await
3141            .expect("the daemon answers");
3142        assert_eq!(daemon.polls(), 1);
3143        assert_eq!(
3144            recorder.call_count("GetMicrovm"),
3145            1,
3146            "RUNNING needs no second read"
3147        );
3148    }
3149
3150    /// A VM that isn't on its way to answering is refused, with no daemon poll.
3151    #[tokio::test]
3152    async fn wait_until_ready_refuses_a_suspended_vm() {
3153        let (mut suspended, _, daemon) = adopted_with_a_daemon("SUSPENDED").await;
3154        let error = suspended
3155            .wait_until_ready(Duration::from_secs(60))
3156            .await
3157            .expect_err("a suspended VM isn't starting");
3158        assert_eq!(error.kind(), ErrorKind::InvalidArg, "{error}");
3159        assert!(error.to_string().contains("SUSPENDED"), "{error}");
3160        assert_eq!(daemon.polls(), 0);
3161    }
3162
3163    /// A VM adopted while PENDING finishes through `wait_until_running`, which counts the
3164    /// bootstrap exactly once and, like a launch, waits for the daemon to answer.
3165    #[tokio::test]
3166    async fn an_adopted_pending_vm_counts_its_bootstrap_once_on_running() {
3167        let recorder = Arc::new(FakeControlPlane::new());
3168        let daemon = crate::testing::HealthyDaemon::new();
3169        let plane = crate::control::ControlPlane::from_ports(
3170            Arc::clone(&recorder) as Arc<dyn crate::control::transport::Transport>,
3171            Region::UsEast1,
3172            Arc::new(TestClock::new()),
3173            Arc::new(crate::testing::SequenceEntropy::new()),
3174            Arc::new(crate::testing::TestAdapters::new().with_backend(daemon.clone())),
3175        );
3176        recorder
3177            .answer(
3178                "GetMicrovm",
3179                Answer::ok(fake::microvm_response("PENDING", None)),
3180            )
3181            .answer(
3182                "GetMicrovm",
3183                Answer::ok(fake::microvm_response("RUNNING", None)),
3184            )
3185            .answer(
3186                "CreateMicrovmAuthToken",
3187                Answer::ok(fake::auth_token_response("proxy-token")),
3188            );
3189        let mut sandbox = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, ADOPT_TOKEN)
3190            .await
3191            .expect("adopts");
3192        assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
3193        assert_eq!(sandbox.bootstrap_count(), 0);
3194        sandbox
3195            .wait_until_running(Duration::from_secs(60))
3196            .await
3197            .expect("reaches RUNNING");
3198        assert_eq!(sandbox.bootstrap_count(), 1);
3199        assert!(sandbox.token_installed());
3200        assert_eq!(
3201            daemon.polls(),
3202            1,
3203            "the daemon answered before the session came back"
3204        );
3205        assert!(
3206            sandbox
3207                .run(RunRequest::new().with_image("arn:image"))
3208                .await
3209                .is_err(),
3210            "still one bootstrap per VM"
3211        );
3212        assert_eq!(recorder.call_count("RunMicrovm"), 0);
3213    }
3214
3215    /// The refusals: an empty token before any call, a mismatched endpoint, and a state
3216    /// this client does not know. None of them, and no `Debug`, prints the token.
3217    ///
3218    /// **Falsification** — 2026-09-24. Remove the endpoint comparison and the mismatch case
3219    /// adopts; remove the empty-token check and that case reaches `GetMicrovm`; print the
3220    /// held token in `Debug` and the canary assertion fails. Each restored after.
3221    #[tokio::test]
3222    async fn adopt_refuses_bad_records_and_never_prints_the_token() {
3223        let (plane, recorder, _) = adopt_plane();
3224        let empty = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, "")
3225            .await
3226            .expect_err("no token");
3227        assert_eq!(empty.kind(), ErrorKind::InvalidArg);
3228        assert_eq!(recorder.calls().len(), 0, "refused before any call");
3229
3230        let (plane, recorder, _) = adopt_plane();
3231        recorder.answer(
3232            "GetMicrovm",
3233            Answer::ok(fake::microvm_response("RUNNING", None)),
3234        );
3235        let mismatch = Sandbox::adopt(plane, "mvm-abc123", "https://other.example", ADOPT_TOKEN)
3236            .await
3237            .expect_err("the endpoint belongs to another record");
3238        assert_eq!(mismatch.kind(), ErrorKind::InvalidArg);
3239        assert!(!mismatch.to_string().contains(ADOPT_TOKEN));
3240
3241        let (plane, recorder, _) = adopt_plane();
3242        recorder.answer(
3243            "GetMicrovm",
3244            Answer::ok(fake::microvm_response("REBOOTING", None)),
3245        );
3246        let unknown = Sandbox::adopt(plane, "mvm-abc123", ADOPT_ENDPOINT, ADOPT_TOKEN)
3247            .await
3248            .expect_err("an unknown state");
3249        assert_eq!(unknown.kind(), ErrorKind::Platform);
3250        assert!(!unknown.to_string().contains(ADOPT_TOKEN));
3251
3252        let (sandbox, _, _) = adopted_in("RUNNING").await;
3253        let printed = format!("{sandbox:?}");
3254        assert!(!printed.contains(ADOPT_TOKEN), "{printed}");
3255        assert!(printed.contains("adopted: true"), "{printed}");
3256    }
3257
3258    /// **STATE-1 and STATE-2.** A launch accepted is PENDING with the image recorded as
3259    /// existing; the platform reporting the run hook succeeded is what marks the token
3260    /// installed.
3261    ///
3262    /// The two halves are asserted with the *same* fake because they are the same call, and
3263    /// what distinguishes them is which fact is recorded when: `image_exists` is true from
3264    /// the accepted launch, `token_installed` only from the RUNNING report. A client that
3265    /// set both at the launch call would pass an end-state assertion and be wrong about a
3266    /// VM that died during startup — which is the next test.
3267    #[tokio::test]
3268    async fn a_launch_records_the_image_and_the_running_report_installs_the_token() {
3269        let (mut sandbox, recorder, _) = planted();
3270        assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
3271        assert!(
3272            !sandbox.image_exists(),
3273            "nothing is recorded before a launch"
3274        );
3275        assert!(!sandbox.token_installed());
3276
3277        answer_launch(&recorder);
3278        let session = sandbox
3279            .run(RunRequest::new().with_image("arn:image"))
3280            .await
3281            .expect("launches");
3282        assert_eq!(
3283            session.endpoint(),
3284            "https://mvm-abc123.microvm.us-east-1.amazonaws.com"
3285        );
3286
3287        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
3288        assert!(sandbox.image_exists(), "STATE-1: the image is recorded");
3289        assert!(sandbox.token_installed(), "STATE-2: the token is installed");
3290        assert_eq!(sandbox.bootstrap_count(), 1);
3291        assert_eq!(sandbox.microvm().expect("launched").id, "mvm-abc123");
3292
3293        // The payload really carried the token, read off the wire member rather than from
3294        // the request type — a field on a struct proves nothing about what was emitted.
3295        let body = recorder.first_body("RunMicrovm");
3296        let payload = body["runHookPayload"].as_str().expect("a string");
3297        assert!(payload.starts_with(r#"{"agent_token":"#), "{payload}");
3298        assert_eq!(body["idlePolicy"]["suspendedDurationSeconds"], 600);
3299    }
3300
3301    /// A launch env reaches the wire member the daemon parses, and it is the only thing
3302    /// that changes about the request.
3303    ///
3304    /// Read off `runHookPayload` rather than off the request struct: a field on a struct
3305    /// proves nothing about what was emitted, which is the same argument the test above
3306    /// makes about the token.
3307    #[tokio::test]
3308    async fn a_launch_env_reaches_the_run_hook_payload_on_the_wire() {
3309        let (mut sandbox, recorder, _) = planted();
3310        answer_launch(&recorder);
3311        sandbox
3312            .run(
3313                RunRequest::new()
3314                    .with_image("arn:image")
3315                    .with_launch_env("ANTHROPIC_BASE_URL", "https://gateway.example")
3316                    .with_launch_env("PATH", "/usr/local/bin:/usr/bin:/bin"),
3317            )
3318            .await
3319            .expect("launches");
3320
3321        let body = recorder.first_body("RunMicrovm");
3322        let payload = body["runHookPayload"].as_str().expect("a string");
3323        // One parse deeper, because that is where the daemon reads it from too.
3324        let inner: serde_json::Value =
3325            serde_json::from_str(payload).expect("the payload is itself JSON");
3326        assert!(
3327            inner["agent_token"].as_str().is_some_and(|t| !t.is_empty()),
3328            "the token still rides alongside: {payload}"
3329        );
3330        assert_eq!(
3331            inner["env"]["ANTHROPIC_BASE_URL"],
3332            "https://gateway.example"
3333        );
3334        assert_eq!(inner["env"]["PATH"], "/usr/local/bin:/usr/bin:/bin");
3335    }
3336
3337    /// **The advisory deny reaches the guest's environment, and it changes nothing else
3338    /// about the request.**
3339    ///
3340    /// Read off `runHookPayload` for the reason the launch-env test gives, and the connector
3341    /// member is asserted absent in the same body: `deny_egress` must not quietly ask the
3342    /// platform for anything, because the whole claim is that the platform has nothing to
3343    /// ask for.
3344    ///
3345    /// **Falsification** — 2026-09-13. Make `run` build the payload from
3346    /// `request.launch_env` instead of `request.effective_launch_env()` and the two
3347    /// `https_proxy` assertions go red while every other launch test stays green; restored
3348    /// after.
3349    #[tokio::test]
3350    async fn the_advisory_deny_reaches_the_launch_environment_in_both_spellings() {
3351        let (mut sandbox, recorder, _) = planted();
3352        answer_launch(&recorder);
3353        let request = RunRequest::new().with_image("arn:image").with_deny_egress();
3354        assert_eq!(
3355            request.egress_posture(),
3356            crate::control::EgressPosture::BestEffort
3357        );
3358        sandbox.run(request).await.expect("launches");
3359
3360        let body = recorder.first_body("RunMicrovm");
3361        let inner: serde_json::Value =
3362            serde_json::from_str(body["runHookPayload"].as_str().expect("a string"))
3363                .expect("the payload is itself JSON");
3364        for key in crate::sandbox::DENY_EGRESS_ENV_KEYS {
3365            assert_eq!(
3366                inner["env"][key], DENY_EGRESS_PROXY_URL,
3367                "{key} must point at the black hole: {inner}"
3368            );
3369        }
3370        assert!(
3371            body.get("egressNetworkConnectors").is_none(),
3372            "the advisory deny asks the platform for nothing: {body}"
3373        );
3374    }
3375
3376    /// A caller's own proxy value survives the deny, and a launch that never asked for the
3377    /// deny carries none of the keys.
3378    #[test]
3379    fn the_deny_never_overwrites_a_callers_own_proxy_and_is_absent_by_default() {
3380        let kept = RunRequest::new()
3381            .with_deny_egress()
3382            .with_launch_env("https_proxy", "http://proxy.internal:3128")
3383            .effective_launch_env();
3384        assert_eq!(kept["https_proxy"], "http://proxy.internal:3128");
3385        assert_eq!(kept["http_proxy"], DENY_EGRESS_PROXY_URL);
3386
3387        let plain = RunRequest::new().effective_launch_env();
3388        assert!(
3389            plain.is_empty(),
3390            "a launch that did not ask for the deny sends byte-for-byte what it always sent: \
3391             {plain:?}"
3392        );
3393        assert_eq!(
3394            RunRequest::new().egress_posture(),
3395            crate::control::EgressPosture::Unsealed,
3396            "and its posture is the measured one, not a seal"
3397        );
3398    }
3399
3400    /// **`egress` and `deny_egress` together are refused locally, with zero calls.**
3401    ///
3402    /// The same shape as the over-budget refusal below: a launch carrying both would report
3403    /// `open` while the workload's own tools failed closed, and AWS has no opinion to
3404    /// return about it.
3405    ///
3406    /// **Falsification** — 2026-09-13. Delete the refusal in `run` and this test fails on
3407    /// `expect_err`; the launch then succeeds and reports posture `open`. Restored after.
3408    #[tokio::test]
3409    async fn asking_for_egress_and_the_deny_together_is_refused_before_any_call() {
3410        let (mut sandbox, recorder, _) = planted();
3411        answer_launch(&recorder);
3412        let mut request = RunRequest::new().with_image("arn:image").with_egress();
3413        request.deny_egress = true;
3414
3415        let error = sandbox
3416            .run(request)
3417            .await
3418            .expect_err("opposite intents are not resolved by a precedence rule");
3419        assert_eq!(error.kind(), ErrorKind::InvalidArg);
3420        assert!(error.to_string().contains("opposite things"), "{error}");
3421        assert_eq!(
3422            recorder.calls().len(),
3423            0,
3424            "a locally-refused launch costs nothing"
3425        );
3426    }
3427
3428    /// **A pinned `imageVersion` reaches the wire through the sandbox**, and an unpinned
3429    /// launch omits the member entirely.
3430    ///
3431    /// This is the layer a caller actually uses, so the forwarding is what needs asserting:
3432    /// [`RunRequest::image_version`] is a field on a struct and proves nothing about the
3433    /// emitted body until it is read off the wire member.
3434    ///
3435    /// **Falsification** — run 2026-08-16. Drop `wire.image_version = ...` from `run` and the
3436    /// pinned assertion goes red with the member absent, while every other launch test still
3437    /// passes — which is why this one is here.
3438    #[tokio::test]
3439    async fn a_pinned_image_version_is_forwarded_to_the_launch_request() {
3440        let (mut sandbox, recorder, _) = planted();
3441        answer_launch(&recorder);
3442        sandbox
3443            .run(
3444                RunRequest::new()
3445                    .with_image("arn:image")
3446                    .with_image_version("2.0"),
3447            )
3448            .await
3449            .expect("launches");
3450        assert_eq!(
3451            recorder.first_body("RunMicrovm")["imageVersion"],
3452            "2.0",
3453            "a canary has to launch against the version it means to test"
3454        );
3455
3456        let (mut sandbox, recorder, _) = planted();
3457        answer_launch(&recorder);
3458        sandbox
3459            .run(RunRequest::new().with_image("arn:image"))
3460            .await
3461            .expect("launches");
3462        assert!(
3463            recorder
3464                .first_body("RunMicrovm")
3465                .get("imageVersion")
3466                .is_none(),
3467            "an unpinned launch sends what this client always sent"
3468        );
3469    }
3470
3471    /// **The local refusal, with zero control-plane calls.**
3472    ///
3473    /// The observable difference between this client and one that lets AWS answer, and the
3474    /// same shape as STATE-5's suspend refusal: an over-budget launch env fails before the
3475    /// launch rather than as a `ValidationException` on a member the caller did not know
3476    /// they were filling. botocore does not enforce the ceiling client-side, so without
3477    /// this there is no local signal at all.
3478    ///
3479    /// **Falsification** — build the payload after `run_microvm` instead of before, and the
3480    /// call count assertion goes red.
3481    #[tokio::test]
3482    async fn an_over_budget_launch_env_is_refused_before_any_control_plane_call() {
3483        let (mut sandbox, recorder, _) = planted();
3484        answer_launch(&recorder);
3485
3486        let error = sandbox
3487            .run(
3488                RunRequest::new()
3489                    .with_image("arn:image")
3490                    .with_launch_env("AWS_SESSION_TOKEN", "t".repeat(4096)),
3491            )
3492            .await
3493            .expect_err("a credential-scale launch env does not fit the payload");
3494
3495        assert_eq!(error.kind(), ErrorKind::InvalidArg);
3496        let message = error.to_string();
3497        assert!(message.contains("ceiling of 4096"), "{message}");
3498        assert!(message.contains("launch env contributed"), "{message}");
3499        assert_eq!(
3500            recorder.calls().len(),
3501            0,
3502            "the refusal has to be local: a launch that reached AWS costs a VM and a bill"
3503        );
3504        // And the sandbox is left usable rather than half-launched, so a caller can trim
3505        // the env and retry through the same handle.
3506        assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
3507        assert_eq!(sandbox.bootstrap_count(), 0);
3508        assert!(sandbox.microvm().is_none());
3509    }
3510
3511    /// **Issue #24's guards reach through `Sandbox`, which is the layer both bindings use.**
3512    ///
3513    /// `microvms-py`'s `run` and `microvms-js`'s `run` both build a [`RunRequest`] and hand it to
3514    /// [`Sandbox::run`], which fills a `RunMicrovmRequest` and calls
3515    /// [`crate::control::ControlPlane::run_microvm`]. So the guards there cover the bindings — but
3516    /// "cover" is a claim about a call chain, and a chain is what a refactor breaks. This asserts
3517    /// it at the layer the bindings actually enter, so a `Sandbox::run` that stopped delegating
3518    /// (or a binding-side default that bypassed the request type) fails a test rather than shipping
3519    /// an unguarded surface to Python and Node.
3520    ///
3521    /// `max_idle_sec` is the case that matters most here, because it is a plain `u32` keyword
3522    /// argument on both bindings with no type narrowing it: `sandbox.run(max_idle_sec=59)` is what
3523    /// a Python caller writes, and before this it reached the wire.
3524    ///
3525    /// **Guard proof.** Delete `require_idle_duration` from `run_microvm` and the idle row goes red
3526    /// on the call count; delete `require_valid_role_arn` and the role row does. Neither guard is in
3527    /// this file, which is the point — the test is about the chain.
3528    #[tokio::test]
3529    async fn the_bindings_layer_refuses_an_illegal_launch_with_zero_calls() {
3530        let cases: [(&str, RunRequest, &str); 3] = [
3531            (
3532                "max_idle_sec=59, which is what a Python keyword argument passes",
3533                RunRequest {
3534                    max_idle_sec: 59,
3535                    ..RunRequest::new().with_image("arn:image")
3536                },
3537                "maxIdleDurationSeconds",
3538            ),
3539            (
3540                "an execution role that is a bare name",
3541                RunRequest {
3542                    execution_role_arn: Some("execution-role".to_string()),
3543                    ..RunRequest::new().with_image("arn:image")
3544                },
3545                "role *name*",
3546            ),
3547            (
3548                "a pinned version with a trailing newline",
3549                RunRequest::new()
3550                    .with_image("arn:image")
3551                    .with_image_version("2.0\n"),
3552                "contains whitespace",
3553            ),
3554        ];
3555
3556        for (label, request, expected) in cases {
3557            let (mut sandbox, recorder, _) = planted();
3558            // The launch answered, so a missing guard is a *successful* launch — a real VM and a
3559            // real bill — rather than a different failure.
3560            answer_launch(&recorder);
3561
3562            // `expect_err` needs the Ok type to be `Debug`, and `run` answers `&mut Session`
3563            // (which is not) — so the discriminant is matched instead. That is also the more
3564            // honest assertion: it says the launch produced no session at all.
3565            let Err(error) = sandbox.run(request).await else {
3566                panic!("{label} must be refused");
3567            };
3568            assert_eq!(error.kind(), ErrorKind::InvalidArg, "{label}");
3569            assert!(
3570                error.to_string().contains(expected),
3571                "{label}: wanted {expected:?}, got {error}"
3572            );
3573            assert_eq!(
3574                recorder.calls().len(),
3575                0,
3576                "{label}: the refusal has to be local, because a launch that reached AWS costs a \
3577                 VM and a bill"
3578            );
3579            assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
3580            assert!(sandbox.microvm().is_none());
3581        }
3582    }
3583
3584    /// A launch whose VM dies during startup leaves the token **not** installed, because
3585    /// the run hook is what delivers it and a dead VM ran no hook.
3586    ///
3587    /// The distinction this pins is the one the test above cannot: both a correct client and
3588    /// one that installs the token at the launch call reach RUNNING with the token set, and
3589    /// only this case separates them.
3590    #[tokio::test]
3591    async fn a_launch_that_dies_during_startup_installs_no_token() {
3592        let (mut sandbox, recorder, _) = planted();
3593        recorder
3594            .answer(
3595                "RunMicrovm",
3596                Answer::ok(fake::microvm_response("PENDING", None)),
3597            )
3598            .answer(
3599                "GetMicrovm",
3600                Answer::ok(fake::microvm_response(
3601                    "TERMINATED",
3602                    Some("run hook returned 500"),
3603                )),
3604            );
3605
3606        let error = sandbox
3607            .run(RunRequest::new().with_image("arn:image"))
3608            .await
3609            .expect_err("a VM that died during startup is not a launch");
3610        assert_eq!(error.kind(), ErrorKind::LaunchDied);
3611        assert!(
3612            error.to_string().contains("run hook returned 500"),
3613            "{error}"
3614        );
3615
3616        assert!(
3617            !sandbox.token_installed(),
3618            "the run hook never answered, so nothing was installed"
3619        );
3620        assert_eq!(
3621            sandbox.bootstrap_count(),
3622            0,
3623            "a bootstrap counted here would make STATE-3's ceiling unreachable for a retry"
3624        );
3625        assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
3626        assert!(
3627            sandbox.image_exists(),
3628            "STATE-1 still holds: the launch was accepted against a real image"
3629        );
3630    }
3631
3632    /// **STATE-3, the guard proof.** A second `run` on one sandbox is refused, and it is
3633    /// refused with **zero** further control-plane calls.
3634    ///
3635    /// The call count is the assertion that matters. A client that let the second launch
3636    /// through would create a second VM and silently address two guests through one handle,
3637    /// and it would also deliver a second run-hook payload to a daemon whose one-shot
3638    /// bootstrap answers 409 — so "an error came back" is not enough to tell the two apart.
3639    ///
3640    /// **Falsification** — delete the `bootstrap_count > 0` branch from `run` and this test
3641    /// is red on both the count and the call total. Verified; see the packet's guard proofs.
3642    #[tokio::test]
3643    async fn a_second_run_on_one_sandbox_is_refused_before_any_call() {
3644        let (mut sandbox, recorder, _) = launched().await;
3645        assert_eq!(sandbox.bootstrap_count(), 1);
3646        let before = recorder.calls().len();
3647
3648        let error = sandbox
3649            .run(RunRequest::new().with_image("arn:image"))
3650            .await
3651            .expect_err("the token is installed at most once per VM lifetime");
3652        assert_eq!(error.kind(), ErrorKind::InvalidArg);
3653        assert!(error.to_string().contains("STATE-3"), "{error}");
3654        assert!(
3655            error.to_string().contains("needs a second Sandbox"),
3656            "the remedy has to be nameable: {error}"
3657        );
3658
3659        assert_eq!(
3660            sandbox.bootstrap_count(),
3661            1,
3662            "bootstrap_count <= 1 is the Z3-proved invariant"
3663        );
3664        assert_eq!(
3665            recorder.calls().len(),
3666            before,
3667            "the refusal must cost no control-plane call"
3668        );
3669        assert_eq!(recorder.call_count("RunMicrovm"), 1);
3670    }
3671
3672    /// **STATE-4 and STATE-6.** A suspend from RUNNING moves to SUSPENDING before the wait,
3673    /// and the platform reporting SUSPENDED is what moves it to SUSPENDED.
3674    #[tokio::test]
3675    async fn a_suspend_from_running_passes_through_suspending_to_suspended() {
3676        let (sandbox, recorder, _) = suspended().await;
3677        assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended);
3678        assert!(
3679            sandbox.token_installed(),
3680            "a freeze keeps the guest's memory, so the token survives"
3681        );
3682        assert_eq!(sandbox.bootstrap_count(), 1, "no re-bootstrap on a freeze");
3683
3684        let calls = recorder.calls();
3685        let suspend = calls
3686            .iter()
3687            .find(|call| call.operation == "SuspendMicrovm")
3688            .expect("the suspend went out");
3689        assert_eq!(suspend.method, Method::Post);
3690        assert_eq!(suspend.path, "/2025-09-09/microvms/mvm-abc123/suspend");
3691    }
3692
3693    /// A suspend whose VM dies while suspending reports TERMINATED rather than raising, and
3694    /// records it — which is what stops a later resume.
3695    ///
3696    /// TERMINATED is *wanted* by the suspend wait for a reason: a VM that dies mid-suspend
3697    /// is a state to report, not an exception out of the middle of a teardown.
3698    #[tokio::test]
3699    async fn a_vm_that_dies_while_suspending_is_recorded_rather_than_raised() {
3700        let (mut sandbox, recorder, _) = launched().await;
3701        recorder
3702            .answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
3703            .answer(
3704                "GetMicrovm",
3705                Answer::ok(fake::microvm_response("TERMINATED", Some("idle policy"))),
3706            );
3707
3708        sandbox
3709            .suspend()
3710            .await
3711            .expect("a death mid-suspend is a state, not an error");
3712        assert_eq!(sandbox.lifecycle(), Lifecycle::Terminated);
3713        assert!(
3714            sandbox.was_terminated(),
3715            "STATE-11's precondition is recorded"
3716        );
3717    }
3718
3719    /// A suspend whose wire call fails leaves the sandbox in RUNNING, and a retry works.
3720    ///
3721    /// STATE-4's "accepted" is the wire call succeeding. A client that moved to SUSPENDING
3722    /// before the call would strand a failed call there — a state neither suspend nor
3723    /// resume accepts, so one throttled or dropped request would brick the handle.
3724    /// **Falsification** — move `self.lifecycle = Lifecycle::Suspending` back above the
3725    /// `control.suspend` call and the first assertion here reads SUSPENDING, and the retry
3726    /// is refused by the STATE-5 guard.
3727    #[tokio::test]
3728    async fn a_suspend_whose_call_fails_stays_running_and_can_be_retried() {
3729        let (mut sandbox, recorder, _) = planted();
3730        recorder
3731            .answer(
3732                "RunMicrovm",
3733                Answer::ok(fake::microvm_response("PENDING", None)),
3734            )
3735            .answer(
3736                "GetMicrovm",
3737                Answer::ok(fake::microvm_response("RUNNING", None)),
3738            )
3739            .answer(
3740                "GetMicrovm",
3741                Answer::ok(fake::microvm_response("SUSPENDED", None)),
3742            )
3743            .answer(
3744                "CreateMicrovmAuthToken",
3745                Answer::ok(fake::auth_token_response("proxy-token")),
3746            )
3747            // A 409 rather than a 429 or a transport cut, because those two are retried
3748            // inside `send_with_retry` and this test wants the call to fail once, fast.
3749            .answer("SuspendMicrovm", Answer::failure(409, "ConflictException"))
3750            .answer("SuspendMicrovm", Answer::ok(fake::empty_response()));
3751
3752        sandbox
3753            .run(RunRequest::new().with_image("arn:image"))
3754            .await
3755            .expect("launches");
3756
3757        sandbox
3758            .suspend()
3759            .await
3760            .expect_err("the control plane refused the suspend");
3761        assert_eq!(
3762            sandbox.lifecycle(),
3763            Lifecycle::Running,
3764            "a refused suspend must not move the lifecycle: SUSPENDING accepts neither a \
3765             suspend nor a resume, so recording it here would brick the handle"
3766        );
3767
3768        sandbox.suspend().await.expect("the retry suspends");
3769        assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended);
3770        assert_eq!(recorder.call_count("SuspendMicrovm"), 2);
3771    }
3772
3773    /// **STATE-5, the guard proof.** A suspend from anything but RUNNING is refused with
3774    /// **zero** control-plane calls.
3775    ///
3776    /// Every non-RUNNING state, so a state added to `Lifecycle` later is not silently
3777    /// exempt. The count is the load-bearing assertion: letting the call go and reading the
3778    /// service's answer also produces an error, and that error is about a non-running id
3779    /// rather than about which of two things the caller got wrong.
3780    ///
3781    /// **Falsification** — delete the `lifecycle != Running` branch from `suspend` and the
3782    /// SUSPENDED case emits a `SuspendMicrovm` call, turning the count assertion red.
3783    /// Verified; see the packet's guard proofs.
3784    #[tokio::test]
3785    async fn a_suspend_from_a_non_running_state_reaches_no_control_plane_call() {
3786        // From SUSPENDED — the caller who believes they resumed.
3787        let (mut sandbox, recorder, _) = suspended().await;
3788        let before = recorder.call_count("SuspendMicrovm");
3789
3790        let error = sandbox
3791            .suspend()
3792            .await
3793            .expect_err("a suspend is only issued from RUNNING");
3794        assert_eq!(error.kind(), ErrorKind::InvalidArg);
3795        assert!(error.to_string().contains("STATE-5"), "{error}");
3796        assert!(error.to_string().contains("SUSPENDED"), "{error}");
3797        assert_eq!(
3798            recorder.call_count("SuspendMicrovm"),
3799            before,
3800            "the refusal must be local: no second suspend went to the wire"
3801        );
3802
3803        // And from PENDING, before anything launched at all.
3804        let (mut fresh, fresh_recorder, _) = planted();
3805        let error = fresh.suspend().await.expect_err("nothing to suspend");
3806        assert_eq!(error.kind(), ErrorKind::Precondition);
3807        assert_eq!(fresh_recorder.calls().len(), 0);
3808    }
3809
3810    /// **STATE-7 and STATE-8.** A resume from SUSPENDED returns to RUNNING, re-delivers
3811    /// **nothing**, and drops the cached proxy token.
3812    ///
3813    /// Three assertions, and each one is a different failure mode. The bootstrap count says
3814    /// no run-hook payload was re-delivered — which a daemon's one-shot bootstrap would
3815    /// answer 409 to, reading like a broken VM. The `RunMicrovm` count says no second launch
3816    /// happened. And `is_cached` says the token was invalidated, which is the only
3817    /// observable difference on a path where the endpoint URL does not change: a client that
3818    /// kept the token would produce identical requests until the pre-suspend token stopped
3819    /// validating, and that rejection reads exactly like a dead daemon.
3820    #[tokio::test]
3821    async fn a_resume_reuses_the_token_redelivers_nothing_and_drops_the_proxy_token() {
3822        let (mut sandbox, recorder, _) = suspended().await;
3823
3824        // The session mints once before the suspend, so there is a cached token to drop.
3825        let auth = Arc::clone(
3826            sandbox
3827                .session()
3828                .expect("launched")
3829                .proxy_auth()
3830                .expect("the launch wired a minter"),
3831        );
3832        auth.headers().await.expect("mints");
3833        assert!(
3834            auth.is_cached(),
3835            "there must be a token for the drop to matter"
3836        );
3837        assert_eq!(auth.mint_count(), 1);
3838
3839        recorder
3840            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
3841            .answer(
3842                "GetMicrovm",
3843                Answer::ok(fake::microvm_response("RUNNING", None)),
3844            );
3845        let session = sandbox.resume().await.expect("resumes");
3846        assert_eq!(
3847            session.endpoint(),
3848            "https://mvm-abc123.microvm.us-east-1.amazonaws.com"
3849        );
3850
3851        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
3852        assert!(
3853            sandbox.token_installed(),
3854            "STATE-7: the installed token is reused"
3855        );
3856        assert_eq!(
3857            sandbox.bootstrap_count(),
3858            1,
3859            "STATE-7: a resume re-delivers no run-hook payload"
3860        );
3861        assert_eq!(
3862            recorder.call_count("RunMicrovm"),
3863            1,
3864            "a resume is not a second launch"
3865        );
3866        assert!(
3867            !auth.is_cached(),
3868            "STATE-8: the cached proxy token survived the resume"
3869        );
3870    }
3871
3872    /// **STATE-8's guard proof, on the mint count.** The request after a resume mints a
3873    /// fresh token rather than reusing the pre-suspend one.
3874    ///
3875    /// Separate from the test above because `is_cached` is a fact about the cache and this is
3876    /// a fact about the wire: a client that dropped the cache but kept emitting the old
3877    /// header would pass the first assertion and fail every request.
3878    ///
3879    /// **Falsification** — delete the `proxy.invalidate()` line from `Session::rebind` and
3880    /// the mint count stays at 1 here. Verified; see the packet's guard proofs.
3881    #[tokio::test]
3882    async fn the_request_after_a_resume_mints_a_fresh_proxy_token() {
3883        let (mut sandbox, recorder, _) = suspended().await;
3884        let auth = Arc::clone(
3885            sandbox
3886                .session()
3887                .expect("launched")
3888                .proxy_auth()
3889                .expect("wired"),
3890        );
3891        auth.headers().await.expect("mints");
3892        assert_eq!(auth.mint_count(), 1);
3893
3894        recorder
3895            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
3896            .answer(
3897                "GetMicrovm",
3898                Answer::ok(fake::microvm_response("RUNNING", None)),
3899            );
3900        sandbox.resume().await.expect("resumes");
3901
3902        // No clock movement at all, so a re-mint here is caused by the invalidation rather
3903        // than by the refresh window rolling over.
3904        auth.headers().await.expect("re-mints");
3905        assert_eq!(
3906            auth.mint_count(),
3907            2,
3908            "STATE-8: the resume did not force a fresh mint"
3909        );
3910    }
3911
3912    /// A keepalive reads this receiver instead of the lock, so every transition must reach
3913    /// it: a suspend it missed would be undone by the keepalive's next poll auto-resuming
3914    /// the VM.
3915    #[tokio::test]
3916    async fn the_lifecycle_watch_follows_every_transition() {
3917        let (mut sandbox, recorder, _clock) = planted();
3918        let watch = sandbox.watch_lifecycle();
3919        assert_eq!(*watch.borrow(), Lifecycle::Pending);
3920        recorder
3921            .answer(
3922                "RunMicrovm",
3923                Answer::ok(fake::microvm_response("PENDING", None)),
3924            )
3925            .answer(
3926                "GetMicrovm",
3927                Answer::ok(fake::microvm_response("RUNNING", None)),
3928            )
3929            .answer(
3930                "GetMicrovm",
3931                Answer::ok(fake::microvm_response("SUSPENDED", None)),
3932            )
3933            .answer(
3934                "CreateMicrovmAuthToken",
3935                Answer::ok(fake::auth_token_response("proxy-token")),
3936            )
3937            .answer("SuspendMicrovm", Answer::ok(fake::empty_response()));
3938        sandbox
3939            .run(RunRequest::new().with_image("arn:image"))
3940            .await
3941            .expect("launches");
3942        assert_eq!(*watch.borrow(), Lifecycle::Running);
3943        sandbox.suspend().await.expect("suspends");
3944        assert_eq!(*watch.borrow(), Lifecycle::Suspended);
3945        assert_eq!(*watch.borrow(), sandbox.lifecycle());
3946    }
3947
3948    /// `ResumeMicrovm`'s refusal of a VM the service terminated, as it answered on 2026-10-12
3949    /// in us-east-1 (#597): a 400 whose error type is `ValidationException`.
3950    fn terminated_refusal() -> Answer {
3951        Answer {
3952            status: 400,
3953            body: r#"{"message": "The MicroVM mvm-abc123 has been terminated and its state cannot be changed."}"#
3954                .to_string(),
3955            error_type: Some("ValidationException".to_string()),
3956        }
3957    }
3958
3959    /// STATE-7 and STATE-8: idle suspension is learned from the service, then resumed
3960    /// without a second bootstrap. The cached proxy token is dropped as for an explicit
3961    /// suspend, and both the held VM and the lifecycle watch reflect the new state.
3962    #[tokio::test]
3963    async fn resume_observes_platform_idle_suspension_and_resumes() {
3964        let (mut sandbox, recorder, _) = planted();
3965        recorder
3966            .answer(
3967                "RunMicrovm",
3968                Answer::ok(fake::microvm_response("PENDING", None)),
3969            )
3970            .answer(
3971                "GetMicrovm",
3972                Answer::ok(fake::microvm_response("RUNNING", None)),
3973            )
3974            .answer(
3975                "GetMicrovm",
3976                Answer::ok(fake::microvm_response("SUSPENDED", None)),
3977            )
3978            .answer(
3979                "GetMicrovm",
3980                Answer::ok(fake::microvm_response("RUNNING", None)),
3981            )
3982            .answer(
3983                "CreateMicrovmAuthToken",
3984                Answer::ok(fake::auth_token_response("proxy-token")),
3985            )
3986            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()));
3987        sandbox
3988            .run(RunRequest::new().with_image("arn:image"))
3989            .await
3990            .expect("launch");
3991        let token = sandbox
3992            .session()
3993            .expect("session")
3994            .agent_token()
3995            .to_string();
3996        let watch = sandbox.watch_lifecycle();
3997        let calls = recorder.calls().len();
3998        sandbox.resume().await.expect("idle-suspended VM resumes");
3999        assert_eq!(
4000            &recorder.operations()[calls..],
4001            &["GetMicrovm", "ResumeMicrovm", "GetMicrovm"]
4002        );
4003        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4004        assert_eq!(*watch.borrow(), Lifecycle::Running);
4005        assert_eq!(sandbox.microvm().expect("VM").state, "RUNNING");
4006        assert_eq!(sandbox.bootstrap_count(), 1);
4007        assert_eq!(recorder.call_count("RunMicrovm"), 1);
4008        assert_eq!(recorder.call_count("SuspendMicrovm"), 0);
4009        assert_eq!(sandbox.session().expect("session").agent_token(), token);
4010        assert!(
4011            !sandbox
4012                .session()
4013                .expect("session")
4014                .proxy_auth()
4015                .expect("auth")
4016                .is_cached()
4017        );
4018    }
4019
4020    /// STATE-12 and STATE-11: an idle-suspended VM may already have ended before resume.
4021    /// The observation names its state and reason, records termination, and avoids a
4022    /// pointless resume call or a drop warning about a live VM.
4023    #[tokio::test]
4024    async fn resume_observes_platform_termination_and_records_window_closed() {
4025        for state in ["TERMINATING", "TERMINATED"] {
4026            let (mut sandbox, recorder, _) = planted();
4027            recorder
4028                .answer(
4029                    "RunMicrovm",
4030                    Answer::ok(fake::microvm_response("PENDING", None)),
4031                )
4032                .answer(
4033                    "GetMicrovm",
4034                    Answer::ok(fake::microvm_response("RUNNING", None)),
4035                )
4036                .answer(
4037                    "GetMicrovm",
4038                    Answer::ok(fake::microvm_response(state, Some("idle window elapsed"))),
4039                )
4040                .answer(
4041                    "CreateMicrovmAuthToken",
4042                    Answer::ok(fake::auth_token_response("proxy-token")),
4043                );
4044            sandbox
4045                .run(RunRequest::new().with_image("arn:image"))
4046                .await
4047                .expect("launch");
4048            let watch = sandbox.watch_lifecycle();
4049            let error = sandbox.resume().await.expect_err("the VM ended");
4050            assert_eq!(error.kind(), ErrorKind::WindowClosed, "{error}");
4051            assert!(error.to_string().contains(state), "{error}");
4052            assert!(error.to_string().contains("idle window elapsed"), "{error}");
4053            assert_eq!(sandbox.lifecycle(), Lifecycle::Terminated);
4054            assert_eq!(*watch.borrow(), Lifecycle::Terminated);
4055            assert_eq!(sandbox.microvm().expect("VM").state, state);
4056            assert!(sandbox.was_terminated());
4057            assert_eq!(sandbox.drop_warning(), None);
4058            let calls = recorder.calls().len();
4059            assert_eq!(
4060                sandbox.resume().await.expect_err("STATE-11").kind(),
4061                ErrorKind::InvalidArg
4062            );
4063            assert_eq!(
4064                recorder.calls().len(),
4065                calls,
4066                "known termination stays local"
4067            );
4068            assert_eq!(recorder.call_count("ResumeMicrovm"), 0);
4069        }
4070    }
4071
4072    /// STATE-7: a service that still reports RUNNING must not receive ResumeMicrovm.
4073    /// A failed observation also leaves the handle available for a later retry.
4074    #[tokio::test]
4075    async fn resume_observes_running_and_propagates_observation_failures() {
4076        for (response, expected) in [
4077            (
4078                Answer::ok(fake::microvm_response("RUNNING", None)),
4079                ErrorKind::InvalidArg,
4080            ),
4081            (
4082                Answer::ok(fake::microvm_response("UNKNOWN", None)),
4083                ErrorKind::Platform,
4084            ),
4085            (
4086                Answer::failure(403, "access denied"),
4087                ErrorKind::Credentials,
4088            ),
4089        ] {
4090            let (mut sandbox, recorder, _) = planted();
4091            recorder
4092                .answer(
4093                    "RunMicrovm",
4094                    Answer::ok(fake::microvm_response("PENDING", None)),
4095                )
4096                .answer(
4097                    "GetMicrovm",
4098                    Answer::ok(fake::microvm_response("RUNNING", None)),
4099                )
4100                .answer("GetMicrovm", response)
4101                .answer(
4102                    "CreateMicrovmAuthToken",
4103                    Answer::ok(fake::auth_token_response("proxy-token")),
4104                );
4105            sandbox
4106                .run(RunRequest::new().with_image("arn:image"))
4107                .await
4108                .expect("launch");
4109            let calls = recorder.calls().len();
4110            let error = sandbox.resume().await.expect_err("cannot resume");
4111            assert_eq!(error.kind(), expected, "{error}");
4112            assert_eq!(&recorder.operations()[calls..], &["GetMicrovm"]);
4113            assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4114            assert!(!sandbox.was_terminated());
4115        }
4116    }
4117
4118    /// A transient service state must not strand a locally RUNNING handle: the next
4119    /// resume still observes the service and can resume once suspension completes.
4120    #[tokio::test]
4121    async fn resume_retries_observation_after_transient_service_states() {
4122        for state in ["SUSPENDING", "PENDING", "RESUMING"] {
4123            let (mut sandbox, recorder, _) = planted();
4124            recorder
4125                .answer(
4126                    "RunMicrovm",
4127                    Answer::ok(fake::microvm_response("PENDING", None)),
4128                )
4129                .answer(
4130                    "GetMicrovm",
4131                    Answer::ok(fake::microvm_response("RUNNING", None)),
4132                )
4133                .answer(
4134                    "GetMicrovm",
4135                    Answer::ok(fake::microvm_response(state, None)),
4136                )
4137                .answer(
4138                    "GetMicrovm",
4139                    Answer::ok(fake::microvm_response("SUSPENDED", None)),
4140                )
4141                .answer(
4142                    "GetMicrovm",
4143                    Answer::ok(fake::microvm_response("RUNNING", None)),
4144                )
4145                .answer(
4146                    "CreateMicrovmAuthToken",
4147                    Answer::ok(fake::auth_token_response("proxy-token")),
4148                )
4149                .answer("ResumeMicrovm", Answer::ok(fake::empty_response()));
4150            sandbox
4151                .run(RunRequest::new().with_image("arn:image"))
4152                .await
4153                .expect("launch");
4154            let error = sandbox.resume().await.expect_err("still changing state");
4155            assert!(error.to_string().contains(state), "{error}");
4156            assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4157            assert_eq!(recorder.call_count("ResumeMicrovm"), 0);
4158            sandbox
4159                .resume()
4160                .await
4161                .expect("the next observation can resume");
4162            assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4163            assert_eq!(recorder.call_count("ResumeMicrovm"), 1);
4164        }
4165    }
4166
4167    /// **STATE-12, the regression (#597).** A resume 1283 s into a 60 s window, on a sandbox
4168    /// that suspended the VM itself, reaches `ResumeMicrovm` and comes back RUNNING. Those are
4169    /// the numbers measured on 2026-10-12 in us-east-1: the service doesn't hold an explicit
4170    /// suspend to `suspendedDurationSeconds`, so a client that refused here refused a resume
4171    /// the service honors.
4172    #[tokio::test]
4173    async fn a_resume_past_the_window_of_an_explicit_suspend_reaches_the_service_and_resumes() {
4174        let (mut sandbox, recorder, clock) = suspended_with_window(60).await;
4175        assert_eq!(sandbox.suspended_window(), Some(Duration::from_secs(60)));
4176        assert_eq!(
4177            sandbox.idle_window(),
4178            Some(Duration::from_secs(600)),
4179            "the launch's own maxIdleDurationSeconds, which a keepalive checks its cadence against"
4180        );
4181
4182        clock.advance(Duration::from_secs(1283));
4183        recorder
4184            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
4185            .answer(
4186                "GetMicrovm",
4187                Answer::ok(fake::microvm_response("RUNNING", None)),
4188            );
4189        sandbox
4190            .resume()
4191            .await
4192            .expect("the service resumes an explicit suspend past its window");
4193
4194        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4195        assert!(!sandbox.was_terminated());
4196        assert_eq!(
4197            recorder.call_count("ResumeMicrovm"),
4198            1,
4199            "the resume has to reach the service"
4200        );
4201    }
4202
4203    /// **STATE-12, a VM the service ended.** The service refuses the resume with the
4204    /// `ValidationException` it gave on 2026-10-12 for a VM the idle policy terminated, and
4205    /// `GetMicrovm` reports TERMINATED. That's `ERR_WINDOW_CLOSED` naming the state and the
4206    /// `stateReason`, and the sandbox records the termination: a second resume is refused
4207    /// with no call (STATE-11), and dropping it warns about no live VM.
4208    #[tokio::test]
4209    async fn a_resume_the_service_refuses_for_an_ended_vm_is_window_closed_and_recorded() {
4210        let (mut sandbox, recorder, _clock) = planted();
4211        // Every `GetMicrovm` answer queued up front, in the order the launch wait, the suspend
4212        // wait and the refused resume's read take them; `suspended_with_window` says why.
4213        recorder
4214            .answer(
4215                "RunMicrovm",
4216                Answer::ok(fake::microvm_response("PENDING", None)),
4217            )
4218            .answer(
4219                "GetMicrovm",
4220                Answer::ok(fake::microvm_response("RUNNING", None)),
4221            )
4222            .answer(
4223                "GetMicrovm",
4224                Answer::ok(fake::microvm_response("SUSPENDED", None)),
4225            )
4226            .answer(
4227                "GetMicrovm",
4228                Answer::ok(fake::microvm_response(
4229                    "TERMINATED",
4230                    Some("MicroVM exceeded maximum lifetime."),
4231                )),
4232            )
4233            .answer(
4234                "CreateMicrovmAuthToken",
4235                Answer::ok(fake::auth_token_response("proxy-token")),
4236            )
4237            .answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
4238            .answer("ResumeMicrovm", terminated_refusal());
4239        sandbox
4240            .run(
4241                RunRequest::new()
4242                    .with_image("arn:image")
4243                    .with_suspended_sec(60),
4244            )
4245            .await
4246            .expect("launches");
4247        sandbox.suspend().await.expect("suspends");
4248
4249        let error = sandbox
4250            .resume()
4251            .await
4252            .expect_err("the service ended the VM");
4253        assert_eq!(error.kind(), ErrorKind::WindowClosed, "{error}");
4254        assert_eq!(error.code(), "ERR_WINDOW_CLOSED");
4255        let message = error.to_string();
4256        assert!(message.contains("TERMINATED"), "the state: {message}");
4257        assert!(
4258            message.contains("MicroVM exceeded maximum lifetime."),
4259            "the stateReason: {message}"
4260        );
4261        assert_eq!(sandbox.lifecycle(), Lifecycle::Terminated);
4262        assert!(sandbox.was_terminated());
4263        assert_eq!(recorder.call_count("ResumeMicrovm"), 1);
4264
4265        let again = sandbox.resume().await.expect_err("STATE-11");
4266        assert!(again.to_string().contains("STATE-11"), "{again}");
4267        assert_eq!(
4268            recorder.call_count("ResumeMicrovm"),
4269            1,
4270            "the second resume makes no call"
4271        );
4272        assert_eq!(
4273            sandbox.drop_warning(),
4274            None,
4275            "a VM the service ended bills nothing, so dropping its sandbox isn't a leak"
4276        );
4277    }
4278
4279    /// A resume the service refuses while `GetMicrovm` still reports SUSPENDED is the
4280    /// service's answer, and the sandbox stays SUSPENDED: only a VM the service reports dead
4281    /// is recorded as terminated (STATE-12), so a retry reaches the service and resumes.
4282    #[tokio::test]
4283    async fn a_resume_refused_for_a_live_vm_leaves_the_sandbox_suspended_and_resumable() {
4284        let (mut sandbox, recorder, _clock) = suspended().await;
4285        recorder
4286            .answer(
4287                "ResumeMicrovm",
4288                Answer::failure(409, "The MicroVM is changing state."),
4289            )
4290            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()));
4291
4292        let error = sandbox.resume().await.expect_err("the service refused");
4293        assert_eq!(error.kind(), ErrorKind::Platform, "{error}");
4294        assert_eq!(sandbox.lifecycle(), Lifecycle::Suspended);
4295        assert!(!sandbox.was_terminated());
4296
4297        recorder.answer(
4298            "GetMicrovm",
4299            Answer::ok(fake::microvm_response("RUNNING", None)),
4300        );
4301        sandbox.resume().await.expect("the retry resumes");
4302        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4303        assert_eq!(recorder.call_count("ResumeMicrovm"), 2);
4304    }
4305
4306    /// **#195 at the sandbox.** A client-token launch that adopts an idle-suspended VM is
4307    /// resumed and reaches RUNNING with the token counted once. The same poll on a launch
4308    /// without a caller token is still a startup death (TRAP-8).
4309    #[tokio::test]
4310    async fn a_client_token_launch_resumes_the_vm_it_adopted() {
4311        let (mut sandbox, recorder, _) = planted();
4312        recorder
4313            .answer(
4314                "RunMicrovm",
4315                Answer::ok(fake::microvm_response("SUSPENDED", None)),
4316            )
4317            .answer(
4318                "GetMicrovm",
4319                Answer::ok(fake::microvm_response("SUSPENDED", None)),
4320            )
4321            .answer(
4322                "GetMicrovm",
4323                Answer::ok(fake::microvm_response("RUNNING", None)),
4324            )
4325            .answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
4326            .answer(
4327                "CreateMicrovmAuthToken",
4328                Answer::ok(fake::auth_token_response("proxy-token")),
4329            );
4330        let mut request = RunRequest::new().with_image("arn:image");
4331        request.client_token = Some("job-195".into());
4332        request.agent_token = Some("agent-token".into());
4333        sandbox
4334            .run(request)
4335            .await
4336            .expect("the adopted VM is resumed");
4337        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4338        assert_eq!(sandbox.bootstrap_count(), 1);
4339        assert_eq!(recorder.call_count("ResumeMicrovm"), 1);
4340
4341        let (mut fresh, recorder, _) = planted();
4342        recorder
4343            .answer(
4344                "RunMicrovm",
4345                Answer::ok(fake::microvm_response("PENDING", None)),
4346            )
4347            .answer(
4348                "GetMicrovm",
4349                Answer::ok(fake::microvm_response("SUSPENDED", Some("hook failed"))),
4350            );
4351        let error = fresh
4352            .run(RunRequest::new().with_image("arn:image"))
4353            .await
4354            .expect_err("a fresh launch that reads SUSPENDED died during startup");
4355        assert_eq!(error.kind(), ErrorKind::LaunchDied);
4356        assert_eq!(recorder.call_count("ResumeMicrovm"), 0);
4357    }
4358
4359    /// **`wait: false`.** The launch returns once accepted, with an addressable session and
4360    /// the lifecycle still PENDING; `wait_until_running` finishes it, exactly once.
4361    #[tokio::test]
4362    async fn a_launch_that_does_not_wait_is_finished_by_wait_until_running() {
4363        let (mut sandbox, recorder, _) = planted();
4364        answer_launch(&recorder);
4365        let mut request = RunRequest::new().with_image("arn:image");
4366        request.wait = false;
4367        let endpoint = sandbox
4368            .run(request)
4369            .await
4370            .expect("accepted")
4371            .endpoint()
4372            .to_string();
4373        assert!(endpoint.starts_with("https://"), "{endpoint}");
4374        assert_eq!(sandbox.lifecycle(), Lifecycle::Pending);
4375        assert_eq!(sandbox.bootstrap_count(), 0);
4376        assert_eq!(recorder.call_count("GetMicrovm"), 0, "nothing polled yet");
4377
4378        sandbox
4379            .wait_until_running(DEFAULT_RUNNING_TIMEOUT)
4380            .await
4381            .expect("reaches RUNNING");
4382        assert_eq!(sandbox.lifecycle(), Lifecycle::Running);
4383        assert_eq!(sandbox.bootstrap_count(), 1);
4384        let error = sandbox
4385            .wait_until_running(DEFAULT_RUNNING_TIMEOUT)
4386            .await
4387            .expect_err("a running launch has nothing to wait for");
4388        assert_eq!(error.kind(), ErrorKind::InvalidArg);
4389        assert_eq!(sandbox.bootstrap_count(), 1, "counted once (STATE-3)");
4390    }
4391
4392    /// **STATE-11, the resume-after-terminate case the packet names.** A terminated VM never
4393    /// returns to RUNNING, and the recorder sees **zero** resume wire calls.
4394    ///
4395    /// The zero count is the assertion the packet asks for, and it is the right one: a client
4396    /// that called and read the answer would also fail, with whatever the service says about
4397    /// a terminated id — which is a different statement from "this VM is gone and even a
4398    /// successful call would hand you a different machine".
4399    #[tokio::test]
4400    async fn a_resume_after_terminate_records_zero_resume_calls() {
4401        let (mut sandbox, recorder, _) = launched().await;
4402        recorder.answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
4403        let report = sandbox.terminate(TeardownOpts::default()).await;
4404        assert!(report.terminate_accepted);
4405        assert!(sandbox.was_terminated());
4406
4407        let error = sandbox
4408            .resume()
4409            .await
4410            .expect_err("a terminated VM never returns to RUNNING");
4411        assert_eq!(error.kind(), ErrorKind::InvalidArg);
4412        assert!(error.to_string().contains("STATE-11"), "{error}");
4413        assert_eq!(
4414            recorder.call_count("ResumeMicrovm"),
4415            0,
4416            "no resume may reach the wire once the VM was terminated"
4417        );
4418        assert_ne!(
4419            sandbox.lifecycle(),
4420            Lifecycle::Running,
4421            "the lifecycle must not return to RUNNING"
4422        );
4423    }
4424
4425    /// **STATE-9 and STATE-10.** A terminate accepted is TERMINATING with the VM recorded
4426    /// terminated; the platform reporting termination complete is what marks TERMINATED.
4427    ///
4428    /// The two are separate states rather than one because the default teardown does not
4429    /// wait — so TERMINATING is a state a report really ends in, and calling it TERMINATED
4430    /// would claim an observation nobody made.
4431    #[tokio::test]
4432    async fn a_terminate_records_terminating_and_the_completion_report_marks_terminated() {
4433        let (mut sandbox, recorder, _) = launched().await;
4434        recorder.answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
4435
4436        let report = sandbox.terminate(TeardownOpts::default()).await;
4437        assert!(report.terminate_accepted, "STATE-9: the call was accepted");
4438        assert!(sandbox.was_terminated(), "STATE-9: recorded terminated");
4439        assert_eq!(
4440            report.lifecycle,
4441            Some(Lifecycle::Terminating),
4442            "the default teardown does not wait, so TERMINATED is not claimed"
4443        );
4444        assert!(!report.leaked(), "{report:?}");
4445
4446        // And with the wait asked for, STATE-10 is observed.
4447        let (mut sandbox, recorder, _) = launched().await;
4448        recorder
4449            .answer("TerminateMicrovm", Answer::ok(fake::empty_response()))
4450            .answer(
4451                "GetMicrovm",
4452                Answer::ok(fake::microvm_response("TERMINATED", None)),
4453            );
4454        let report = sandbox
4455            .terminate(TeardownOpts::default().waiting_for_terminated())
4456            .await;
4457        assert_eq!(report.lifecycle, Some(Lifecycle::Terminated));
4458        assert_eq!(sandbox.lifecycle(), Lifecycle::Terminated);
4459    }
4460
4461    /// The teardown order is VM, then image, then the log group **last** — asserted on the
4462    /// recorder's ledger rather than on the report, because the order is a property of what
4463    /// was emitted.
4464    ///
4465    /// The log group is last because the service can recreate a group deleted before its
4466    /// image. This crate cannot delete it at all, so the assertion is that it is *named
4467    /// after* the image work rather than that a delete call went out — see
4468    /// `TeardownReport::undeleted`.
4469    #[tokio::test]
4470    async fn teardown_deletes_the_vm_then_the_image_and_names_the_log_group_last() {
4471        let (mut sandbox, recorder, _) = planted();
4472        recorder
4473            .answer(
4474                "CreateMicrovmImage",
4475                Answer::created(fake::create_image_response("agentd-conformance")),
4476            )
4477            .answer(
4478                "GetMicrovmImage",
4479                Answer::ok(fake::get_image_response("agentd-conformance", "CREATED")),
4480            );
4481        sandbox
4482            .build_image(CreateImageRequest::new(
4483                "agentd-conformance",
4484                crate::testing::aarch64_daemon(b"binary"),
4485                "s3://bucket/img.zip",
4486                "arn:aws:iam::123456789012:role/build",
4487            ))
4488            .await
4489            .expect("builds");
4490        answer_launch(&recorder);
4491        sandbox
4492            .run(RunRequest::new())
4493            .await
4494            .expect("launches from the built image");
4495
4496        recorder
4497            .answer("TerminateMicrovm", Answer::ok(fake::empty_response()))
4498            .answer(
4499                "ListMicrovmImageVersions",
4500                Answer::ok(fake::list_versions_response("1")),
4501            )
4502            .answer(
4503                "DeleteMicrovmImage",
4504                Answer::ok(fake::delete_image_response()),
4505            );
4506
4507        let report = sandbox
4508            .terminate(
4509                TeardownOpts::default()
4510                    .deleting_image()
4511                    .deleting_log_group(),
4512            )
4513            .await;
4514        assert!(report.terminate_accepted);
4515        assert_eq!(report.image_deleted, Some(true));
4516
4517        // The ledger, filtered to the three destructive operations.
4518        let order: Vec<&str> = recorder
4519            .operations()
4520            .into_iter()
4521            .filter(|operation| matches!(*operation, "TerminateMicrovm" | "DeleteMicrovmImage"))
4522            .collect();
4523        assert_eq!(
4524            order,
4525            ["TerminateMicrovm", "DeleteMicrovmImage"],
4526            "the VM goes before the image: a terminating VM holds a reference to it"
4527        );
4528
4529        // The log group is named, and named last.
4530        assert_eq!(
4531            report.undeleted,
4532            ["/aws/lambda-microvms/agentd-conformance"],
4533            "{report:?}"
4534        );
4535        assert!(report.leaked());
4536        assert!(
4537            report
4538                .failures
4539                .last()
4540                .expect("a failure")
4541                .contains("log group"),
4542            "the log group's failure has to be the last one recorded: {report:?}"
4543        );
4544        assert!(
4545            report
4546                .failures
4547                .last()
4548                .expect("a failure")
4549                .contains("terraform destroy"),
4550            "the reason it leaks has to be named: {report:?}"
4551        );
4552    }
4553
4554    /// An image delete that fails every attempt lands its identifier in the report rather
4555    /// than raising, so the CLI can emit what was left behind (CLI-6).
4556    ///
4557    /// The identifier rather than a flag is the whole point: a leak nobody can name is a leak
4558    /// nobody can clean up.
4559    #[tokio::test]
4560    async fn a_failing_image_delete_names_what_it_left_behind() {
4561        let (mut sandbox, recorder, _) = planted();
4562        recorder
4563            .answer(
4564                "CreateMicrovmImage",
4565                Answer::created(fake::create_image_response("img")),
4566            )
4567            .answer(
4568                "GetMicrovmImage",
4569                Answer::ok(fake::get_image_response("img", "CREATED")),
4570            );
4571        sandbox
4572            .build_image(CreateImageRequest::new(
4573                "img",
4574                crate::testing::aarch64_daemon(b"binary"),
4575                "s3://bucket/img.zip",
4576                "arn:aws:iam::123456789012:role/build",
4577            ))
4578            .await
4579            .expect("builds");
4580        answer_launch(&recorder);
4581        sandbox.run(RunRequest::new()).await.expect("launches");
4582
4583        recorder
4584            .answer("TerminateMicrovm", Answer::ok(fake::empty_response()))
4585            .answer(
4586                "ListMicrovmImageVersions",
4587                Answer::ok(fake::list_versions_response("1")),
4588            )
4589            .answer(
4590                "DeleteMicrovmImage",
4591                Answer::failure(409, "image is in CREATING"),
4592            );
4593
4594        let mut opts = TeardownOpts::default().deleting_image();
4595        opts.delete_attempts = 3;
4596        opts.delete_backoff = Duration::from_secs(1);
4597        let report = sandbox.terminate(opts).await;
4598
4599        assert_eq!(report.image_deleted, Some(false));
4600        assert_eq!(
4601            report.undeleted,
4602            ["arn:aws:lambda:us-east-1:123456789012:microvm-image:img"],
4603            "{report:?}"
4604        );
4605        assert!(
4606            sandbox.image_exists(),
4607            "the image really is still there, so the flag must say so"
4608        );
4609        assert_eq!(
4610            recorder.call_count("DeleteMicrovmImage"),
4611            3,
4612            "every attempt ran"
4613        );
4614    }
4615
4616    /// A terminate whose own call fails still records the VM as one this client asked to
4617    /// destroy, and names it as undeleted.
4618    ///
4619    /// Recording it is what stops a later resume from being offered against a VM the caller
4620    /// already tried to kill (STATE-11) — the alternative leaves the sandbox looking
4621    /// resumable, which is the worse of the two wrong answers.
4622    #[tokio::test]
4623    async fn a_terminate_whose_call_fails_still_records_the_intent_and_the_leak() {
4624        let (mut sandbox, recorder, _) = launched().await;
4625        recorder.answer(
4626            "TerminateMicrovm",
4627            Answer::failure(500, "InternalServerException"),
4628        );
4629
4630        let report = sandbox.terminate(TeardownOpts::default()).await;
4631        assert!(!report.terminate_accepted);
4632        assert_eq!(report.undeleted, ["mvm-abc123"], "{report:?}");
4633        assert!(sandbox.was_terminated());
4634        assert_eq!(report.lifecycle, Some(Lifecycle::Terminating));
4635        assert!(
4636            !report.failures.is_empty(),
4637            "the swallowed failure is recorded"
4638        );
4639    }
4640
4641    /// A teardown on a sandbox that never launched is a no-op report rather than a panic.
4642    ///
4643    /// The path a caller reaches by tearing down in a `finally` after a launch that failed
4644    /// before any VM existed, which is exactly when a teardown that assumed a VM would turn
4645    /// the real failure into a panic.
4646    #[tokio::test]
4647    async fn a_teardown_before_any_launch_is_an_empty_report() {
4648        let (mut sandbox, recorder, _) = planted();
4649        let report = sandbox.terminate(TeardownOpts::default()).await;
4650        assert!(!report.terminate_accepted);
4651        assert!(!report.leaked());
4652        assert_eq!(report.lifecycle, Some(Lifecycle::Pending));
4653        assert_eq!(recorder.calls().len(), 0);
4654    }
4655
4656    /// A run with no image at all is a precondition error before any call, rather than a
4657    /// launch of an empty identifier.
4658    #[tokio::test]
4659    async fn a_run_with_no_image_is_refused_before_any_call() {
4660        let (mut sandbox, recorder, _) = planted();
4661        let error = sandbox
4662            .run(RunRequest::new())
4663            .await
4664            .expect_err("there is nothing to launch");
4665        assert_eq!(error.kind(), ErrorKind::Precondition);
4666        assert!(error.to_string().contains("build_image first"), "{error}");
4667        assert_eq!(recorder.calls().len(), 0);
4668    }
4669
4670    /// The lifecycle's six states are the symspec's `vm_state` domain, spelled as the service
4671    /// spells them.
4672    ///
4673    /// Asserted rather than assumed because the spelling reaches an error message a reader
4674    /// compares against a `GetMicrovm` response: a lifecycle rendering `Suspended` beside a
4675    /// service saying `SUSPENDED` reads like two different facts.
4676    #[test]
4677    fn the_lifecycle_states_are_the_state_models_domain_in_the_services_spelling() {
4678        let all = [
4679            Lifecycle::Pending,
4680            Lifecycle::Running,
4681            Lifecycle::Suspending,
4682            Lifecycle::Suspended,
4683            Lifecycle::Terminating,
4684            Lifecycle::Terminated,
4685        ];
4686        assert_eq!(
4687            all.map(Lifecycle::as_str),
4688            [
4689                "PENDING",
4690                "RUNNING",
4691                "SUSPENDING",
4692                "SUSPENDED",
4693                "TERMINATING",
4694                "TERMINATED"
4695            ]
4696        );
4697        for state in all {
4698            assert_eq!(state.to_string(), state.as_str());
4699        }
4700        // The four live states are the ones a `Drop` warns about, and TERMINATING is not one
4701        // of them: the platform accepted the terminate, so nobody needs telling.
4702        assert_eq!(
4703            all.iter().filter(|state| state.is_live()).count(),
4704            4,
4705            "a state added to the enum defaults to not-live, which would silence the warning"
4706        );
4707        assert!(!Lifecycle::Terminating.is_live());
4708        assert!(!Lifecycle::Terminated.is_live());
4709    }
4710
4711    /// An agent token is 64 hex characters and never repeats across draws.
4712    ///
4713    /// The distinctness matters because the token is the only thing separating one VM's
4714    /// control API from another's: two VMs sharing a token means either one's caller can
4715    /// drive the other's guest. The token is the source's draw, so a fresh source per launch
4716    /// is fresh tokens; the OS pool's own distinctness is `microvms-edges`'s
4717    /// `the_os_source_draws_distinct_bytes`.
4718    #[test]
4719    fn a_minted_agent_token_is_sixty_four_hex_characters_and_never_repeats() {
4720        let entropy = crate::entropy::testing::SequenceEntropy::new();
4721        let minted: std::collections::HashSet<String> = (0..200)
4722            .map(|_| mint_agent_token(&entropy).expect("scripted"))
4723            .collect();
4724        assert_eq!(minted.len(), 200, "a repeated token is a shared guest");
4725        for token in &minted {
4726            assert_eq!(token.len(), 64, "{token}");
4727            assert!(token.chars().all(|c| c.is_ascii_hexdigit()), "{token}");
4728            assert_ne!(
4729                token,
4730                &"0".repeat(64),
4731                "an all-zero draw is a read that did nothing"
4732            );
4733        }
4734    }
4735
4736    /// A sandbox's `Debug` does not print the agent token.
4737    #[tokio::test]
4738    async fn a_sandbox_debug_does_not_print_the_agent_token() {
4739        let (mut sandbox, recorder, _) = planted();
4740        answer_launch(&recorder);
4741        sandbox
4742            .run(
4743                RunRequest::new()
4744                    .with_image("arn:image")
4745                    .with_agent_token("super-secret-agent-token"),
4746            )
4747            .await
4748            .expect("launches");
4749
4750        let rendered = format!("{sandbox:?}");
4751        assert!(rendered.contains("mvm-abc123"), "{rendered}");
4752        assert!(rendered.contains("Running"), "{rendered}");
4753        assert!(
4754            !rendered.contains("super-secret"),
4755            "the agent token reached a Debug string: {rendered}"
4756        );
4757    }
4758
4759    /// A torn-down sandbox does not warn on drop, and an abandoned one is the case the
4760    /// warning exists for.
4761    ///
4762    /// Asserted on the flag rather than on stderr — capturing another thread's stderr from a
4763    /// test is not something this crate can do without a dependency — so what is pinned is
4764    /// the condition the warning branches on. Both halves, so the branch cannot be
4765    /// vacuously true.
4766    #[tokio::test]
4767    async fn a_torn_down_sandbox_is_distinguishable_from_an_abandoned_one() {
4768        let (mut sandbox, recorder, _) = launched().await;
4769        assert!(
4770            sandbox.lifecycle().is_live() && !sandbox.torn_down,
4771            "an abandoned live VM is what the drop warning is for"
4772        );
4773
4774        recorder.answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
4775        sandbox.terminate(TeardownOpts::default()).await;
4776        assert!(
4777            sandbox.torn_down,
4778            "terminate must mark the sandbox torn down"
4779        );
4780        assert!(
4781            !sandbox.lifecycle().is_live(),
4782            "and the lifecycle must no longer read as live"
4783        );
4784    }
4785
4786    #[tokio::test]
4787    async fn stable_launch_key_and_payload_survive_a_fresh_supervisor() {
4788        let mut bodies = Vec::new();
4789        for _ in 0..2 {
4790            let (mut sandbox, recorder, _) = planted();
4791            answer_launch(&recorder);
4792            let mut request = RunRequest::new().with_image("arn:image");
4793            request.client_token = Some("one-unique-job-launch".into());
4794            request.agent_token = Some("persisted-private-secret".into());
4795            sandbox.run(request).await.expect("accepted");
4796            bodies.push(recorder.first_body("RunMicrovm"));
4797        }
4798        assert_eq!(bodies[0]["clientToken"], "one-unique-job-launch");
4799        assert_eq!(bodies[0], bodies[1]);
4800    }
4801
4802    #[tokio::test]
4803    async fn unsafe_or_malformed_stable_launch_is_refused_without_calls() {
4804        for (token, secret, identity) in [
4805            ("key".to_string(), None, false),
4806            ("key".to_string(), Some("secret".into()), true),
4807            ("".to_string(), Some("secret".into()), false),
4808            ("x".repeat(129), Some("secret".into()), false),
4809            ("line\nbreak".to_string(), Some("secret".into()), false),
4810        ] {
4811            let (mut sandbox, recorder, _) = planted();
4812            let mut request = RunRequest::new().with_image("arn:image");
4813            request.client_token = Some(token);
4814            request.agent_token = secret;
4815            request.identity = identity;
4816            let error = sandbox.run(request).await.expect_err("invalid");
4817            assert_eq!(error.kind(), ErrorKind::InvalidArg);
4818            assert!(recorder.calls().is_empty());
4819        }
4820    }
4821}