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};
const GOTO_WAIT_SECS: u32 = 30;
const GOTO_TIMEOUT: Duration = Duration::from_secs(GOTO_WAIT_SECS as u64 + 10);
const GOTO_OUTPUT_CAP: usize = 64 * 1024;
const GOTO_NO_WINDOW: i32 = 3;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Goto {
pub path: String,
pub line: Option<u32>,
pub col: Option<u32>,
}
impl Goto {
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 })
}
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())
}
pub fn abs_in(&self, workspace: &str) -> String {
format!("{}/{}", workspace.trim_end_matches('/'), self.path)
}
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(),
}
}
}
impl fmt::Display for Goto {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.path, self.suffix())
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum GotoOutcome {
Opened,
NotReady,
NoHelper,
Failed(String),
}
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}")
}
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()),
}
}
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(())
}
#[derive(Debug)]
pub struct LeakRefused {
pub message: String,
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 {}
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}"),
})
}
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"),
]
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Safety {
Safe,
Exposed,
Unverified,
}
const EXT_HOST_ENTRYPOINT: (&str, &str) = ("VSCODE_ESM_ENTRYPOINT", "vs/workbench/api/node/extensionHostProcess");
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 }
}
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()
}
#[cfg(target_os = "linux")]
fn ext_hosts_safety() -> Safety {
use std::os::unix::fs::MetadataExt;
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
}
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(", ")
))
}
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());
}
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<_>>(),
);
let (flag, path) = match &info.workspace_file {
Some(file) => ("--file-uri", file.as_str()),
None => ("--folder-uri", info.workspace.as_str()),
};
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}");
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?)")?;
#[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))
}
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)
}
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)));
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)"
);
}
#[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() {
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");
}
}