diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index b6fdd03a30..fe6eebe769 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -702,6 +702,94 @@ pub fn probe_socket(path: &std::path::Path) -> bool { std::os::unix::net::UnixStream::connect(path).is_ok() } +/// File name of the tailnet proxy env the seat bootstrap writes +/// beside tailscaled's node state in userspace mode +/// (`scripts/muse/bootstrap.sh`): one `export HTTPS_PROXY=...` line +/// naming tailscaled's local CONNECT proxy. +pub const TAILNET_PROXY_ENV_FILE: &str = "fleet-proxy.env"; + +/// Where to look for [`TAILNET_PROXY_ENV_FILE`], most specific +/// first: an explicit `$FLEET_PROXY_ENV` path, then the named +/// agent's isolated node state +/// (`~/.local/state/tailscale/agents/`, with the bootstrap's +/// own slug rule over `$FLEET_AGENT`), then the legacy shared node +/// state (`~/.local/state/tailscale`). Pure over its inputs so the +/// order is testable. +pub fn tailnet_proxy_env_candidates( + home: &std::path::Path, + fleet_agent: Option<&str>, + explicit: Option, +) -> Vec { + let mut out = Vec::new(); + if let Some(path) = non_empty_path(explicit) { + out.push(resolve_under(home, &path)); + } + let state = home.join(".local").join("state").join("tailscale"); + if let Some(slug) = fleet_agent.and_then(agent_slug) { + out.push(state.join("agents").join(slug).join(TAILNET_PROXY_ENV_FILE)); + } + out.push(state.join(TAILNET_PROXY_ENV_FILE)); + out +} + +/// The bootstrap's agent slug: lower-cased, every character outside +/// `[a-z0-9-]` replaced by `-`, leading and trailing dashes trimmed, +/// cut to 55 characters, then one `muse-` prefix dropped. `None` +/// when nothing is left, as the bootstrap refuses such a name. +fn agent_slug(agent: &str) -> Option { + let mapped: String = agent + .to_lowercase() + .chars() + .map(|c| { + if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' { + c + } else { + '-' + } + }) + .collect(); + let trimmed: String = mapped.trim_matches('-').chars().take(55).collect(); + let slug = trimmed.strip_prefix("muse-").unwrap_or(&trimmed); + (!slug.is_empty()).then(|| slug.to_string()) +} + +/// The `HTTPS_PROXY` value an env file sets, from a line of the form +/// `[export ]HTTPS_PROXY=value` (the value optionally in matching +/// single or double quotes). The last such line with a value wins, +/// as it would when the file is sourced. +pub fn parse_tailnet_proxy_env(text: &str) -> Option { + text.lines().rev().find_map(|line| { + let line = line.trim(); + let line = line.strip_prefix("export ").unwrap_or(line).trim_start(); + let value = line.strip_prefix("HTTPS_PROXY=")?.trim(); + let value = value + .strip_prefix('"') + .and_then(|v| v.strip_suffix('"')) + .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\''))) + .unwrap_or(value); + (!value.is_empty()).then(|| value.to_string()) + }) +} + +/// The seat's recorded tailnet proxy (#12555): the first readable +/// [`TAILNET_PROXY_ENV_FILE`] among [`tailnet_proxy_env_candidates`] +/// that sets `HTTPS_PROXY`. Tailnet tunnels use it in place of the +/// caller's ambient `HTTPS_PROXY`, which in a sandbox shell is the +/// platform egress proxy: a broker started from there otherwise +/// opens every tailnet tunnel through the wrong proxy while it looks +/// alive. `None` (no file, as on a kernel-mode seat) leaves the +/// ambient env in charge. +pub fn tailnet_https_proxy() -> Option { + let agent = std::env::var("FLEET_AGENT").ok(); + tailnet_proxy_env_candidates( + &home_dir(), + agent.as_deref(), + std::env::var_os("FLEET_PROXY_ENV").map(PathBuf::from), + ) + .into_iter() + .find_map(|path| parse_tailnet_proxy_env(&std::fs::read_to_string(path).ok()?)) +} + impl Config { /// The config file path: `$FLEET_CONFIG`, else /// `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`. @@ -1526,6 +1614,58 @@ impl Config { mod tests { use super::*; + #[test] + fn tailnet_proxy_env_candidates_follow_the_bootstrap_layout() { + let home = std::path::Path::new("/home/a"); + let state = home.join(".local/state/tailscale"); + assert_eq!( + tailnet_proxy_env_candidates(home, None, None), + vec![state.join("fleet-proxy.env")] + ); + assert_eq!( + tailnet_proxy_env_candidates(home, Some("Muse-Felix"), Some("x/p.env".into())), + vec![ + home.join("x/p.env"), + state.join("agents/felix/fleet-proxy.env"), + state.join("fleet-proxy.env"), + ] + ); + // A name with nothing usable gets no agent path. + assert_eq!( + tailnet_proxy_env_candidates(home, Some("--"), None), + vec![state.join("fleet-proxy.env")] + ); + } + + #[test] + fn agent_slug_matches_the_bootstrap_rule() { + assert_eq!(agent_slug("felix").as_deref(), Some("felix")); + assert_eq!(agent_slug("Muse Archer!").as_deref(), Some("archer")); + assert_eq!(agent_slug("muse-archer").as_deref(), Some("archer")); + assert_eq!(agent_slug("-a_b-").as_deref(), Some("a-b")); + assert_eq!(agent_slug("muse-").as_deref(), Some("muse")); + assert_eq!(agent_slug(""), None); + assert_eq!(agent_slug(&"x".repeat(80)).map(|s| s.len()), Some(55)); + } + + #[test] + fn parse_tailnet_proxy_env_reads_the_bootstrap_line() { + assert_eq!( + parse_tailnet_proxy_env("export HTTPS_PROXY=http://127.0.0.1:3130\n").as_deref(), + Some("http://127.0.0.1:3130") + ); + assert_eq!( + parse_tailnet_proxy_env( + "# c\nHTTPS_PROXY='http://a:1'\nexport HTTPS_PROXY=\"http://b:2\"\n" + ) + .as_deref(), + Some("http://b:2") + ); + assert_eq!(parse_tailnet_proxy_env("HTTP_PROXY=http://x\n"), None); + assert_eq!(parse_tailnet_proxy_env("export HTTPS_PROXY=\n"), None); + assert_eq!(parse_tailnet_proxy_env(""), None); + } + fn write_temp(contents: &str) -> (tempfile_dir::Dir, PathBuf) { let dir = tempfile_dir::Dir::new(); let path = dir.path().join("fleet.toml"); diff --git a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs index fe9a82f861..9ee11898d5 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/tunnel.rs @@ -169,10 +169,19 @@ fn base64_encode(data: &[u8]) -> String { out } -/// Parse the egress endpoint from the `HTTPS_PROXY` env var. The -/// error strings name shapes only — never the URL (it carries the -/// credential). +/// Parse the tailnet egress endpoint: the seat's recorded tailnet +/// proxy when it has one ([`fleet_config::tailnet_https_proxy`], +/// #12555), else the `HTTPS_PROXY` env var. A process started from +/// a sandbox shell carries the platform egress proxy in +/// `HTTPS_PROXY`, and tailnet tunnels through it fail while the +/// process looks healthy; the Cloudflare leg +/// ([`egress_from_env_url_port`]) keeps using that ambient proxy. +/// The error strings name shapes only — never the URL (it carries +/// the credential). pub fn egress_from_env(proxy_port: u16) -> Result { + if let Some(raw) = fleet_config::tailnet_https_proxy() { + return egress_from_url(&raw, proxy_port); + } let raw = std::env::var("HTTPS_PROXY") .map_err(|_| "HTTPS_PROXY must be set (runtime proxy env)".to_string())?; egress_from_url(&raw, proxy_port) diff --git a/scripts/muse/bootstrap.sh b/scripts/muse/bootstrap.sh index c58a6f622c..6c845db760 100755 --- a/scripts/muse/bootstrap.sh +++ b/scripts/muse/bootstrap.sh @@ -475,6 +475,10 @@ PY if [ "$MODE" = userspace ]; then echo 'export HTTPS_PROXY=http://127.0.0.1:3130' >"$TS_STATE/fleet-proxy.env" say "tailnet: userspace mode; start fleet proxy with HTTPS_PROXY from $TS_STATE/fleet-proxy.env" + else + # Fleet's tailnet tunnels prefer this file over the ambient proxy, + # so a kernel-mode seat must not keep one from an earlier run. + rm -f "$TS_STATE/fleet-proxy.env" fi EFFECTIVE_HOSTNAME=$("$BIN/tailscale" --socket="$TS_SOCK" status --json 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin).get("Self",{}).get("HostName",""))' 2>/dev/null || true)