microsandbox 0.6.8

`microsandbox` is the core library for the microsandbox project.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! Cloud sandbox lifecycle: the [`SandboxBackend`] impl for [`CloudBackend`]
//! plus the conversions between the SDK's [`SandboxConfig`] and the cloud's
//! create wire shape.

use std::sync::Arc;
use std::time::Duration;

use futures::future::BoxFuture;

use super::CloudBackend;
use crate::backend::{
    Backend,
    sandbox::{LogStream, MetricsStream, SandboxBackend},
};
use crate::error::{Operation, UnsupportedReason};
use crate::logs::{LogEntry, LogOptions, LogStreamOptions};
use crate::sandbox::metrics::SandboxMetrics;
use crate::sandbox::{
    RootfsSource, Sandbox, SandboxConfig, SandboxHandle, SandboxListBuilder, SandboxPage,
    SandboxStatus,
};
use crate::{MicrosandboxError, MicrosandboxResult};
use microsandbox_image::RegistryAuth;
use microsandbox_types::{
    CloudCreateSandboxRequest, CloudCreateSandboxResponse, CloudSandboxStatus,
};

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Wire body for the cloud's create route: the shared create envelope with
/// the cloud-only fields that ride beside it.
#[derive(Debug, Clone, serde::Serialize)]
pub(in crate::backend) struct CloudCreateBody {
    /// The shared sandbox spec, flattened onto the body.
    #[serde(flatten)]
    pub envelope: CloudCreateSandboxRequest,
    /// Requested globally-unique slug; the cloud assigns one when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slug: Option<String>,
    /// Registry-credential selection for the image pull, derived from the
    /// config's [`RegistryAuth`]. Omitted (`None`) lets the cloud pick the
    /// stored credential configured for the image's registry host.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registry: Option<CloudRegistrySelection>,
}

/// Wire shape of the cloud's registry-credential selection.
///
/// `auto` is expressed by omitting the field.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub(in crate::backend) enum CloudRegistrySelection {
    /// Pull anonymously, even when a stored credential matches the registry.
    Anonymous,
    /// Credentials for this sandbox's image pull only; the cloud applies them
    /// to the registry host derived from the image reference and never stores
    /// them with the org's registry credentials.
    Inline {
        /// Registry username.
        username: String,
        /// Registry password or access token.
        password: String,
    },
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

impl SandboxBackend for CloudBackend {
    fn create<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        config: SandboxConfig,
        start: bool,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>> {
        Box::pin(async move {
            let req = CloudCreateBody::try_from(config.clone())?;
            let cloud = CloudBackend::create_sandbox(self, &req, start).await?;
            if start {
                ensure_cloud_sandbox_ready(&cloud)?;
            }
            Ok(Sandbox::from_cloud(backend, cloud, config))
        })
    }

    fn create_detached<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        config: SandboxConfig,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>> {
        // Cloud has no notion of "detached" — the sandbox lifecycle is owned
        // by msb-cloud, not by this process. Reuse the eager-start path.
        Box::pin(async move {
            let req = CloudCreateBody::try_from(config.clone())?;
            let cloud = CloudBackend::create_sandbox(self, &req, true).await?;
            ensure_cloud_sandbox_ready(&cloud)?;
            Ok(Sandbox::from_cloud(backend, cloud, config))
        })
    }

    fn start<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>> {
        Box::pin(async move {
            let current = CloudBackend::get_sandbox(self, name).await?;
            let config = sandbox_config_from_cloud(&current);
            let cloud = CloudBackend::start_sandbox(self, name).await?;
            ensure_cloud_sandbox_ready(&cloud)?;
            Ok(Sandbox::from_cloud(backend, cloud, config))
        })
    }

