devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! Apple's `container` CLI (github.com/apple/container, 1.x). Shares the
//! `run`/`exec`/`build`/`start`/`stop` surface with docker, but `inspect` and
//! `ls` are JSON-only (no Go templates, no `--filter`), there is no `network
//! connect`, no `--network-alias` and no `top`, and `logs` tails with `-n`.
//! JSON keys are the Swift property names verbatim (no key strategy).

use std::collections::BTreeMap;

use anyhow::{bail, Context, Result};
use serde::Deserialize;

use super::{
    human_bytes, identity, without_self_ps, Backend, ContainerRow, ProcList, ServiceEndpoint, StatsRow,
    PROC_PS_ARGS,
};

pub struct AppleContainer;

/// Element of `container inspect` / `container ls --format json`.
#[derive(Debug, Deserialize)]
struct ManagedContainer {
    id: String,
    #[serde(default)]
    configuration: Configuration,
    #[serde(default)]
    status: Status,
}

#[derive(Debug, Default, Deserialize)]
struct Configuration {
    #[serde(default)]
    image: Option<Image>,
    #[serde(default)]
    labels: BTreeMap<String, String>,
    /// Shape not pinned; scanned for a `hostPort` key.
    #[serde(rename = "publishedPorts", default)]
    published_ports: Vec<serde_json::Value>,
}

#[derive(Debug, Deserialize)]
struct Image {
    #[serde(default)]
    reference: String,
}

#[derive(Debug, Default, Deserialize)]
struct Status {
    /// `running` | `stopped` | `stopping` | `unknown`.
    #[serde(default)]
    state: String,
    #[serde(default)]
    networks: Vec<Attachment>,
}

#[derive(Debug, Deserialize)]
struct Attachment {
    /// CIDR form, e.g. `192.168.64.3/24`.
    #[serde(rename = "ipv4Address", default)]
    ipv4_address: Option<String>,
}

impl ManagedContainer {
    fn into_row(self) -> ContainerRow {
        let host_ports = self
            .configuration
            .published_ports
            .iter()
            .filter_map(|p| p.get("hostPort"))
            .filter_map(|p| p.as_u64().map(|n| n.to_string()).or_else(|| p.as_str().map(str::to_string)))
            .collect();
        ContainerRow {
            name: self.id,
            image: self.configuration.image.map(|i| i.reference).unwrap_or_default(),
            status: self.status.state.clone(),
            state: self.status.state,
            labels: self.configuration.labels,
            host_ports,
        }
    }

    /// First IPv4 address without its prefix length.
    fn ipv4(&self) -> Option<&str> {
        self.status
            .networks
            .iter()
            .find_map(|a| a.ipv4_address.as_deref())
            .map(|cidr| cidr.split('/').next().unwrap_or(cidr))
    }
}

fn parse_containers(json: &str) -> Result<Vec<ManagedContainer>> {
    serde_json::from_str(json).context("unexpected `container` JSON")
}

impl AppleContainer {
    /// `inspect <name>`, `None` when the container does not exist (inspect
    /// exits non-zero for unknown ids).
    fn inspect_one(&self, name: &str) -> Result<Option<ManagedContainer>> {
        let Ok(out) = self.output_quiet(&["inspect", name]) else {
            return Ok(None);
        };
        Ok(parse_containers(&out)?.into_iter().next())
    }
}

/// Element of `container stats --format json`. Counters are raw; a single
/// sample has no CPU percentage.
#[derive(Debug, Deserialize)]
struct Stats {
    id: String,
    #[serde(rename = "memoryUsageBytes")]
    memory_usage_bytes: Option<u64>,
    #[serde(rename = "memoryLimitBytes")]
    memory_limit_bytes: Option<u64>,
}

fn parse_stats(json: &str) -> Result<Vec<StatsRow>> {
    let stats: Vec<Stats> = serde_json::from_str(json).context("unexpected `container stats` JSON")?;
    Ok(stats
        .into_iter()
        .map(|s| StatsRow {
            name: s.id,
            cpu: "-".into(),
            mem: match (s.memory_usage_bytes, s.memory_limit_bytes) {
                (Some(used), Some(limit)) => {
                    format!("{} / {}", human_bytes(used), human_bytes(limit))
                }
                (Some(used), None) => human_bytes(used),
                _ => "-".into(),
            },
        })
        .collect())
}

