devsandbox 0.11.1

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
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
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;

use anyhow::{Context, Result};

use super::resolve_instance;
use crate::config::Config;
use crate::credentials::instance::InstanceClaim;
use crate::runtime::{backend, bounded};
use crate::state::{Instance, State};

/// How long `devsbd vscode-goto` polls for the window to attach: a first
/// attach may install the VS Code server before the extension host appears.
const GOTO_WAIT_SECS: u32 = 30;

/// Host-side bound on the whole goto exec: the helper's wait plus slack for
/// the exec itself and the remote CLI. The container controls how long it
/// runs, so it must not hang `vscode` (or the TUI's worker) forever.
const GOTO_TIMEOUT: Duration = Duration::from_secs(GOTO_WAIT_SECS as u64 + 10);

/// Helper stdout kept: it prints one `socket=… pid=… cli=…` line plus the
/// remote CLI's output, none of which is shown.
const GOTO_OUTPUT_CAP: usize = 64 * 1024;

/// `devsbd vscode-goto`'s exit code for "no VS Code window attached".
const GOTO_NO_WINDOW: i32 = 3;

/// A file position to open in the attached window: `path` is relative to the
/// instance's workspace folder and normalized (no `.`/empty components), with
/// no `..` and not absolute, so joining it can't leave the workspace.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Goto {
    pub path: String,
    pub line: Option<u32>,
    /// Only with a `line` (VS Code's `-g` has no column-only form).
    pub col: Option<u32>,
}

impl Goto {
    /// Validate and normalize the parts (the Inbox `vscode` action carries
    /// them separately).
    pub fn new(path: &str, line: Option<u32>, col: Option<u32>) -> Result<Goto, String> {
        if path.starts_with('/') || path.starts_with('~') {
            return Err(format!("goto path must be relative to the workspace: {path}"));
        }
        let parts: Vec<&str> = path.split('/').filter(|c| !c.is_empty() && *c != ".").collect();
        if parts.contains(&"..") {
            return Err(format!("goto path must stay inside the workspace: {path}"));
        }
        if parts.is_empty() {
            return Err("goto path is empty".into());
        }
        if line == Some(0) || col == Some(0) {
            return Err("goto line and column start at 1".into());
        }
        if col.is_some() && line.is_none() {
            return Err("goto column needs a line".into());
        }
        Ok(Goto { path: parts.join("/"), line, col })
    }

    /// `PATH[:LINE[:COL]]`. Numbers are taken from the right, so a `:` inside
    /// the path (`a:b.rs:3`) survives; what's left must not still end in
    /// `:<digits>` (`x:1:2:3`), which VS Code's `-g` would read differently.
    pub fn parse(spec: &str) -> Result<Goto, String> {
        let mut path = spec;
        let mut nums = Vec::new();
        while nums.len() < 2 {
            let Some((rest, tail)) = path.rsplit_once(':') else { break };
            if tail.is_empty() {
                return Err(format!("empty line or column in `{spec}`"));
            }
            if !tail.bytes().all(|b| b.is_ascii_digit()) {
                break;
            }
            nums.push(tail.parse::<u32>().map_err(|_| format!("line or column too large in `{spec}`"))?);
            path = rest;
        }
        if nums.len() == 2
            && path.rsplit_once(':').is_some_and(|(_, t)| t.bytes().all(|b| b.is_ascii_digit()))
        {
            return Err(format!("ambiguous goto `{spec}`: expected PATH[:LINE[:COL]]"));
        }
        nums.reverse();
        Goto::new(path, nums.first().copied(), nums.get(1).copied())
    }

    /// The in-container absolute path: `workspace` is the instance's
    /// workspace folder as the container sees it (`Instance::workspace`).
    pub fn abs_in(&self, workspace: &str) -> String {
        format!("{}/{}", workspace.trim_end_matches('/'), self.path)
    }

    /// `devsbd vscode-goto`'s argument: `<abs>[:line[:col]]`.
    fn arg_in(&self, workspace: &str) -> String {
        format!("{}{}", self.abs_in(workspace), self.suffix())
    }

    fn suffix(&self) -> String {
        match (self.line, self.col) {
            (Some(l), Some(c)) => format!(":{l}:{c}"),
            (Some(l), None) => format!(":{l}"),
            _ => String::new(),
        }
    }
}