    fn start_detached<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>> {
        // Cloud start is detached by definition — the sandbox keeps running
        // after this process exits. Same code path as `start`.
        Box::pin(async move {
            let current = CloudBackend::get_sandbox(self, name).await?;
            let config = sandbox_config_from_cloud(&current);
            let cloud = CloudBackend::start_sandbox(self, name).await?;
            ensure_cloud_sandbox_ready(&cloud)?;
            Ok(Sandbox::from_cloud(backend, cloud, config))
        })
    }

    fn get<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<SandboxHandle>> {
        Box::pin(async move {
            let cloud = CloudBackend::get_sandbox(self, name).await?;
            SandboxHandle::from_cloud(backend, cloud)
        })
    }

    fn list<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        query: SandboxListBuilder,
    ) -> BoxFuture<'a, MicrosandboxResult<SandboxPage>> {
        Box::pin(async move {
            let page = CloudBackend::list_sandboxes(self, &query).await?;
            let sandboxes = page
                .data
                .into_iter()
                .map(|sb| SandboxHandle::from_cloud(backend.clone(), sb))
                .collect::<MicrosandboxResult<Vec<_>>>()?;
            Ok(SandboxPage {
                sandboxes,
                next_cursor: page.next_cursor,
            })
        })
    }

    fn remove<'a>(
        &'a self,
        _backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            CloudBackend::destroy_sandbox(self, name).await?;
            Ok(())
        })
    }

    fn stop<'a>(
        &'a self,
        _backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            CloudBackend::stop_sandbox(self, name).await?;
            Ok(())
        })
    }

    fn kill<'a>(
        &'a self,
        _backend: Arc<dyn Backend>,
        _name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            Err(MicrosandboxError::unsupported(
                Operation::SandboxKill,
                UnsupportedReason::UseInstead(Operation::SandboxStop),
            ))
        })
    }

    fn drain<'a>(
        &'a self,
        _backend: Arc<dyn Backend>,
        _name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            Err(MicrosandboxError::unsupported(
                Operation::SandboxDrain,
                UnsupportedReason::UseInstead(Operation::SandboxStop),
            ))
        })
    }

    fn logs<'a>(
        &'a self,
        _backend: Arc<dyn Backend>,
        _name: &'a str,
        _opts: &'a LogOptions,
    ) -> BoxFuture<'a, MicrosandboxResult<Vec<LogEntry>>> {
        Box::pin(async move { CloudBackend::logs(self, _name, _opts).await })
    }

    fn log_stream<'a>(
        &'a self,
        _backend: Arc<dyn Backend>,
        name: &'a str,
        opts: &'a LogStreamOptions,
    ) -> BoxFuture<'a, MicrosandboxResult<LogStream>> {
        Box::pin(async move { CloudBackend::log_stream(self, name, opts).await })
    }

    fn metrics<'a>(
        &'a self,
        _backend: Arc<dyn Backend>,
        _name: &'a str,
        _config: &'a SandboxConfig,
    ) -> BoxFuture<'a, MicrosandboxResult<SandboxMetrics>> {
        Box::pin(async move { Err(MicrosandboxError::local_only(Operation::SandboxMetrics)) })
    }

    fn metrics_stream(
        &self,
        _backend: Arc<dyn Backend>,
        _name: String,
        _config: SandboxConfig,
        _interval: Duration,
    ) -> MetricsStream {
        Box::pin(futures::stream::once(async {
            Err(MicrosandboxError::local_only(
                Operation::SandboxMetricsStream,
            ))
        }))
    }
}

impl TryFrom<SandboxConfig> for CloudCreateBody {
    type Error = MicrosandboxError;