/// Element of `container system version --format json`: `[cli, server?]`.
#[derive(Debug, Deserialize)]
struct VersionInfo {
    version: String,
}

fn parse_version(json: &str) -> Result<String> {
    let versions: Vec<VersionInfo> =
        serde_json::from_str(json).context("unexpected `container system version` JSON")?;
    // The API server entry (index 1) is present only when it answers; fall
    // back to the CLI's own version.
    versions
        .last()
        .map(|v| v.version.clone())
        .context("empty version list")
}

/// Aliases and addresses are interpolated into a shell script; keep them to
/// hostname/IP characters so quoting can't be broken.
fn hosts_token_ok(s: &str) -> bool {
    !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | ':'))
}

/// `sh -c` script that replaces `alias`'s `/etc/hosts` line with `ip alias`.
/// Rewrites in place (no rename) so it also works when `/etc/hosts` is a mount.
fn hosts_script(entries: &[(String, String)]) -> String {
    let mut script = String::from("set -e; h=/etc/hosts; ");
    for (ip, alias) in entries {
        script.push_str(&format!(
            "t=$(grep -v '[[:space:]]{alias}$' $h || true); printf '%s\\n{ip} {alias}\\n' \"$t\" > $h; "
        ));
    }
    script
}

impl Backend for AppleContainer {
    fn name(&self) -> &'static str {
        "container"
    }

    fn bin(&self) -> &'static str {
        "container"
    }

    fn is_running(&self, container: &str) -> Result<Option<bool>> {
        Ok(self.inspect_one(container)?.map(|c| c.status.state == "running"))
    }

    fn label(&self, container: &str, key: &str) -> Result<Option<String>> {
        Ok(self
            .inspect_one(container)?
            .and_then(|c| c.configuration.labels.get(key).cloned())
            .filter(|v| !v.is_empty()))
    }

    fn network_exists(&self, network: &str) -> Result<bool> {
        Ok(self.output_quiet(&["network", "inspect", network]).is_ok())
    }

    fn inspect_json(&self, container: &str) -> Result<String> {
        self.output_quiet(&["inspect", container])
    }

    fn list(&self, all: bool, name_prefix: &str) -> Result<Vec<ContainerRow>> {
        let mut args = vec!["ls"];
        if all {
            args.push("--all");
        }
        args.extend(["--format", "json"]);
        let out = self.output_quiet(&args)?;
        Ok(parse_containers(&out)?
            .into_iter()
            .filter(|c| c.id.starts_with(name_prefix))
            .map(ManagedContainer::into_row)
            .collect())
    }

    fn stats(&self) -> Result<Vec<StatsRow>> {
        let out = self.output_quiet(&["stats", "--no-stream", "--format", "json"])?;
        parse_stats(&out)
    }

    fn server_version(&self) -> Result<String> {
        let out = self.output_quiet(&["system", "version", "--format", "json"])?;
        parse_version(&out)
    }

    fn logs_tail(&self, container: &str, n: usize) -> Result<String> {
        self.output_merged(&["logs", "-n", &n.to_string(), container])
    }

    fn proc_list(&self, container: &str) -> Result<ProcList> {
        // No `top` subcommand; ask procps inside the container instead, so pids
        // are container-namespace and signalable.
        let mut exec = vec!["exec", container];
        exec.extend_from_slice(&PROC_PS_ARGS);
        let text = self.output_quiet(&exec)?;
        Ok(ProcList { text: without_self_ps(&text), container_pids: true })
    }

    fn remove_force(&self, container: &str) -> Result<i32> {
        self.run_inherit(&["delete", "--force", container])
    }

    fn network_run_args(&self, networks: &[String]) -> Vec<String> {
        networks
            .iter()
            .flat_map(|n| ["--network".to_string(), n.clone()])
            .collect()
    }

    fn connect_networks(&self, _container: &str, _networks: &[String]) -> Result<()> {
        // All networks were attached at `run`; there is no `network connect`.
        Ok(())
    }

    fn service_alias_args(&self, _alias: &str) -> Vec<String> {
        Vec::new()
    }

    fn wire_service_dns(&self, container: &str, endpoints: &[ServiceEndpoint]) -> Result<()> {
        if endpoints.is_empty() {
            return Ok(());
        }
        let mut entries = Vec::with_capacity(endpoints.len());
        for endpoint in endpoints {
            let service = self
                .inspect_one(&endpoint.container)?
                .with_context(|| format!("service container `{}` not found", endpoint.container))?;
            let ip = service.ipv4().with_context(|| {
                format!("service container `{}` has no IPv4 address yet", endpoint.container)
            })?;
            if !hosts_token_ok(&endpoint.alias) || !hosts_token_ok(ip) {
                bail!("cannot map service `{}` to `{ip}` in /etc/hosts", endpoint.alias);
            }
            entries.push((ip.to_string(), endpoint.alias.clone()));
        }
        let script = super::fixed_path(&hosts_script(&entries));
        self.run_checked(&["exec", "-u", "root", container, super::SH, "-c", &script])
    }

    fn supports_cache_from(&self) -> bool {
        false
    }

    fn supports_file_binds(&self) -> bool {
        false
    }

    fn supports_privileged(&self) -> bool {
        false
    }

    fn supports_restart_policy(&self) -> bool {
        false
    }

    fn restart_policy(&self, _container: &str) -> Result<Option<String>> {
        Ok(None)
    }

    fn set_restart_policy(&self, _container: &str, _policy: &str) -> Result<()> {
        Ok(())
    }

    fn image_entrypoint(&self, image: &str) -> Result<Vec<String>> {
        let out = self.output_quiet(&["image", "inspect", image])?;
        parse_image_entrypoint(&out, oci_arch(std::env::consts::ARCH))
    }

    fn image_user(&self, image: &str) -> Result<Option<String>> {
        let out = self.output_quiet(&["image", "inspect", image])?;
        parse_image_user(&out, oci_arch(std::env::consts::ARCH))
    }

    fn image_env(&self, image: &str) -> Result<Vec<(String, String)>> {
        let out = self.output_quiet(&["image", "inspect", image])?;
        parse_image_env(&out, oci_arch(std::env::consts::ARCH))
    }

    /// Facts are read fresh each time: env is one inspect, and there's no
    /// passwd to cache ([`Self::image_passwd`]).
    fn image_id(&self, _image: &str) -> Result<Option<String>> {
        Ok(None)
    }

    /// A VM per run is too slow for one file: the fallbacks stand in.
    fn image_passwd(&self, _image: &str) -> Result<Option<String>> {
        Ok(None)
    }

    fn remove_volume(&self, name: &str) -> Result<bool> {
        match self.output_quiet(&["volume", "delete", name]) {
            Ok(_) => Ok(true),
            Err(e) if super::is_missing_volume(&e.to_string()) => Ok(false),
            Err(e) => Err(e),
        }
    }

    /// Every container is its own VM: nothing to ask.
    fn identity_fast_path(&self) -> Result<identity::FastPath> {
        Ok(identity::FastPath { mode: Ok(identity::Mode::VmBacked), selinux: false })
    }

    /// Every container is its own VM, sized per container: no engine host
    /// to report.
    fn engine_info(&self) -> Result<identity::EngineInfo> {
        Ok(identity::EngineInfo::default())
    }

    fn identity_canary(&self, _image: &str, _dir: &std::path::Path, _relabel: bool) -> Result<identity::Canary> {
        bail!("no identity canary on Apple `container`: it is always VM-backed")
    }
}

