From d4dd1f72290404827472eea378d606fc2f3abf27 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 18:04:01 +0000 Subject: [PATCH 1/2] fleet: start an auto-spawned broker on the seat's tailnet proxy A fleet client that finds no broker spawns `fleet proxy serve` with its own environment. From a sandbox shell that carries the platform egress proxy in HTTPS_PROXY, the broker then opens every tailnet tunnel through the wrong proxy and the queue and shell legs fail while it looks alive. Both spawn sites now set HTTPS_PROXY from fleet-proxy.env, the file the seat bootstrap writes beside tailscaled's node state ($FLEET_PROXY_ENV, then the named agent's state, then the legacy shared state). With no such file, as on a kernel-mode seat, the ambient env is kept. Refs #12555 Co-Authored-By: Claude Opus 5.5 --- pkgs/fleet/crates/fleet-config/src/lib.rs | 140 ++++++++++++++++++ pkgs/fleet/crates/fleet-proxy/src/client.rs | 6 + .../fleet-queue/src/client/transport.rs | 14 +- 3 files changed, 156 insertions(+), 4 deletions(-) diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index b6fdd03a30..22cb7c0b12 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 tailnet proxy a broker this process auto-spawns must use +/// (#12555): the first readable [`TAILNET_PROXY_ENV_FILE`] among +/// [`tailnet_proxy_env_candidates`] that sets `HTTPS_PROXY`. A +/// spawned broker otherwise inherits the caller's ambient +/// `HTTPS_PROXY`, which in a sandbox shell is the platform egress +/// proxy, and every tailnet tunnel it opens then fails while the +/// broker looks alive. `None` (no file, as on a kernel-mode seat) +/// leaves the ambient env as it is. +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/client.rs b/pkgs/fleet/crates/fleet-proxy/src/client.rs index 6b75b7cfaf..70a2b0d593 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/client.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/client.rs @@ -213,6 +213,12 @@ fn spawn_serve(config: &Config) -> Result<(), ClientError> { ClientError::Transport(format!("broker.log: {e}")) })?)) .stderr(std::process::Stdio::from(log)); + // The broker's tailnet tunnels go through tailscaled's proxy as + // the seat recorded it, not whatever proxy this caller's shell + // carries (#12555). + if let Some(proxy) = fleet_config::tailnet_https_proxy() { + cmd.env("HTTPS_PROXY", proxy); + } unsafe { cmd.pre_exec(|| { // Detach from the caller's session, exactly like the diff --git a/pkgs/fleet/crates/fleet-queue/src/client/transport.rs b/pkgs/fleet/crates/fleet-queue/src/client/transport.rs index d46a193bfc..d3985a8559 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/transport.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/transport.rs @@ -457,12 +457,18 @@ pub(super) fn spawn_broker() { Err(_) => (std::process::Stdio::null(), std::process::Stdio::null()), }; let (program, prefix_args) = broker_program(); - let _ = std::process::Command::new(program) - .args(prefix_args) + let mut cmd = std::process::Command::new(program); + cmd.args(prefix_args) .stdout(out) .stderr(err) - .stdin(std::process::Stdio::null()) - .spawn(); + .stdin(std::process::Stdio::null()); + // The broker's tailnet tunnels go through tailscaled's proxy as + // the seat recorded it, not whatever proxy this caller's shell + // carries (#12555). + if let Some(proxy) = fleet_config::tailnet_https_proxy() { + cmd.env("HTTPS_PROXY", proxy); + } + let _ = cmd.spawn(); for _ in 0..50 { if std::path::Path::new(&broker_sock()).exists() { // Give the listener a moment to accept. From 8884e067eb9b1b364427adc57f5c4d5fe590664b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 18:07:40 +0000 Subject: [PATCH 2/2] fleet: apply the seat's tailnet proxy to tailnet tunnels only Overriding HTTPS_PROXY at broker spawn also moved the Cloudflare leg onto tailscaled's local proxy, so a stopped tailscaled took the fallback down with it. Read fleet-proxy.env where the tailnet egress is parsed instead: egress_from_env prefers the seat's recorded proxy and the Cloudflare leg keeps the ambient one. The spawn sites go back to inheriting the caller's env unchanged. The bootstrap now removes a fleet-proxy.env left from a userspace run when the seat comes up in kernel mode, since the file now steers tailnet tunnels directly. Refs #12555 Co-Authored-By: Claude Opus 5.5 --- pkgs/fleet/crates/fleet-config/src/lib.rs | 16 ++++++++-------- pkgs/fleet/crates/fleet-proxy/src/client.rs | 6 ------ pkgs/fleet/crates/fleet-proxy/src/tunnel.rs | 15 ++++++++++++--- .../crates/fleet-queue/src/client/transport.rs | 14 ++++---------- scripts/muse/bootstrap.sh | 4 ++++ 5 files changed, 28 insertions(+), 27 deletions(-) diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 22cb7c0b12..fe6eebe769 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -771,14 +771,14 @@ pub fn parse_tailnet_proxy_env(text: &str) -> Option { }) } -/// The tailnet proxy a broker this process auto-spawns must use -/// (#12555): the first readable [`TAILNET_PROXY_ENV_FILE`] among -/// [`tailnet_proxy_env_candidates`] that sets `HTTPS_PROXY`. A -/// spawned broker otherwise inherits the caller's ambient -/// `HTTPS_PROXY`, which in a sandbox shell is the platform egress -/// proxy, and every tailnet tunnel it opens then fails while the -/// broker looks alive. `None` (no file, as on a kernel-mode seat) -/// leaves the ambient env as it is. +/// 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( diff --git a/pkgs/fleet/crates/fleet-proxy/src/client.rs b/pkgs/fleet/crates/fleet-proxy/src/client.rs index 70a2b0d593..6b75b7cfaf 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/client.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/client.rs @@ -213,12 +213,6 @@ fn spawn_serve(config: &Config) -> Result<(), ClientError> { ClientError::Transport(format!("broker.log: {e}")) })?)) .stderr(std::process::Stdio::from(log)); - // The broker's tailnet tunnels go through tailscaled's proxy as - // the seat recorded it, not whatever proxy this caller's shell - // carries (#12555). - if let Some(proxy) = fleet_config::tailnet_https_proxy() { - cmd.env("HTTPS_PROXY", proxy); - } unsafe { cmd.pre_exec(|| { // Detach from the caller's session, exactly like the 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/pkgs/fleet/crates/fleet-queue/src/client/transport.rs b/pkgs/fleet/crates/fleet-queue/src/client/transport.rs index d3985a8559..d46a193bfc 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/transport.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/transport.rs @@ -457,18 +457,12 @@ pub(super) fn spawn_broker() { Err(_) => (std::process::Stdio::null(), std::process::Stdio::null()), }; let (program, prefix_args) = broker_program(); - let mut cmd = std::process::Command::new(program); - cmd.args(prefix_args) + let _ = std::process::Command::new(program) + .args(prefix_args) .stdout(out) .stderr(err) - .stdin(std::process::Stdio::null()); - // The broker's tailnet tunnels go through tailscaled's proxy as - // the seat recorded it, not whatever proxy this caller's shell - // carries (#12555). - if let Some(proxy) = fleet_config::tailnet_https_proxy() { - cmd.env("HTTPS_PROXY", proxy); - } - let _ = cmd.spawn(); + .stdin(std::process::Stdio::null()) + .spawn(); for _ in 0..50 { if std::path::Path::new(&broker_sock()).exists() { // Give the listener a moment to accept. 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)