    /// Build the cloud create body from an SDK config, rejecting the
    /// create-time options the cloud does not accept.
    fn try_from(config: SandboxConfig) -> MicrosandboxResult<Self> {
        if config.replace_existing {
            return Err(MicrosandboxError::unsupported(
                Operation::SandboxCreate,
                UnsupportedReason::ConfigField("replace"),
            ));
        }
        if config.insecure {
            return Err(MicrosandboxError::unsupported(
                Operation::SandboxCreate,
                UnsupportedReason::ConfigField("insecure"),
            ));
        }
        if !config.ca_certs.is_empty() {
            return Err(MicrosandboxError::unsupported(
                Operation::SandboxCreate,
                UnsupportedReason::ConfigField("ca_certs"),
            ));
        }
        #[cfg(feature = "net")]
        {
            // Only flag user-set opt-in fields the cloud's create contract does
            // not accept (published ports, custom DNS resolvers, host-CA trust).
            // Policy and secrets ride in the request's network section, and the
            // default `NetworkConfig` ships with a baseline policy plus built-in
            // DNS settings, so comparing those would always trigger.
            let net = config.local_network_config()?;
            if !net.ports.is_empty() || !net.dns.nameservers.is_empty() || net.trust_host_cas {
                return Err(MicrosandboxError::unsupported(
                    Operation::SandboxCreate,
                    UnsupportedReason::ConfigField("network ports / custom DNS / host-CA trust"),
                ));
            }
        }

        // Cloud only supports OCI rootfs; reject the local-only rootfs kinds before
        // handing the spec to the control plane. Borrow so the spec isn't moved.
        match &config.spec.image {
            RootfsSource::Oci(_) => {}
            RootfsSource::Bind { .. } => {
                return Err(MicrosandboxError::unsupported(
                    Operation::SandboxCreate,
                    UnsupportedReason::ConfigField("host-directory rootfs"),
                ));
            }
            RootfsSource::DiskImage { .. } => {
                return Err(MicrosandboxError::unsupported(
                    Operation::SandboxCreate,
                    UnsupportedReason::ConfigField("disk-image rootfs"),
                ));
            }
        }

        // registry_auth converts into the cloud's credential selection: absent
        // means the cloud picks the stored credential configured for the
        // image's registry host (mirroring the local fallback to configured
        // registries), Anonymous forces an unauthenticated pull, and Basic
        // credentials ride as sandbox-scoped inline credentials.
        let registry = match &config.registry_auth {
            None => None,
            Some(RegistryAuth::Anonymous) => Some(CloudRegistrySelection::Anonymous),
            Some(RegistryAuth::Basic { username, password }) => {
                Some(CloudRegistrySelection::Inline {
                    username: username.clone(),
                    password: password.clone(),
                })
            }
        };

        // The cloud request composes the shared spec verbatim plus the cloud-only
        // fields that have no place in it (slug, registry-credential selection).
        Ok(Self {
            slug: config.slug,
            registry,
            envelope: CloudCreateSandboxRequest::from(config.spec),
        })
    }
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

/// Map [`CloudSandboxStatus`] to the SDK's [`SandboxStatus`] enum.
///
/// `Stopping` collapses to `Draining` (microsandbox uses `Draining` for
/// the graceful-stop state); `Failed` collapses to `Crashed`. All other
/// variants map 1:1.
pub(crate) fn cloud_status_to_sandbox_status(s: CloudSandboxStatus) -> SandboxStatus {
    match s {
        CloudSandboxStatus::Created => SandboxStatus::Created,
        CloudSandboxStatus::Starting => SandboxStatus::Starting,
        CloudSandboxStatus::Running => SandboxStatus::Running,
        CloudSandboxStatus::Stopping => SandboxStatus::Draining,
        CloudSandboxStatus::Stopped => SandboxStatus::Stopped,
        CloudSandboxStatus::Failed => SandboxStatus::Crashed,
    }
}

/// Enforce the cross-backend lifecycle contract: a successful create or start
/// returns a sandbox whose agent-facing operations are immediately usable.
fn ensure_cloud_sandbox_ready(cloud: &CloudCreateSandboxResponse) -> MicrosandboxResult<()> {
    match cloud.status {
        CloudSandboxStatus::Running => Ok(()),
        CloudSandboxStatus::Failed => Err(MicrosandboxError::Runtime(format!(
            "cloud sandbox {:?} failed to start: {}",
            cloud.name,
            cloud
                .last_failure_message
                .as_deref()
                .unwrap_or("the cloud control plane reported no failure reason")
        ))),
        CloudSandboxStatus::Starting => Err(MicrosandboxError::Runtime(format!(
            "cloud sandbox {:?} did not reach running before the readiness wait expired",
            cloud.name
        ))),
        status => Err(MicrosandboxError::Runtime(format!(
            "cloud sandbox {:?} entered {status:?} instead of running",
            cloud.name
        ))),
    }
}

/// Build the best available runtime config for a sandbox the SDK did not
/// create itself.
///
/// The cloud owns its response projection and may omit `spec` or return a
/// curated shape. A complete shared cloud spec is decoded when available;
/// otherwise agent operations use SDK defaults. Lifecycle start must never
/// depend on the optional inspection projection.
fn sandbox_config_from_cloud(cloud: &CloudCreateSandboxResponse) -> SandboxConfig {
    sandbox_config_from_cloud_spec(&cloud.name, cloud.spec.clone())
}

/// Decode the server-owned spec projection carried by a cloud handle.
///
/// Agent operations only require a best-effort runtime config. The response
/// projection may be absent or curated, so reconnecting must preserve the
/// lifecycle contract without requiring a complete create request.
pub(crate) fn sandbox_config_from_cloud_spec(
    name: &str,
    spec: Option<serde_json::Value>,
) -> SandboxConfig {
    let mut config = spec
        .and_then(|value| {
            serde_json::from_value::<microsandbox_types::CloudSandboxSpec>(value).ok()
        })
        .and_then(|spec| crate::sandbox::SandboxSpec::try_from(spec).ok())
        .map(|spec| SandboxConfig {
            spec,
            ..Default::default()
        })
        .unwrap_or_default();

    // The top-level response name is canonical even when a complete spec was
    // unavailable or carried stale inspection data.
    config.spec.name = name.to_string();
    config
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use microsandbox_types::CloudSandboxSpec;

    use super::*;
    use crate::sandbox::{EnvVar, OciRootfsSource, RootDisk, SandboxBuilder, SandboxSpec};

    #[tokio::test]
    async fn cloud_create_request_maps_common_fields() {
        let config = SandboxBuilder::new("agent-1")
            .image("python:3.12")
            .cpus(2)
            .memory(1024)
            .env("A", "B")
            .workdir("/app")
            .shell("/bin/bash")
            .entrypoint(["python", "-u"])
            .build()
            .await
            .unwrap();

        let req = CloudCreateBody::try_from(config).unwrap();

        // The request carries the cloud wire spec, so assert on `envelope.spec`.
        let spec = &req.envelope.spec;
        assert_eq!(spec.name, "agent-1");
        assert!(
            matches!(spec.image, microsandbox_types::CloudRootfsSource::Oci { ref reference } if reference == "python:3.12")
        );
        assert_eq!(spec.resources.vcpus, 2);
        assert_eq!(spec.resources.memory_mib, 1024);
        assert_eq!(spec.env, vec![EnvVar::new("A", "B")]);
        assert_eq!(spec.runtime.workdir.as_deref(), Some("/app"));
        assert_eq!(spec.runtime.shell.as_deref(), Some("/bin/bash"));
        assert_eq!(
            spec.runtime.entrypoint,
            Some(vec!["python".to_string(), "-u".to_string()])
        );
        assert_eq!(req.slug, None);
        assert_eq!(req.registry, None);
    }

    #[test]
    fn cloud_create_body_serializes_slug_and_registry_beside_spec() {
        let mut config = base_cloud_config();
        config.slug = Some("brave-otter".into());
        config.registry_auth = Some(microsandbox_image::RegistryAuth::Anonymous);

        let req = CloudCreateBody::try_from(config).unwrap();
        let json = serde_json::to_value(&req).unwrap();

        // The envelope flattens onto the body; slug/registry ride beside it.
        // An anonymous registry_auth converts to the anonymous selection.
        assert_eq!(json["name"], "agent-1");
        assert_eq!(json["image"]["type"], "oci");
        assert_eq!(json["image"]["reference"], "python:3.12");
        assert_eq!(json["slug"], "brave-otter");
        assert_eq!(json["registry"]["mode"], "anonymous");
    }

    #[test]
    fn cloud_create_body_omits_unset_slug_and_registry() {
        let req = CloudCreateBody::try_from(base_cloud_config()).unwrap();
        let json = serde_json::to_value(&req).unwrap();

        assert!(json.get("slug").is_none());
        assert!(json.get("registry").is_none());
    }

    #[tokio::test]
    async fn cloud_create_request_rejects_disk_image_rootfs() {
        let config = SandboxConfig {
            spec: SandboxSpec {
                name: "agent-1".into(),
                image: RootfsSource::DiskImage {
                    path: "rootfs.img".into(),
                    format: crate::sandbox::DiskImageFormat::Raw,
                    fstype: None,
                },
                ..Default::default()
            },
            ..Default::default()
        };

        let err = CloudCreateBody::try_from(config).unwrap_err();
        assert!(matches!(err, MicrosandboxError::Unsupported { .. }));
    }

    /// Build a minimal OCI-backed [`SandboxConfig`] suitable for the
    /// cloud-reject tests. Each test then mutates one field and asserts
    /// the resulting request errors with `Unsupported`.
    fn base_cloud_config() -> SandboxConfig {
        SandboxConfig {
            spec: SandboxSpec {
                name: "agent-1".into(),
                image: RootfsSource::Oci(OciRootfsSource {
                    reference: "python:3.12".into(),
                    root_disk: None,
                }),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn cloud_create_request_rejects_replace_existing() {
        let mut config = base_cloud_config();
        config.replace_existing = true;
        let err = CloudCreateBody::try_from(config).unwrap_err();
        assert!(matches!(err, MicrosandboxError::Unsupported { .. }));
    }

    #[test]
    fn cloud_create_request_maps_previously_deferred_spec_fields() {
        // These spec fields ride in the create body now; assert they map
        // instead of erroring.
        let mut config = base_cloud_config();
        config.spec.init = Some(crate::sandbox::HandoffInit {
            cmd: "/sbin/init".into(),
            args: Vec::new(),
            env: Vec::new(),
        });
        config.spec.pull_policy = crate::sandbox::PullPolicy::Always;
        config.spec.runtime.cmd = Some(vec!["python".into(), "app.py".into()]);
        config.spec.rlimits.push(crate::sandbox::exec::Rlimit {
            resource: crate::sandbox::exec::RlimitResource::Nofile,
            soft: 1024,
            hard: 2048,
        });
        if let RootfsSource::Oci(oci) = &mut config.spec.image {
            oci.root_disk = Some(RootDisk::managed(8192));
        }

        let req = CloudCreateBody::try_from(config).unwrap();

        let spec = &req.envelope.spec;
        assert!(spec.init.is_some());
        assert_eq!(
            spec.pull_policy,
            microsandbox_types::CloudPullPolicy::Always
        );
        assert_eq!(
            spec.runtime.cmd,
            Some(vec!["python".to_string(), "app.py".to_string()])
        );
        assert_eq!(spec.rlimits.len(), 1);
        assert_eq!(spec.resources.disk_size_mib, Some(8192));
    }

    #[test]
    fn cloud_create_body_maps_basic_registry_auth_to_inline() {
        let mut config = base_cloud_config();
        config.registry_auth = Some(microsandbox_image::RegistryAuth::Basic {
            username: "u".into(),
            password: "p".into(),
        });
        let req = CloudCreateBody::try_from(config).unwrap();
        let json = serde_json::to_value(&req).unwrap();

        assert_eq!(json["registry"]["mode"], "inline");
        assert_eq!(json["registry"]["username"], "u");
        assert_eq!(json["registry"]["password"], "p");
        // The credentials ride only in the registry section of the body.
        let body = serde_json::to_string(&json).unwrap();
        assert_eq!(body.matches("\"p\"").count(), 1);
    }

    #[test]
    fn cloud_create_request_rejects_insecure() {
        let mut config = base_cloud_config();
        config.insecure = true;
        let err = CloudCreateBody::try_from(config).unwrap_err();
        assert!(matches!(err, MicrosandboxError::Unsupported { .. }));
    }

    #[test]
    fn cloud_create_request_rejects_ca_certs() {
        let mut config = base_cloud_config();
        config
            .ca_certs
            .push(b"-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----".to_vec());
        let err = CloudCreateBody::try_from(config).unwrap_err();
        assert!(matches!(err, MicrosandboxError::Unsupported { .. }));
    }

    #[cfg(feature = "net")]
    #[test]
    fn cloud_create_request_rejects_published_ports() {
        let mut config = base_cloud_config();
        config
            .spec
            .network
            .ports
            .push(microsandbox_types::PublishedPortSpec {
                host_port: 8080,
                guest_port: 80,
                protocol: microsandbox_types::PortProtocol::Tcp,
                host_bind: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST).to_string(),
            });
        let err = CloudCreateBody::try_from(config).unwrap_err();
        assert!(matches!(err, MicrosandboxError::Unsupported { .. }));
    }

    #[test]
    fn sandbox_config_from_cloud_round_trips_d13_fields() {
        // The cloud response carries the wire `CloudSandboxSpec`, which converts
        // back into the shared `SandboxSpec`. Populate a full spec and assert the
        // fields the wire spec carries survive the round-trip; fields with no
        // representation on `CloudSandboxSpec` (like the runtime hostname) are not
        // carried back.
        let mut spec = SandboxSpec {
            name: "agent-1".into(),
            image: RootfsSource::Oci(OciRootfsSource {
                reference: "python:3.12".into(),
                root_disk: None,
            }),
            env: vec![EnvVar::new("A", "B")],
            ..Default::default()
        };
        spec.resources.cpus = 4;
        spec.resources.memory_mib = 2048;
        spec.runtime.workdir = Some("/app".into());
        spec.runtime.shell = Some("/bin/bash".into());
        spec.runtime.entrypoint = Some(vec!["python".into(), "-u".into()]);
        spec.runtime.hostname = Some("worker".into());
        spec.runtime.user = Some("appuser".into());
        spec.runtime.log_level = Some(microsandbox_types::SandboxLogLevel::Debug);
        spec.runtime
            .scripts
            .insert("setup".into(), "echo hi".into());
        spec.lifecycle.max_duration_secs = Some(3600);
        spec.lifecycle.idle_timeout_secs = Some(600);

        let cloud = CloudCreateSandboxResponse {
            id: "00000000-0000-0000-0000-000000000002".into(),
            org_id: "00000000-0000-0000-0000-000000000001".into(),
            name: "agent-1".into(),
            slug: "brave-otter".into(),
            status: CloudSandboxStatus::Running,
            status_reason: None,
            spec: Some(serde_json::to_value(CloudSandboxSpec::from(spec)).unwrap()),
            ephemeral: true,
            created_at: chrono::Utc::now(),
            started_at: None,
            stopped_at: None,
            last_failure_message: None,
        };

        let config = sandbox_config_from_cloud(&cloud);

        assert_eq!(config.spec.name, "agent-1");
        assert!(
            matches!(config.spec.image, RootfsSource::Oci(ref s) if s.reference == "python:3.12")
        );
        assert_eq!(config.spec.resources.cpus, 4);
        assert_eq!(config.spec.resources.memory_mib, 2048);
        assert_eq!(
            config.spec.env,
            vec![EnvVar::new("A", "B")],
            "env round-trip"
        );
        assert_eq!(config.spec.runtime.workdir.as_deref(), Some("/app"));
        assert_eq!(config.spec.runtime.shell.as_deref(), Some("/bin/bash"));
        assert_eq!(
            config.spec.runtime.entrypoint,
            Some(vec!["python".to_string(), "-u".to_string()])
        );
        assert_eq!(config.spec.runtime.hostname, None);
        assert_eq!(config.spec.runtime.user.as_deref(), Some("appuser"));
        assert_eq!(
            config.spec.runtime.log_level,
            Some(microsandbox_types::SandboxLogLevel::Debug),
        );
        assert_eq!(
            config.spec.runtime.scripts.get("setup"),
            Some(&"echo hi".to_string())
        );
        assert_eq!(config.spec.lifecycle.max_duration_secs, Some(3600));
        assert_eq!(config.spec.lifecycle.idle_timeout_secs, Some(600));
    }

    #[test]
    fn sandbox_config_from_cloud_does_not_require_spec() {
        let mut cloud = cloud_response(CloudSandboxStatus::Stopped);
        cloud.spec = None;

        let config = sandbox_config_from_cloud(&cloud);

        assert_eq!(config.spec.name, cloud.name);
        assert_eq!(config.spec.runtime.shell, None);
    }

    #[test]
    fn sandbox_config_from_cloud_accepts_curated_spec() {
        let mut cloud = cloud_response(CloudSandboxStatus::Stopped);
        cloud.spec = Some(serde_json::json!({
            "image": "alpine:3.19",
            "resources": { "vcpus": 1 }
        }));

        let config = sandbox_config_from_cloud(&cloud);

        assert_eq!(config.spec.name, cloud.name);
        assert_eq!(config.spec.runtime.shell, None);
    }

    #[test]
    fn cloud_status_maps_created_and_starting_one_to_one() {
        assert_eq!(
            cloud_status_to_sandbox_status(CloudSandboxStatus::Created),
            SandboxStatus::Created,
        );
        assert_eq!(
            cloud_status_to_sandbox_status(CloudSandboxStatus::Starting),
            SandboxStatus::Starting,
        );
        assert_eq!(
            cloud_status_to_sandbox_status(CloudSandboxStatus::Running),
            SandboxStatus::Running,
        );
        assert_eq!(
            cloud_status_to_sandbox_status(CloudSandboxStatus::Stopping),
            SandboxStatus::Draining,
        );
        assert_eq!(
            cloud_status_to_sandbox_status(CloudSandboxStatus::Stopped),
            SandboxStatus::Stopped,
        );
        assert_eq!(
            cloud_status_to_sandbox_status(CloudSandboxStatus::Failed),
            SandboxStatus::Crashed,
        );
    }

    #[test]
    fn cloud_lifecycle_readiness_accepts_only_running() {
        assert!(ensure_cloud_sandbox_ready(&cloud_response(CloudSandboxStatus::Running)).is_ok());

        for status in [
            CloudSandboxStatus::Created,
            CloudSandboxStatus::Starting,
            CloudSandboxStatus::Stopping,
            CloudSandboxStatus::Stopped,
            CloudSandboxStatus::Failed,
        ] {
            assert!(ensure_cloud_sandbox_ready(&cloud_response(status)).is_err());
        }
    }

    /// Minimal response fixture for create-readiness assertions.
    fn cloud_response(status: CloudSandboxStatus) -> CloudCreateSandboxResponse {
        CloudCreateSandboxResponse {
            id: "00000000-0000-0000-0000-000000000002".into(),
            org_id: "00000000-0000-0000-0000-000000000001".into(),
            name: "agent-1".into(),
            slug: "brave-otter".into(),
            status,
            status_reason: None,
            spec: None,
            ephemeral: true,
            created_at: chrono::Utc::now(),
            started_at: None,
            stopped_at: None,
            last_failure_message: (status == CloudSandboxStatus::Failed)
                .then(|| "image pull failed".into()),
        }
    }
}