/// Element of `container image inspect`: one OCI image config per platform
/// variant (`variants[].config` is `ContainerizationOCI.Image`, whose keys
/// follow the OCI image spec).
#[derive(Debug, Deserialize)]
struct ImageInspect {
    #[serde(default)]
    variants: Vec<ImageVariant>,
}

#[derive(Debug, Deserialize)]
struct ImageVariant {
    config: OciImage,
}

#[derive(Debug, Deserialize)]
struct OciImage {
    #[serde(default)]
    architecture: String,
    #[serde(default)]
    os: String,
    #[serde(default)]
    config: Option<OciImageConfig>,
}

#[derive(Debug, Deserialize)]
struct OciImageConfig {
    #[serde(rename = "Entrypoint", default)]
    entrypoint: Option<Vec<String>>,
    #[serde(rename = "User", default)]
    user: Option<String>,
    #[serde(rename = "Env", default)]
    env: Option<Vec<String>>,
}

/// Rust's `std::env::consts::ARCH` in OCI platform terms.
fn oci_arch(arch: &str) -> &str {
    match arch {
        "aarch64" => "arm64",
        "x86_64" => "amd64",
        other => other,
    }
}

/// The entrypoint of the `linux/<arch>` variant (what `run` would start),
/// falling back to the first variant.
fn parse_image_entrypoint(json: &str, arch: &str) -> Result<Vec<String>> {
    Ok(image_config(json, arch)?.and_then(|c| c.entrypoint).unwrap_or_default())
}