/// The relative form, `path[:line[:col]]`, as the user wrote it.
impl fmt::Display for Goto {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.path, self.suffix())
    }
}

/// How the in-container half of a goto went.
#[derive(Debug, PartialEq, Eq)]
pub enum GotoOutcome {
    Opened,
    /// No window attached within the helper's wait.
    NotReady,
    /// No helper recorded for the instance: nothing to exec.
    NoHelper,
    /// Anything else, with a one-line reason.
    Failed(String),
}

/// The status line for a launch with a goto; `hint` is the runtime caveat
/// `launch` appends either way.
pub fn goto_status(goto: &Goto, outcome: &GotoOutcome, hint: &str) -> String {
    let why = match outcome {
        GotoOutcome::Opened => return format!("opened VS Code at {goto}{hint}"),
        GotoOutcome::NotReady => "window not ready",
        GotoOutcome::NoHelper => "no devsbd helper",
        GotoOutcome::Failed(why) => why,
    };
    format!("opened VS Code; --goto dropped ({why}){hint}")
}

/// Run `devsbd vscode-goto` as root in `container` (root to find the window
/// whoever owns it; the helper drops to the owner for the CLI). Captured and
/// bounded, never inherited: the TUI runs this while it owns the terminal,
/// and the container controls the output and the duration.
pub fn goto_in(container: &str, workspace: &str, goto: &Goto) -> GotoOutcome {
    let arg = goto.arg_in(workspace);
    let wait = GOTO_WAIT_SECS.to_string();
    let mut cmd = Command::new(backend().bin());
    cmd.args(["exec", "-u", "root", container, crate::devsbd::BIN, "vscode-goto", &arg, "--wait", &wait])
        .stdin(Stdio::null());
    match bounded::run(&mut cmd, GOTO_OUTPUT_CAP, GOTO_TIMEOUT) {
        Ok(out) if out.status.success() => GotoOutcome::Opened,
        Ok(out) if out.status.code() == Some(GOTO_NO_WINDOW) => GotoOutcome::NotReady,
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr);
            GotoOutcome::Failed(match stderr.lines().map(str::trim).find(|l| !l.is_empty()) {
                Some(line) => line.to_string(),
                None => match out.status.code() {
                    Some(code) => format!("exit {code}"),
                    None => "killed".into(),
                },
            })
        }
        Err(e) => GotoOutcome::Failed(e.to_string()),
    }
}

/// CLI entry point: open VS Code attached to the instance `name` resolves to
/// (same as `o` in the dashboard), at `goto` when given. An instance with
/// a credential claim opens only when no VS Code window can leak
/// ([`launch`]), else only with `allow_credential_leak`, warned.
pub fn vscode(dir: &Path, name: &str, goto: Option<&Goto>, allow_credential_leak: bool) -> Result<()> {
    let state = State::load()?;
    let key = resolve_instance(&state, name)?;
    let info = &state.instances[&key];
    if allow_credential_leak
        && let Some(why) = credential_leak(&key, &info.claims)
        && ext_hosts_safety() != Safety::Safe
    {
        eprintln!("warning: {why}");
    }
    println!("{}", launch(dir, &key, info, goto, allow_credential_leak)?);
    Ok(())
}

/// [`launch`]'s refusal of an instance with a credential claim: the
/// dashboard tells it from other errors to offer the open anyway.
#[derive(Debug)]
pub struct LeakRefused {
    pub message: String,
    /// A running extension host lacks [`leak_overrides`] (else unverified).
    pub exposed: bool,
}

impl fmt::Display for LeakRefused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for LeakRefused {}

/// [`launch`]'s refusal of an instance with `claims`, unless `allowed` or
/// the running extension hosts are `safety`-checked safe.
fn leak_refusal(instance: &str, claims: &[InstanceClaim], allowed: bool, safety: Safety) -> Option<String> {
    let why = credential_leak(instance, claims).filter(|_| !allowed && safety != Safety::Safe)?;
    let anyway = format!("`devsandbox vscode --allow-credential-leak {instance}` opens it anyway");
    Some(match safety {
        Safety::Exposed => format!(
            "{why}; another VS Code window is running with your logins (its window would be reused): close VS Code first, or {anyway}"
        ),
        _ => format!("{why}; {anyway}"),
    })
}

