From 6ea5770c73758750d8bfb703b95d83d5337deb62 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sun, 15 Nov 2026 19:36:50 -0600 Subject: [PATCH] feat(fleet): dual-host the secrets broker on the sandbox (#10582) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stage 2 of the broker-resilience order (#10578): stand up a standing secrets broker on the sandbox, UDS-only, kept alive by fleet init. - secrets-broker: SECRETS_BROKER_BIND=none selects UDS-only mode (no TCP listener); a live UDS owner makes a duplicate invocation exit 0, a UDS bind failure exits 3 instead of parking listenerless. - fleet init (spawn mode): the secrets-broker role is spawn-managed — probe the role socket, spawn fleet serve secrets-broker detached with SECRETS_BROKER_BIND=none, strict no-op when already running. Other non-proxy roles keep report-only semantics. - fleet-config: the built-in sandbox role set is now proxy + secrets-broker. - README: sandbox role set + provisioning note (token file at ~/.config/secrets-broker/token). --- pkgs/fleet/README.md | 21 ++- pkgs/fleet/crates/fleet-config/src/lib.rs | 19 ++- pkgs/fleet/crates/fleet-proxy/src/client.rs | 119 +++++++++++++- .../crates/fleet-queue/src/secrets_broker.rs | 147 +++++++++++++++--- 4 files changed, 265 insertions(+), 41 deletions(-) diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index dddd15e8d1..94bcde7ff3 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -285,12 +285,16 @@ rather than working around it silently. `fleet init` is location-aware: it resolves this machine's location and role set from the `[host]` section of `fleet.toml` (or `FLEET_HOST_CONFIG` / `FLEET_LOCATION`) and ensures exactly -those roles — sandbox = the session proxy under `init_mode = -"spawn"`; laptop/lab = the daemon roles under `init_mode = -"systemd"`, reported via their `fleet-.service` units and -started only through `systemctl --user`. An unknown location -reports state, starts nothing, and exits 69. The full design is -issue #5687 §§1–6. +those roles — sandbox = the session proxy plus the dual-hosted +secrets broker under `init_mode = "spawn"` (the broker is +spawn-managed UDS-only since #10582: `fleet init` spawns +`fleet serve secrets-broker` with `SECRETS_BROKER_BIND=none`, so +it never opens a network listener, and sandbox consumers reach it +directly over its role socket); laptop/lab = the daemon roles +under `init_mode = "systemd"`, reported via their +`fleet-.service` units and started only through +`systemctl --user`. An unknown location reports state, starts +nothing, and exits 69. The full design is issue #5687 §§1–6. **The deploy sequence is part of the feature** (§6): the location-aware binary has NO "no manifest ⇒ assume proxy" @@ -299,7 +303,10 @@ location-aware build replaces either live install: 1. Write the `[host]` section into that machine's `fleet.toml` (sandbox: `location = "sandbox"`, `init_mode = "spawn"`, - `[host.roles] proxy = {}`). + `[host.roles] proxy = {}` and, since #10582, + `secrets-broker = {}`; the sandbox broker also needs its token + file at `~/.config/secrets-broker/token`, holding the same + secrets-broker token the host's consumers already present). 2. Pin the sandbox's `init-ensure.sh` call site to `FLEET_LOCATION=sandbox fleet init` (belt-and-braces: the env var makes the caller's assumption explicit and survives a diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 8381da76fc..df4202ec89 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -847,7 +847,12 @@ impl Config { /// its own `[host]` section instead of growing this table. pub fn builtin_host(location: &str) -> Option<(InitMode, Vec)> { match location { - "sandbox" => Some((InitMode::Spawn, vec!["proxy".to_string()])), + // #10582: the sandbox dual-hosts the secrets broker + // (UDS-only) alongside its session proxy. + "sandbox" => Some(( + InitMode::Spawn, + vec!["proxy".to_string(), "secrets-broker".to_string()], + )), "laptop" => Some(( InitMode::Systemd, vec![ @@ -2323,10 +2328,11 @@ socket = "rel/s.sock" } #[test] - fn host_env_location_sandbox_builtin_map_is_proxy_spawn() { + fn host_env_location_sandbox_builtin_map_is_proxy_and_secrets_broker_spawn() { // The hermetic-provisioning shape: FLEET_LOCATION alone on - // a machine with no [host] section resolves to exactly - // today's sandbox behaviour (design #5687 §5/§6). + // a machine with no [host] section resolves to the sandbox + // role set (design #5687 §5/§6) — the session proxy plus, + // since #10582, the dual-hosted UDS-only secrets broker. let cfg = Config::default(); let path = PathBuf::from("/nonexistent/fleet.toml"); let resolved = cfg @@ -2334,7 +2340,10 @@ socket = "rel/s.sock" .unwrap() .unwrap(); assert_eq!(resolved.init_mode, InitMode::Spawn); - assert_eq!(resolved.roles, vec!["proxy".to_string()]); + assert_eq!( + resolved.roles, + vec!["proxy".to_string(), "secrets-broker".to_string()] + ); } #[test] diff --git a/pkgs/fleet/crates/fleet-proxy/src/client.rs b/pkgs/fleet/crates/fleet-proxy/src/client.rs index d056115d37..dc4a756c8f 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/client.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/client.rs @@ -512,8 +512,10 @@ Autostart this host's fleet roles if they are not running. The FLEET_HOST_CONFIG) names this machine's location and roles: on the sandbox that is the session proxy (probe the broker socket, sync the PATH shims when a broker answers, start one when none -does — a strict no-op when a broker is already running). An -unknown location reports state, starts nothing, and exits 69. +does — a strict no-op when a broker is already running) and the +UDS-only secrets-broker (probe its role socket, spawn it when +nothing answers — likewise a strict no-op when it is running). +An unknown location reports state, starts nothing, and exits 69. Takes no arguments."; @@ -595,10 +597,17 @@ fn run_init_resolved( for role in &active { if role == "proxy" { proxy_active = true; + } else if spawn_managed_role(role) { + // #10582: the secrets-broker is spawn-managed — + // the sandbox dual-hosts it UDS-only, kept alive + // by this same init path (the init-ensure pgrep + // pattern calls `fleet init` on every prelude). + ensure_secrets_broker_spawn(config); } else { - // v1 spawn semantics exist for the proxy only - // (the sandbox's one role, §5); any other role - // in a spawn manifest is reported, not spawned. + // v1 spawn semantics exist for the proxy (and, + // since #10582, the secrets-broker); any other + // role in a spawn manifest is reported, not + // spawned. println!( "fleet: role {role}: not spawn-managed in this build — reported, skipped" ); @@ -618,6 +627,91 @@ fn run_init_resolved( } } +/// Roles `fleet init` spawn-manages in `InitMode::Spawn` beyond +/// the session proxy itself (#10582). A pure classification so the +/// set is pinnable in tests without spawning anything. +fn spawn_managed_role(role: &str) -> bool { + role == "secrets-broker" +} + +/// Ensure the spawn-managed secrets-broker (#10582): probe its UDS +/// socket first — a live broker is a strict no-op, exactly like the +/// proxy. Only an unanswered socket spawns, detached, with +/// `SECRETS_BROKER_BIND=none`: the sandbox broker is UDS-only and +/// never opens a network listener. A spawn that never answers is +/// reported, not fatal — the proxy remains init's critical path, +/// and the next init line retries the broker. +fn ensure_secrets_broker_spawn(config: &Config) { + let socket = config.secrets_broker_socket(); + if fleet_config::probe_socket(&socket) { + println!( + "fleet: role secrets-broker: already running (uds {})", + socket.display() + ); + return; + } + match spawn_secrets_broker(&socket) { + Ok(()) => { + for _ in 0..50 { + if fleet_config::probe_socket(&socket) { + println!( + "fleet: role secrets-broker: started (uds {})", + socket.display() + ); + return; + } + std::thread::sleep(Duration::from_millis(100)); + } + println!( + "fleet: role secrets-broker: spawned but socket {} did not answer within 5s — see broker.log beside the socket", + socket.display() + ); + } + Err(e) => println!("fleet: role secrets-broker: spawn failed: {e}"), + } +} + +/// Spawn `fleet serve secrets-broker` detached (setsid, output +/// appended to broker.log beside the role socket — the proxy +/// spawn's shape), pinned to UDS-only mode via the environment so +/// no fleet.toml spelling can give the sandbox broker a TCP +/// listener (#10582). +fn spawn_secrets_broker(socket: &std::path::Path) -> Result<(), ClientError> { + use std::os::unix::process::CommandExt; + let sock_dir = socket + .parent() + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| std::path::PathBuf::from(".")); + std::fs::create_dir_all(&sock_dir) + .map_err(|e| ClientError::Transport(format!("socket dir: {e}")))?; + let log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(sock_dir.join("broker.log")) + .map_err(|e| ClientError::Transport(format!("broker.log: {e}")))?; + let exe = + std::env::current_exe().map_err(|e| ClientError::Transport(format!("current exe: {e}")))?; + let mut cmd = std::process::Command::new(exe); + cmd.args(["serve", "secrets-broker"]) + .env("SECRETS_BROKER_BIND", "none") + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::from(log.try_clone().map_err(|e| { + ClientError::Transport(format!("broker.log: {e}")) + })?)) + .stderr(std::process::Stdio::from(log)); + unsafe { + cmd.pre_exec(|| { + if libc::setsid() == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + cmd.spawn() + .map_err(|e| ClientError::Transport(format!("spawn secrets-broker: {e}")))?; + Ok(()) +} + /// The unknown-location report (#5687 §4): every source consulted /// and what detection found. Detection informs this report only — /// it never selects roles (§3). @@ -830,6 +924,21 @@ mod tests { assert_eq!(code, 0); } + #[test] + fn spawn_managed_role_is_exactly_the_secrets_broker() { + // #10582 oracle: in spawn mode only the secrets-broker is + // spawn-managed beyond the proxy; every other daemon role + // keeps the report-only semantics, so a typo'd or future + // role can never silently acquire a spawn path. + assert!(spawn_managed_role("secrets-broker")); + for role in ["queue-broker", "search", "laptop-agent", "proxy", "prox"] { + assert!( + !spawn_managed_role(role), + "{role} must not be spawn-managed" + ); + } + } + #[test] fn init_spawn_mode_reports_non_proxy_roles_without_a_spawn() { let host = ResolvedHost { diff --git a/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs index 306faee030..fab366031f 100644 --- a/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs @@ -32,7 +32,10 @@ //! serves what it finds, so a secret minted moments ago is visible //! immediately instead of at the next TTL refresh (#6275). //! -//! Env: SECRETS_BROKER_BIND (default 100.99.113.103:4800), +//! Env: SECRETS_BROKER_BIND (default 100.99.113.103:4800; the +//! literal `none` disables the TCP listener entirely — +//! UDS-only mode for hosts that must never open a network +//! listener, #10582), //! SECRETS_BROKER_SOCKET (Unix socket dual-bind, #6216; default //! ~/.config/secrets-broker/broker.sock via fleet-config), //! SECRETS_BROKER_TOKEN_FILE (default ~/.config/secrets-broker/token), @@ -629,10 +632,24 @@ pub fn parse_ttl_s(raw: Option<&str>) -> Result { } } +/// The TCP bind for this broker, resolved from `SECRETS_BROKER_BIND` +/// (#10582): unset selects the laptop tailnet default; the literal +/// `none` (any case, surrounding whitespace ignored) selects NO TCP +/// listener at all — UDS-only mode, for a host that must never open +/// a network listener (the sandbox dual-host, whose consumers reach +/// the broker over its Unix socket). Any other value is used as the +/// bind address as-is. +fn tcp_bind(raw: Option<&str>) -> Option { + match raw { + None => Some("100.99.113.103:4800".to_string()), + Some(v) if v.trim().eq_ignore_ascii_case("none") => None, + Some(v) => Some(v.to_string()), + } +} + pub fn run() -> i32 { use std::io::Read as _; - let bind = - std::env::var("SECRETS_BROKER_BIND").unwrap_or_else(|_| "100.99.113.103:4800".to_string()); + let bind = tcp_bind(std::env::var("SECRETS_BROKER_BIND").ok().as_deref()); let home = match crate::home::from_env() { Ok(home) => home, Err(error) => { @@ -686,23 +703,40 @@ pub fn run() -> i32 { }); } - let server = match Server::http(&bind) { - Ok(server) => server, - Err(e) => { - crate::log::info("secrets-broker", &format!("cannot bind {bind}: {e:?}")); - return 3; + let server = match &bind { + Some(bind) => match Server::http(bind) { + Ok(server) => { + crate::log::info("secrets-broker", &format!("listening on {bind}")); + Some(server) + } + Err(e) => { + crate::log::info("secrets-broker", &format!("cannot bind {bind}: {e:?}")); + return 3; + } + }, + None => { + crate::log::info( + "secrets-broker", + "TCP listener disabled (SECRETS_BROKER_BIND=none); UDS only", + ); + None } }; - crate::log::info("secrets-broker", &format!("listening on {bind}")); - // Dual-bind (#6216): the same handler over a Unix socket. A bind - // failure or a live owner degrades to TCP only, never to exit: - // the TCP listener is the established surface. + // Dual-bind (#6216): the same handler over a Unix socket. With a + // TCP listener, a bind failure or a live owner degrades to TCP + // only, never to exit: the TCP listener is the established + // surface. In UDS-only mode (#10582) the socket IS the only + // surface: a live owner means this invocation is a duplicate + // (exit 0, the owner keeps serving), and a bind failure leaves + // no listener at all (exit 3). let socket_path = fleet_config::Config::load() .unwrap_or_default() .secrets_broker_socket(); + let mut uds_serving = false; match crate::uds_http::bind_socket(&socket_path) { Ok(Some(listener)) => { + uds_serving = true; let st = Arc::clone(&state); let tok = token.clone(); crate::log::info( @@ -748,19 +782,57 @@ pub fn run() -> i32 { ); }); } - Ok(None) => crate::log::info( - "secrets-broker", - &format!( - "uds {} already owned by a live broker; TCP only", - socket_path.display() - ), - ), - Err(e) => crate::log::info( - "secrets-broker", - &format!("cannot bind uds {}: {e}; TCP only", socket_path.display()), - ), + Ok(None) => { + if bind.is_none() { + crate::log::info( + "secrets-broker", + &format!( + "uds {} already owned by a live broker; UDS-only duplicate exiting", + socket_path.display() + ), + ); + return 0; + } + crate::log::info( + "secrets-broker", + &format!( + "uds {} already owned by a live broker; TCP only", + socket_path.display() + ), + ); + } + Err(e) => { + if bind.is_none() { + crate::log::info( + "secrets-broker", + &format!( + "cannot bind uds {}: {e}; UDS-only mode has no other listener", + socket_path.display() + ), + ); + return 3; + } + crate::log::info( + "secrets-broker", + &format!("cannot bind uds {}: {e}; TCP only", socket_path.display()), + ); + } } + let Some(server) = server else { + // UDS-only mode (#10582): the UDS serve thread owns every + // request; park the main thread so the process (and its + // background refresh loop) stays resident until killed. + // Reaching here without a serving socket is impossible — + // the arms above return first — but never park listenerless. + if !uds_serving { + return 3; + } + loop { + std::thread::sleep(Duration::from_secs(3600)); + } + }; + for mut req in server.incoming_requests() { let state = Arc::clone(&state); let token = token.clone(); @@ -844,9 +916,36 @@ mod tests { use super::{ CachedSecret, DEFAULT_TTL_S, MIN_TTL_S, State, fetch_through_with, handle_request, install_refresh, now_unix, parse_list_entries, parse_ttl_s, pre_body_refusal, - resolve_list_id, url_decode, + resolve_list_id, tcp_bind, url_decode, }; + #[test] + fn tcp_bind_unset_is_the_tailnet_default() { + // Oracle: the laptop's established listener is unchanged + // when SECRETS_BROKER_BIND is not set (#10582 must not move + // the existing dual-host's TCP surface). + assert_eq!(tcp_bind(None).as_deref(), Some("100.99.113.103:4800")); + } + + #[test] + fn tcp_bind_none_disables_the_tcp_listener() { + // Oracle: UDS-only mode is selected by the literal `none`, + // case-insensitively and ignoring surrounding whitespace — + // and by nothing else, so a real bind address (including a + // loopback one) still passes through untouched. + assert_eq!(tcp_bind(Some("none")), None); + assert_eq!(tcp_bind(Some("NONE")), None); + assert_eq!(tcp_bind(Some(" None ")), None); + assert_eq!( + tcp_bind(Some("127.0.0.1:4800")).as_deref(), + Some("127.0.0.1:4800") + ); + assert_eq!( + tcp_bind(Some("100.99.113.103:4800")).as_deref(), + Some("100.99.113.103:4800") + ); + } + #[test] fn pre_body_refusal_decides_from_headers_alone() { // #6515 oracle (thread 4492609604): the gate's answer