/// The `USER` of the variant [`parse_image_entrypoint`] picks; `None` when
/// unset or empty.
fn parse_image_user(json: &str, arch: &str) -> Result<Option<String>> {
    Ok(image_config(json, arch)?.and_then(|c| c.user).filter(|u| !u.is_empty()))
}

/// The `Env` of the variant [`parse_image_entrypoint`] picks.
fn parse_image_env(json: &str, arch: &str) -> Result<Vec<(String, String)>> {
    Ok(super::split_env(image_config(json, arch)?.and_then(|c| c.env).unwrap_or_default()))
}

/// The `linux/<arch>` variant's config, else the first variant's.
fn image_config(json: &str, arch: &str) -> Result<Option<OciImageConfig>> {
    let images: Vec<ImageInspect> =
        serde_json::from_str(json).context("unexpected `container image inspect` JSON")?;
    let variants = images.into_iter().next().map(|i| i.variants).unwrap_or_default();
    let pick = variants
        .iter()
        .position(|v| v.config.os == "linux" && v.config.architecture == arch)
        .unwrap_or(0);
    Ok(variants.into_iter().nth(pick).and_then(|v| v.config.config))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn image_entrypoint_picks_host_variant() {
        let json = r#"[{"id": "x", "configuration": {}, "variants": [
          {"platform": {}, "digest": "d1", "size": 1,
           "config": {"architecture": "amd64", "os": "linux", "config": {"Entrypoint": ["/amd"]}}},
          {"platform": {}, "digest": "d2", "size": 1,
           "config": {"architecture": "arm64", "os": "linux", "config": {"Entrypoint": ["/arm", "--"]}}}
        ]}]"#;
        assert_eq!(parse_image_entrypoint(json, "arm64").unwrap(), ["/arm", "--"]);
        assert_eq!(parse_image_entrypoint(json, "amd64").unwrap(), ["/amd"]);
        // No matching variant: first one.
        assert_eq!(parse_image_entrypoint(json, "riscv64").unwrap(), ["/amd"]);
    }

    #[test]
    fn image_user_picks_host_variant() {
        let json = r#"[{"variants": [
          {"config": {"architecture": "amd64", "os": "linux", "config": {"User": "amd"}}},
          {"config": {"architecture": "arm64", "os": "linux", "config": {"User": "node"}}}
        ]}]"#;
        assert_eq!(parse_image_user(json, "arm64").unwrap().as_deref(), Some("node"));
        let json = r#"[{"variants": [{"config": {"architecture": "arm64", "os": "linux", "config": {"User": ""}}}]}]"#;
        assert_eq!(parse_image_user(json, "arm64").unwrap(), None);
        let json = r#"[{"variants": [{"config": {"architecture": "arm64", "os": "linux"}}]}]"#;
        assert_eq!(parse_image_user(json, "arm64").unwrap(), None);
    }

    #[test]
    fn image_env_picks_host_variant() {
        let json = r#"[{"variants": [
          {"config": {"architecture": "amd64", "os": "linux", "config": {"Env": ["PATH=/amd"]}}},
          {"config": {"architecture": "arm64", "os": "linux", "config": {"Env": ["PATH=/usr/bin:/bin", "A=b=c"]}}}
        ]}]"#;
        let want = [("PATH".to_string(), "/usr/bin:/bin".to_string()), ("A".into(), "b=c".into())];
        assert_eq!(parse_image_env(json, "arm64").unwrap(), want);
        let json = r#"[{"variants": [{"config": {"architecture": "arm64", "os": "linux"}}]}]"#;
        assert!(parse_image_env(json, "arm64").unwrap().is_empty());
    }

    #[test]
    fn image_entrypoint_unset_is_empty() {
        let json = r#"[{"variants": [{"config": {"architecture": "arm64", "os": "linux", "config": {"Cmd": ["sh"]}}}]}]"#;
        assert!(parse_image_entrypoint(json, "arm64").unwrap().is_empty());
        let json = r#"[{"variants": [{"config": {"architecture": "arm64", "os": "linux"}}]}]"#;
        assert!(parse_image_entrypoint(json, "arm64").unwrap().is_empty());
        assert_eq!(oci_arch("aarch64"), "arm64");
    }

    const INSPECT: &str = r#"[{
      "id": "devsandbox-repo",
      "configuration": {
        "id": "devsandbox-repo",
        "image": {"reference": "docker.io/library/node:22", "descriptor": {"mediaType": "x", "digest": "sha256:0", "size": 1}},
        "labels": {"devsandbox.sandbox": "repo", "devsandbox.config_hash": "abc"},
        "publishedPorts": [{"hostAddress": "0.0.0.0", "hostPort": 5432, "containerPort": 5432, "proto": "tcp"}],
        "creationDate": "2026-09-15T10:00:00Z"
      },
      "status": {
        "state": "running",
        "networks": [{"network": "devsandbox-net-p", "hostname": "devsandbox-repo", "ipv4Address": "192.168.64.3/24", "ipv4Gateway": "192.168.64.1"}],
        "startedDate": "2026-09-15T10:00:01Z"
      }
    }]"#;

    #[test]
    fn inspect_maps_to_row() {
        let containers = parse_containers(INSPECT).unwrap();
        assert_eq!(containers[0].ipv4(), Some("192.168.64.3"));
        let row = containers.into_iter().next().unwrap().into_row();
        assert_eq!(row.name, "devsandbox-repo");
        assert_eq!(row.image, "docker.io/library/node:22");
        assert!(row.is_running());
        assert_eq!(row.label("devsandbox.config_hash"), Some("abc"));
        assert_eq!(row.host_ports, vec!["5432"]);
    }

    #[test]
    fn inspect_tolerates_sparse_objects() {
        let rows = parse_containers(r#"[{"id":"x","status":{"state":"stopped"}}]"#).unwrap();
        let row = rows.into_iter().next().unwrap().into_row();
        assert_eq!(row.name, "x");
        assert!(!row.is_running());
        assert!(row.image.is_empty());
    }

    #[test]
    fn stats_render_memory_without_cpu() {
        let json = r#"[{"id":"devsandbox-repo","memoryUsageBytes":52428800,"memoryLimitBytes":2147483648,"cpuUsageUsec":1234}]"#;
        let stats = parse_stats(json).unwrap();
        assert_eq!(stats[0].name, "devsandbox-repo");
        assert_eq!(stats[0].cpu, "-");
        assert_eq!(stats[0].mem, "50.0MiB / 2.0GiB");
    }

    #[test]
    fn version_prefers_server_entry() {
        let json = r#"[{"version":"1.4.1","buildType":"release","commit":"a","appName":"container"},{"version":"1.4.0","buildType":"release","commit":"b","appName":"container-apiserver"}]"#;
        assert_eq!(parse_version(json).unwrap(), "1.4.0");
        let cli_only = r#"[{"version":"1.4.1","buildType":"release","commit":"a","appName":"container"}]"#;
        assert_eq!(parse_version(cli_only).unwrap(), "1.4.1");
    }

    #[test]
    fn network_args_repeat_per_network() {
        let nets = vec!["a".to_string(), "b".to_string()];
        assert_eq!(
            AppleContainer.network_run_args(&nets),
            vec!["--network", "a", "--network", "b"]
        );
    }

    #[test]
    fn hosts_script_replaces_alias_line() {
        let script = hosts_script(&[("192.168.64.3".into(), "db".into())]);
        assert!(script.contains("grep -v '[[:space:]]db$'"));
        assert!(script.contains("192.168.64.3 db"));
        assert!(hosts_token_ok("db-primary.local"));
        assert!(!hosts_token_ok("db; rm -rf /"));
    }
}