/// The env `code` gets for an instance with a claim, cutting what Dev
/// Containers hands an attached container: it forwards the agent at the
/// local extension host's `SSH_AUTH_SOCK` (any non-empty value; empty or
/// unset isn't enough, since a window's env is VS Code's own overlaid with
/// the CLI's), and its git credential helper runs host `git credential`
/// with the extension host's env, where the `GIT_CONFIG_*` entry resets
/// every configured helper and `GIT_ASKPASS` stops an inherited prompt.
pub fn leak_overrides() -> [(&'static str, &'static str); 5] {
    [
        ("SSH_AUTH_SOCK", "/nonexistent"),
        ("GIT_CONFIG_COUNT", "1"),
        ("GIT_CONFIG_KEY_0", "credential.helper"),
        ("GIT_CONFIG_VALUE_0", ""),
        ("GIT_ASKPASS", "/bin/false"),
    ]
}

/// Whether the local VS Code extension hosts already running would leak
/// to a new attach: `code` reuses a running VS Code, whose windows'
/// extension hosts keep the env they started with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Safety {
    /// None running, or every one started with [`leak_overrides`].
    Safe,
    /// One started without them.
    Exposed,
    /// Not checkable on this platform.
    Unverified,
}

/// The local extension hosts' marker in their environ.
const EXT_HOST_ENTRYPOINT: (&str, &str) = ("VSCODE_ESM_ENTRYPOINT", "vs/workbench/api/node/extensionHostProcess");

/// [`Safety`] over the environs of this user's processes.
fn verdict<'a>(environs: impl IntoIterator<Item = &'a HashMap<String, String>>) -> Safety {
    let (key, value) = EXT_HOST_ENTRYPOINT;
    let exposed = environs
        .into_iter()
        .filter(|env| env.get(key).is_some_and(|v| v == value))
        .any(|env| leak_overrides().iter().any(|(k, v)| env.get(*k).is_none_or(|got| got != v)));
    if exposed { Safety::Exposed } else { Safety::Safe }
}

/// One `/proc/<pid>/environ`: NUL-separated `KEY=VALUE`s, non-UTF-8 lossy.
fn parse_environ(bytes: &[u8]) -> HashMap<String, String> {
    bytes
        .split(|&b| b == 0)
        .filter_map(|entry| {
            let entry = String::from_utf8_lossy(entry);
            let (k, v) = entry.split_once('=')?;
            Some((k.to_string(), v.to_string()))
        })
        .collect()
}

/// [`verdict`] over the current uid's processes; unreadable ones (gone,
/// another user's) are skipped.
#[cfg(target_os = "linux")]
fn ext_hosts_safety() -> Safety {
    use std::os::unix::fs::MetadataExt;
    // SAFETY: getuid has no preconditions and cannot fail.
    let uid = unsafe { libc::getuid() };
    let Ok(entries) = std::fs::read_dir("/proc") else {
        return Safety::Unverified;
    };
    let environs: Vec<HashMap<String, String>> = entries
        .flatten()
        .filter(|e| e.file_name().to_str().is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit())))
        .filter(|e| e.metadata().is_ok_and(|m| m.uid() == uid))
        .filter_map(|e| std::fs::read(e.path().join("environ")).ok())
        .map(|bytes| parse_environ(&bytes))
        .collect();
    verdict(&environs)
}

#[cfg(not(target_os = "linux"))]
fn ext_hosts_safety() -> Safety {
    Safety::Unverified
}

/// Why attaching VS Code to an instance with `claims` hands the sandbox
/// what the broker keeps out (git-gateway, *Other ways around the
/// gateway*): Dev Containers' git credential helper, its forwarded agent
/// and the git extension's askpass reach the host's logins, and their
/// switches are host-side user settings devsandbox can't set.
fn credential_leak(instance: &str, claims: &[InstanceClaim]) -> Option<String> {
    if claims.is_empty() {
        return None;
    }
    let kinds: Vec<&str> = claims.iter().map(|c| c.kind.as_str()).collect();
    Some(format!(
        "`{instance}` has credential claims ({}): VS Code's attach gives it your host's git logins and whole ssh-agent, past the broker and the agent's key filter",
        kinds.join(", ")
    ))
}

