diff --git a/crates/reach-cli/Cargo.toml b/crates/reach-cli/Cargo.toml index 6b4976f..929b941 100644 --- a/crates/reach-cli/Cargo.toml +++ b/crates/reach-cli/Cargo.toml @@ -34,6 +34,7 @@ async-trait = "0.1" chrono = { version = "0.4", features = ["serde"] } toml = "0.8" futures = "0.3" +sha2 = "0.10" tokio-stream = "0.1" colored = "3" reqwest = { version = "0.13.3", features = ["json"] } diff --git a/crates/reach-cli/src/docker.rs b/crates/reach-cli/src/docker.rs index d31df1b..e5c0d8b 100644 --- a/crates/reach-cli/src/docker.rs +++ b/crates/reach-cli/src/docker.rs @@ -210,13 +210,96 @@ impl Labels { // Docker client // ═══════════════════════════════════════════════════════════ +/// Resolve an override before falling back to Bollard's platform-local default. +pub fn resolve_docker_socket(explicit: &str) -> Option { + let config_dir = std::env::var_os("DOCKER_CONFIG") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".docker"))); + resolve_docker_socket_with_env( + explicit, + std::env::var("DOCKER_HOST").ok().as_deref(), + std::env::var("DOCKER_CONTEXT").ok().as_deref(), + config_dir.as_deref(), + std::env::var_os("XDG_RUNTIME_DIR") + .as_deref() + .map(std::path::Path::new), + ) +} + +/// Precedence: explicit socket, host env, CLI context, rootless socket, default. +/// Configuration read/parse failures deliberately leave the fallback available. +pub fn resolve_docker_socket_with_env( + explicit: &str, + docker_host: Option<&str>, + docker_context: Option<&str>, + config_dir: Option<&std::path::Path>, + runtime_dir: Option<&std::path::Path>, +) -> Option { + if !explicit.is_empty() { + return Some(explicit.to_owned()); + } + if let Some(host) = docker_host.filter(|host| !host.is_empty()) { + return Some(host.to_owned()); + } + if let Some(dir) = config_dir { + let current = docker_context + .filter(|context| !context.is_empty()) + .map(str::to_owned) + .or_else(|| { + let config: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join("config.json")).ok()?).ok()?; + config.get("currentContext")?.as_str().map(str::to_owned) + }); + if let Some(context) = current.filter(|name| !name.is_empty() && name != "default") { + use sha2::{Digest, Sha256}; + let path = dir + .join("contexts/meta") + .join(format!("{:x}", Sha256::digest(context.as_bytes()))) + .join("meta.json"); + let host = std::fs::read(path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .and_then(|meta| { + meta.pointer("/Endpoints/docker/Host")? + .as_str() + .filter(|host| !host.is_empty()) + .map(str::to_owned) + }); + if host.is_some() { + return host; + } + } + } + if !std::path::Path::new("/var/run/docker.sock").exists() + && let Some(socket) = runtime_dir.map(|dir| dir.join("docker.sock")) + && socket.exists() + { + return Some(socket.to_string_lossy().into_owned()); + } + None +} + pub struct DockerClient { client: bollard::Docker, } impl DockerClient { pub fn new() -> Result { - let client = bollard::Docker::connect_with_local_defaults()?; + let config = crate::config::ReachConfig::load(); + let client = match resolve_docker_socket(&config.docker.socket) { + Some(host) + if host.starts_with("tcp://") + || host.starts_with("http://") + || host.starts_with("https://") => + { + bollard::Docker::connect_with_http(&host, 120, bollard::API_DEFAULT_VERSION)? + } + Some(socket) => { + bollard::Docker::connect_with_local(&socket, 120, bollard::API_DEFAULT_VERSION)? + } + None => bollard::Docker::connect_with_local_defaults()?, + }; Ok(Self { client }) } diff --git a/crates/reach-cli/tests/docker_types.rs b/crates/reach-cli/tests/docker_types.rs index 31eaa95..69d37ba 100644 --- a/crates/reach-cli/tests/docker_types.rs +++ b/crates/reach-cli/tests/docker_types.rs @@ -202,3 +202,145 @@ fn novnc_url_uses_localhost_pattern() { "http://localhost:6080/vnc.html?autoconnect=1&resize=remote" ); } + +// Docker endpoint precedence. All configuration is isolated from the real home. +struct DockerFixture(std::path::PathBuf); + +impl DockerFixture { + fn new() -> Self { + let path = std::env::temp_dir().join(format!("reach-context-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn context(&self, name: &str, host: &str) { + use sha2::{Digest, Sha256}; + let dir = self + .0 + .join("contexts/meta") + .join(format!("{:x}", Sha256::digest(name))); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("meta.json"), + serde_json::json!({ + "Endpoints": {"docker": {"Host": host}} + }) + .to_string(), + ) + .unwrap(); + } + + fn resolve(&self, explicit: &str, host: Option<&str>, context: Option<&str>) -> Option { + resolve_docker_socket_with_env(explicit, host, context, Some(&self.0), None) + } +} + +impl Drop for DockerFixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } +} + +#[test] +fn resolve_docker_socket_current_context() { + let f = DockerFixture::new(); + f.context("rootless", "unix:///run/user/1000/docker.sock"); + std::fs::write(f.0.join("config.json"), r#"{"currentContext":"rootless"}"#).unwrap(); + assert_eq!( + f.resolve("", Some(""), None).as_deref(), + Some("unix:///run/user/1000/docker.sock") + ); +} + +#[test] +fn resolve_docker_socket_env_context_overrides_current() { + let f = DockerFixture::new(); + f.context("chosen", "tcp://localhost:2375"); + f.context("other", "unix:///other.sock"); + std::fs::write(f.0.join("config.json"), r#"{"currentContext":"other"}"#).unwrap(); + assert_eq!( + f.resolve("", None, Some("chosen")).as_deref(), + Some("tcp://localhost:2375") + ); +} + +#[test] +fn resolve_docker_socket_default_context_is_skipped() { + let f = DockerFixture::new(); + f.context("default", "unix:///wrong.sock"); + std::fs::write(f.0.join("config.json"), r#"{"currentContext":"default"}"#).unwrap(); + assert_eq!(f.resolve("", None, None), None); + assert_eq!(f.resolve("", None, Some("default")), None); +} + +#[test] +fn resolve_docker_socket_bad_files_fall_through() { + let f = DockerFixture::new(); + assert_eq!(f.resolve("", None, None), None); + std::fs::write(f.0.join("config.json"), "{").unwrap(); + assert_eq!(f.resolve("", None, None), None); + assert_eq!(f.resolve("", None, Some("missing")), None); + f.context("broken", "unix:///unused.sock"); + use sha2::{Digest, Sha256}; + let meta = + f.0.join("contexts/meta") + .join(format!("{:x}", Sha256::digest("broken"))) + .join("meta.json"); + std::fs::write(&meta, "{").unwrap(); + assert_eq!(f.resolve("", None, Some("broken")), None); + std::fs::remove_file(&meta).unwrap(); + std::fs::create_dir(&meta).unwrap(); + assert_eq!(f.resolve("", None, Some("broken")), None); +} + +#[test] +fn resolve_docker_socket_host_wins_over_context() { + let f = DockerFixture::new(); + f.context("rootless", "unix:///context.sock"); + assert_eq!( + f.resolve("", Some("unix:///host.sock"), Some("rootless")) + .as_deref(), + Some("unix:///host.sock") + ); +} + +#[test] +fn resolve_docker_socket_explicit_wins_over_everything() { + let f = DockerFixture::new(); + f.context("rootless", "unix:///context.sock"); + assert_eq!( + f.resolve( + "/explicit.sock", + Some("unix:///host.sock"), + Some("rootless") + ) + .as_deref(), + Some("/explicit.sock") + ); +} + +#[test] +fn resolve_docker_socket_runtime_fallback() { + let f = DockerFixture::new(); + let socket = f.0.join("docker.sock"); + assert_eq!( + resolve_docker_socket_with_env("", None, None, Some(&f.0), Some(&f.0)), + None + ); + std::fs::write(&socket, "").unwrap(); + let expected = if std::path::Path::new("/var/run/docker.sock").exists() { + None + } else { + Some(socket.to_string_lossy().into_owned()) + }; + assert_eq!( + resolve_docker_socket_with_env("", None, None, Some(&f.0), Some(&f.0)), + expected + ); + f.context("selected", "unix:///selected.sock"); + assert_eq!( + resolve_docker_socket_with_env("", None, Some("selected"), Some(&f.0), Some(&f.0)) + .as_deref(), + Some("unix:///selected.sock") + ); +}