/// Launch VS Code attached to `info`'s container, detached. Writes the
/// extensions name-config (best-effort), then spawns `code`. With `goto`,
/// then has the helper open the file in that window
/// (docs/architecture/helper/in-container.md, *`devsbd vscode-goto
/// <abs>[:line[:col]] [--wait SECS]`*): the host `code` always runs first,
/// since it opens or focuses the window the in-container CLI needs. Blocks up
/// to [`GOTO_TIMEOUT`] then. Returns a one-line status. Shared with the TUI's
/// `o` so both open identically. An instance with a credential claim gets
/// `code` with [`leak_overrides`], and is refused ([`LeakRefused`]) unless
/// the running extension hosts check safe or `allow_credential_leak`.
pub fn launch(
    dir: &Path,
    instance: &str,
    info: &Instance,
    goto: Option<&Goto>,
    allow_credential_leak: bool,
) -> Result<String> {
    let leaks = credential_leak(instance, &info.claims).is_some();
    let safety = if leaks { ext_hosts_safety() } else { Safety::Safe };
    if let Some(message) = leak_refusal(instance, &info.claims, allow_credential_leak, safety) {
        return Err(LeakRefused { message, exposed: safety == Safety::Exposed }.into());
    }
    // Extensions come from the resolved sandbox, read from the instance's own
    // config root: state is global, so `dir` (the cwd by default) may be
    // another root or none. Failure to resolve is non-fatal: keep the
    // extensions `run` registered. The user is the one every exec runs as,
    // recorded at create (the identity plan's, not the config's
    // `remoteUser`), so the attach opens as the user that owns the files.
    let config_dir = info.config_dir.as_deref().unwrap_or(dir);
    let resolved = Config::load(config_dir)
        .and_then(|cfg| cfg.resolve_sandbox(&info.sandbox))
        .ok();
    let extensions: Option<Vec<String>> = resolved.as_ref().map(|sb| {
        sb.properties.vscode_extensions().map(<[String]>::to_vec).unwrap_or_default()
    });
    let _ = super::run::write_vscode_name_config(
        &info.container,
        extensions.as_deref(),
        info.remote_user.as_deref(),
        &crate::credentials::instance::ports(&info.claims, info.intercept.as_ref()).collect::<Vec<_>>(),
    );

    // Prefer the generated `.code-workspace` (window named after the instance,
    // carries the extra `folders` roots); instances created before it existed
    // fall back to a plain folder open.
    let (flag, path) = match &info.workspace_file {
        Some(file) => ("--file-uri", file.as_str()),
        None => ("--folder-uri", info.workspace.as_str()),
    };
    // The Remote-Containers extension resolves a different authority per runtime.
    // Docker/podman use `attached-container` (hex of the bare container name).
    // Apple `container` uses `apple-container` (hex of a JSON `{id, image}`
    // payload) and requires the user's opt-in
    // `dev.containers.experimentalAppleContainerSupport` setting.
    let (authority, hint) = if backend().name() == "container" {
        let image = apple_image_reference(&info.container).unwrap_or_default();
        let payload = serde_json::json!({ "id": info.container, "image": image }).to_string();
        (
            format!("apple-container+{}", hex_encode(&payload)),
            " (needs dev.containers.experimentalAppleContainerSupport=true)",
        )
    } else {
        (format!("attached-container+{}", hex_encode(&info.container)), "")
    };
    let uri = format!("vscode-remote://{authority}/{path}");
    // Detached and silent: the dashboard calls this while it owns the
    // terminal, so `code`'s own chatter must not land on the screen.
    let mut code = std::process::Command::new("code");
    if leaks {
        code.envs(leak_overrides());
    }
    code.args([flag, &uri])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .context("code: failed to launch (`code` on PATH?)")?;
    // A point-in-time attach (`code` runs detached): it begins and ends at
    // once, so this host is the instance's latest attach.
    #[cfg(unix)]
    drop(crate::serve::client::attach_hold(&info.instance_id, None));
    let Some(goto) = goto else {
        return Ok(format!("opening VS Code → {instance}{hint}"));
    };
    let outcome = match info.devsbd_arch {
        Some(_) => goto_in(&info.container, &info.workspace, goto),
        None => GotoOutcome::NoHelper,
    };
    Ok(goto_status(goto, &outcome, hint))
}

/// Apple `container` image reference (`configuration.image.reference`) for
/// `container`, needed in the `apple-container` attach URI payload. Best-effort:
/// `None` when inspect fails or the field is absent, in which case the caller
/// sends an empty image (the resolver only requires `id`).
fn apple_image_reference(container: &str) -> Option<String> {
    let json = backend().inspect_json(container).ok()?;
    let v: serde_json::Value = serde_json::from_str(&json).ok()?;
    let obj = v.get(0).unwrap_or(&v);
    obj.get("configuration")?
        .get("image")?
        .get("reference")?
        .as_str()
        .map(str::to_string)
}

/// Lowercase hex of a string's UTF-8 bytes, as the Remote-Containers URI wants.
fn hex_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len() * 2);
    for b in s.bytes() {
        out.push(char::from_digit((b >> 4) as u32, 16).unwrap());
        out.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
    }
    out
}

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

    fn goto(path: &str, line: Option<u32>, col: Option<u32>) -> Goto {
        Goto { path: path.into(), line, col }
    }

    #[test]
    fn goto_parses_numbers_from_the_right() {
        assert_eq!(Goto::parse("x.rs"), Ok(goto("x.rs", None, None)));
        assert_eq!(Goto::parse("x.rs:3"), Ok(goto("x.rs", Some(3), None)));
        assert_eq!(Goto::parse("x.rs:3:4"), Ok(goto("x.rs", Some(3), Some(4))));
        assert_eq!(Goto::parse("a:b.rs:3"), Ok(goto("a:b.rs", Some(3), None)));
        assert_eq!(Goto::parse("a:b.rs"), Ok(goto("a:b.rs", None, None)));
        // Normalized: `.` and empty components dropped.
        assert_eq!(Goto::parse("./src//a.rs/:7"), Ok(goto("src/a.rs", Some(7), None)));
        assert_eq!(Goto::parse("x.rs:3:4").unwrap().to_string(), "x.rs:3:4");
    }

    #[test]
    fn goto_rejects_bad_specs() {
        for bad in [
            "x.rs::3", "x.rs:", "x.rs:3:", "../x", "a/../../x", "/abs", "~/x", "", ".", ":3", "x.rs:0",
            "x.rs:1:0", "x:1:2:3", "x.rs:99999999999",
        ] {
            assert!(Goto::parse(bad).is_err(), "{bad:?} parsed");
        }
        assert_eq!(Goto::new("x.rs", None, Some(2)), Err("goto column needs a line".into()));
    }

    #[test]
    fn goto_joins_the_container_workspace() {
        let g = goto("src/a.rs", Some(3), Some(4));
        assert_eq!(g.abs_in("/workspaces/repo"), "/workspaces/repo/src/a.rs");
        assert_eq!(g.abs_in("/workspaces/repo/"), "/workspaces/repo/src/a.rs");
        assert_eq!(g.abs_in("/"), "/src/a.rs");
        assert_eq!(g.arg_in("/w"), "/w/src/a.rs:3:4");
        assert_eq!(goto("a.rs", Some(3), None).arg_in("/w"), "/w/a.rs:3");
        assert_eq!(goto("a.rs", None, None).arg_in("/w"), "/w/a.rs");
    }

    #[test]
    fn goto_status_per_outcome() {
        let g = goto("src/a.rs", Some(3), None);
        assert_eq!(goto_status(&g, &GotoOutcome::Opened, ""), "opened VS Code at src/a.rs:3");
        assert_eq!(
            goto_status(&g, &GotoOutcome::NotReady, ""),
            "opened VS Code; --goto dropped (window not ready)"
        );
        assert_eq!(
            goto_status(&g, &GotoOutcome::NoHelper, " (hint)"),
            "opened VS Code; --goto dropped (no devsbd helper) (hint)"
        );
        assert_eq!(
            goto_status(&g, &GotoOutcome::Failed("exit 1".into()), ""),
            "opened VS Code; --goto dropped (exit 1)"
        );
    }

    /// `goto_in` against the fake window (`devsbd::fake_vscode_window`):
    /// the helper ends up running the window's CLI with the joined path.
    #[test_utils::docker_test(helper)]
    fn goto_in_opens_the_joined_path_in_the_window_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let name = format!("devsandbox-vscode-goto-test-{stamp}");
        let up = crate::test_support::runtime_cmd()
            .args(["run", "-d", "--rm", "--name", &name, "python:3.13-alpine", "sleep", "300"])
            .output()
            .unwrap();
        assert!(up.status.success(), "{}", String::from_utf8_lossy(&up.stderr));
        let cleanup = || {
            let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
        };
        crate::test_support::with_cleanup(cleanup, || {
            crate::devsbd::install(&name, None).unwrap();
            crate::devsbd::fake_vscode_window(&name);
            let outcome = goto_in(&name, "/workspaces/repo/", &goto("src/a.rs", Some(4), Some(2)));
            assert_eq!(outcome, GotoOutcome::Opened);
            let argv = crate::test_support::runtime_cmd().args(["exec", &name, "cat", "/tmp/rec/argv"]).output().unwrap();
            assert_eq!(String::from_utf8_lossy(&argv.stdout), "-g\n/workspaces/repo/src/a.rs:4:2\n");
        });
        Ok(())
    }

    #[test]
    fn an_instance_with_claims_needs_the_leak_flag() {
        assert_eq!(credential_leak("repo", &[]), None);
        assert_eq!(leak_refusal("repo", &[], false, Safety::Unverified), None);
        let claims = vec![InstanceClaim {
            kind: "github".into(),
            feature: "./gh".into(),
            version: "v".into(),
            claim: "{}".into(),
            phantom: "p".into(),
            listeners: Vec::new(),
            files: Vec::new(),
            git_hosts: vec!["github.com".into()],
        }];
        let why = credential_leak("repo", &claims).unwrap();
        assert!(why.contains("(github)") && why.contains("ssh-agent"), "{why}");
        let refused = leak_refusal("repo", &claims, false, Safety::Unverified).unwrap();
        assert!(refused.contains("--allow-credential-leak repo"), "{refused}");
        assert!(!refused.contains("another VS Code window"), "{refused}");
        let refused = leak_refusal("repo", &claims, false, Safety::Exposed).unwrap();
        assert!(refused.contains("another VS Code window") && refused.contains("--allow-credential-leak repo"), "{refused}");
        assert_eq!(leak_refusal("repo", &claims, true, Safety::Exposed), None);
        assert_eq!(leak_refusal("repo", &claims, false, Safety::Safe), None);
        assert_eq!(leak_refusal("repo", &[], false, Safety::Exposed), None);
    }

    fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
    }

    #[test]
    fn environ_parses_nul_separated_pairs() {
        let parsed = parse_environ(b"A=1\0B=x=y\0EMPTY=\0junk\0");
        assert_eq!(parsed, env(&[("A", "1"), ("B", "x=y"), ("EMPTY", "")]));
    }

    #[test]
    fn only_ext_hosts_without_the_overrides_are_exposed() {
        let host = [EXT_HOST_ENTRYPOINT];
        let bare_host = env(&host);
        let mut covered: Vec<(&str, &str)> = host.to_vec();
        covered.extend(leak_overrides());
        let covered = env(&covered);
        let mut agent_only = covered.clone();
        agent_only.insert("SSH_AUTH_SOCK".into(), "/run/agent.sock".into());
        let other = env(&[("SSH_AUTH_SOCK", "/run/agent.sock")]);

        assert_eq!(verdict([]), Safety::Safe);
        assert_eq!(verdict([&other]), Safety::Safe);
        assert_eq!(verdict([&covered, &other]), Safety::Safe);
        assert_eq!(verdict([&covered, &bare_host]), Safety::Exposed);
        assert_eq!(verdict([&agent_only]), Safety::Exposed);
    }

    #[test]
    fn hex_encodes_container_name() {
        assert_eq!(hex_encode("devsandbox-web"), "64657673616e64626f782d776562");
        assert_eq!(hex_encode(""), "");
        assert_eq!(hex_encode("A/z"), "412f7a");
    }

    #[test]
    fn apple_authority_payload_roundtrips() {
        // The `apple-container` authority carries hex of a JSON `{id, image}`
        // payload; VS Code hex-decodes and `JSON.parse`s it. Verify the encoding
        // devsandbox emits decodes back to that object.
        let payload = serde_json::json!({ "id": "devsandbox-web", "image": "img:latest" })
            .to_string();
        let hex = hex_encode(&payload);
        let bytes: Vec<u8> = (0..hex.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
            .collect();
        let decoded: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(decoded["id"], "devsandbox-web");
        assert_eq!(decoded["image"], "img:latest");
    }
}