diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 35d1fdc9e9..47fc936c17 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -415,6 +415,27 @@ fn resolve_under_home(path: &str) -> PathBuf { resolve_under(&home_dir(), &PathBuf::from(path)) } +/// The transport a fleet client should use to reach a broker role +/// on this host (#6218, from the #5699 design adopted 2026-11-05): +/// the role's Unix socket, or its TCP listener. Selected by +/// [`Config::role_transport_choice`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RoleTransport { + Socket(PathBuf), + Tcp, +} + +/// Probe a broker role's Unix socket: the file exists AND a connect +/// succeeds. A stale socket file (left by a dead broker) fails the +/// connect, so callers fall back to TCP within the same connection +/// attempt (#6218 acceptance). +pub fn probe_socket(path: &std::path::Path) -> bool { + if !path.exists() { + return false; + } + std::os::unix::net::UnixStream::connect(path).is_ok() +} + impl Config { /// The config file path: `$FLEET_CONFIG`, else /// `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`. @@ -592,6 +613,50 @@ impl Config { .filter(|v| v == "socket" || v == "tcp") } + /// A broker role's Unix socket path by role name (#6218): + /// `queue-broker` / `secrets-broker`; `None` for an unknown role. + pub fn role_socket(&self, role: &str) -> Option { + match role { + "queue-broker" => Some(self.queue_broker_socket()), + "secrets-broker" => Some(self.secrets_broker_socket()), + _ => None, + } + } + + /// The transport a client should use to reach a broker role + /// (#6218): the `[] transport` preference wins ("tcp" + /// selects TCP without probing; "socket" selects the role's + /// Unix socket); with no preference, probe the role socket -- + /// a socket that answers selects UDS, an absent or stale one + /// selects TCP. `None` for an unknown role (the caller then + /// keeps whatever route it already had). + pub fn role_transport_choice(&self, role: &str) -> Option { + let socket = self.role_socket(role)?; + let probe_ok = probe_socket(&socket); + Some(Self::role_transport_choice_from( + self.role_transport(role).as_deref(), + socket, + probe_ok, + )) + } + + /// The pure core of [`Config::role_transport_choice`], split + /// out so the socket-present / socket-absent / socket-stale + /// cases are testable without a live broker: `probe_ok` is the + /// probe's verdict (a stale socket file probes false). + fn role_transport_choice_from( + pref: Option<&str>, + socket: PathBuf, + probe_ok: bool, + ) -> RoleTransport { + match pref { + Some("tcp") => RoleTransport::Tcp, + Some("socket") => RoleTransport::Socket(socket), + _ if probe_ok => RoleTransport::Socket(socket), + _ => RoleTransport::Tcp, + } + } + /// A role socket's resolution (#6215, design #5699): explicit /// env > config > `$XDG_RUNTIME_DIR/fleet/.sock` when /// `XDG_RUNTIME_DIR` is an absolute non-empty base (tmpfs, @@ -1066,6 +1131,74 @@ transport = "udp" assert_eq!(Config::default().role_transport("queue-broker"), None); } + #[test] + fn role_transport_choice_pref_wins_then_probe() { + // #6218: explicit preference beats the probe; with no + // preference the probe decides (present -> socket, absent + // or stale -> TCP). + let sock = PathBuf::from("/tmp/role.sock"); + assert_eq!( + Config::role_transport_choice_from(Some("tcp"), sock.clone(), true), + RoleTransport::Tcp + ); + assert_eq!( + Config::role_transport_choice_from(Some("socket"), sock.clone(), false), + RoleTransport::Socket(sock.clone()) + ); + assert_eq!( + Config::role_transport_choice_from(None, sock.clone(), true), + RoleTransport::Socket(sock.clone()) + ); + assert_eq!( + Config::role_transport_choice_from(None, sock.clone(), false), + RoleTransport::Tcp + ); + // An unrecognized preference degrades to the probe, exactly + // like role_transport's None. + assert_eq!( + Config::role_transport_choice_from(Some("udp"), sock, false), + RoleTransport::Tcp + ); + } + + #[test] + fn probe_socket_distinguishes_live_absent_and_stale() { + // #6218 acceptance: socket-present, socket-absent, and + // socket-stale probe outcomes. + let dir = + std::env::temp_dir().join(format!("fleet-config-probe-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create temp dir"); + let live = dir.join("live.sock"); + let stale = dir.join("stale.sock"); + let absent = dir.join("absent.sock"); + let listener = std::os::unix::net::UnixListener::bind(&live).expect("bind live socket"); + assert!(probe_socket(&live), "live socket must probe true"); + drop(listener); + // The socket file outlives its listener: stale. + assert!(live.exists(), "socket file remains after drop"); + assert!(!probe_socket(&live), "stale socket must probe false"); + std::fs::write(&stale, b"not a socket").expect("write stale placeholder"); + assert!(!probe_socket(&stale), "regular file must probe false"); + assert!(!probe_socket(&absent), "absent socket must probe false"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn role_socket_dispatches_known_roles_only() { + let cfg = Config::default(); + assert_eq!( + cfg.role_socket("queue-broker"), + Some(cfg.queue_broker_socket()) + ); + assert_eq!( + cfg.role_socket("secrets-broker"), + Some(cfg.secrets_broker_socket()) + ); + assert_eq!(cfg.role_socket("dispatch"), None); + assert_eq!(cfg.role_transport_choice("dispatch"), None); + } + #[test] fn role_config_rejects_unknown_fields() { // #6215: deny-unknown-fields discipline holds for the new diff --git a/pkgs/fleet/crates/fleet-queue/Cargo.toml b/pkgs/fleet/crates/fleet-queue/Cargo.toml index 135d05d46d..d6d9e976d3 100644 --- a/pkgs/fleet/crates/fleet-queue/Cargo.toml +++ b/pkgs/fleet/crates/fleet-queue/Cargo.toml @@ -12,7 +12,7 @@ description = "The fleet queue domain: the repo-queue client surface plus the qu # without the client, and a client-only build is possible for the # standalone artifact. [features] -client = [] +client = ["dep:fleet-config"] queue-broker = ["client", "dep:tiny_http", "dep:ureq", "dep:fleet-config"] secrets-broker = ["dep:tiny_http", "dep:fleet-config"] diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index 33b1c98a2f..3143ae3c93 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -8,6 +8,11 @@ //! socket); on the laptop itself, a direct HTTP connection selected //! by REPO_QUEUE_BROKER_URL or ~/.config/repo-queue/broker-url (the //! opencode claimant and the worker sessions it launches use this). +//! Without a configured URL, the direct path is probe-selected +//! (#6218): fleet-config's transport choice for the queue-broker +//! role picks the broker's Unix socket when it answers; an absent +//! or stale socket keeps the session-proxy route, and a failed +//! UDS attempt falls back to it within the same call. //! No Bitwarden fetch, no direct Supabase access. Exit 3 means the //! broker path itself is unavailable. //! @@ -53,7 +58,14 @@ fn print_json(v: &Value) { // --------------------------------------------------------------------------- fn broker_sock() -> String { - broker_sock_from_home(Some(&home())).unwrap_or_else(|error| die(3, error)) + // #6218: ask fleet-config instead of hardcoding the path -- + // env beats the config file beats the compiled-in default, + // which is the same path broker_sock_from_home builds. A + // config load error falls back to the home-anchored default. + match fleet_config::Config::load() { + Ok(cfg) => cfg.broker_socket().to_string_lossy().into_owned(), + Err(_) => broker_sock_from_home(Some(&home())).unwrap_or_else(|error| die(3, error)), + } } fn broker_sock_from_home(home_dir: Option<&str>) -> Result { @@ -88,35 +100,60 @@ fn direct_broker_url() -> Option { None } -fn direct_roundtrip(url: &str, path: &str, body: &Value) -> Result { - let rest = url - .strip_prefix("http://") - .ok_or("broker URL must be http://host:port")?; - let hostport = rest.trim_end_matches('/'); - if hostport.is_empty() || hostport.contains('/') { - return Err(format!("bad broker URL {url:?}")); +/// The direct route to the queue-broker (#6218): its TCP +/// listener, or its Unix socket (the broker dual-binds both, +/// #6216). Selected by [`direct_route`]. +#[derive(Debug, PartialEq, Eq)] +enum DirectRoute { + Tcp(String), + Unix(std::path::PathBuf), +} + +/// Parse a configured broker URL into a route: `unix://` +/// selects the socket; anything else keeps the historical +/// `http://host:port` TCP reading (validated in the TCP leg). +fn route_from_configured_url(url: &str) -> Result { + if let Some(p) = url.strip_prefix("unix://") { + if p.is_empty() { + return Err(format!("bad broker URL {url:?}")); + } + return Ok(DirectRoute::Unix(std::path::PathBuf::from(p))); + } + Ok(DirectRoute::Tcp(url.to_string())) +} + +/// Which direct route, if any (#6218): an explicitly configured +/// URL (env or broker-url file) wins; otherwise fleet-config's +/// probe-based choice for the queue-broker role -- a live role +/// socket selects UDS, the TCP choice keeps today's behavior +/// (None: the session-proxy route below IS the sandbox's TCP +/// route, and sandbox consumers are untouched by design). +fn direct_route() -> Option { + if let Some(url) = direct_broker_url() { + return match route_from_configured_url(&url) { + Ok(route) => Some(route), + Err(e) => die(3, &e), + }; } + let cfg = fleet_config::Config::load().unwrap_or_default(); + match cfg.role_transport_choice("queue-broker") { + Some(fleet_config::RoleTransport::Socket(socket)) => Some(DirectRoute::Unix(socket)), + _ => None, + } +} + +fn direct_token() -> Result { let token_file_env = std::env::var("REPO_QUEUE_TOKEN_FILE").ok(); let home_env = std::env::var("HOME").ok(); let token_file = token_file_from_env(token_file_env.as_deref(), home_env.as_deref()) .unwrap_or_else(|error| die(3, error)); let token = crate::token_file::load_token_file(&token_file)?; - let token = token.trim(); - let payload = serde_json::to_vec(body).unwrap(); - let mut s = TcpStream::connect(hostport) - .map_err(|e| format!("cannot connect to queue-broker at {hostport}: {e}"))?; - s.set_read_timeout(Some(Duration::from_secs(300))).ok(); - s.set_write_timeout(Some(Duration::from_secs(60))).ok(); - let head = format!( - "POST {path} HTTP/1.1\r\nHost: {hostport}\r\nX-Agent-Token: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - payload.len() - ); - s.write_all(head.as_bytes()) - .and_then(|_| s.write_all(&payload)) - .map_err(|e| format!("queue-broker write failed: {e}"))?; - let mut raw = Vec::new(); - s.read_to_end(&mut raw) - .map_err(|e| format!("queue-broker read failed: {e}"))?; + Ok(token.trim().to_string()) +} + +/// The response handling both direct legs share: status line, +/// JSON body, 401 and >=400 die with exit 3 exactly as before. +fn finish_direct_response(raw: &[u8]) -> Result { let split = raw .windows(4) .position(|w| w == b"\r\n\r\n") @@ -142,9 +179,76 @@ fn direct_roundtrip(url: &str, path: &str, body: &Value) -> Result Result { + let rest = url + .strip_prefix("http://") + .ok_or("broker URL must be http://host:port")?; + let hostport = rest.trim_end_matches('/'); + if hostport.is_empty() || hostport.contains('/') { + return Err(format!("bad broker URL {url:?}")); + } + let token = direct_token()?; + let payload = serde_json::to_vec(body).unwrap(); + let mut s = TcpStream::connect(hostport) + .map_err(|e| format!("cannot connect to queue-broker at {hostport}: {e}"))?; + s.set_read_timeout(Some(Duration::from_secs(300))).ok(); + s.set_write_timeout(Some(Duration::from_secs(60))).ok(); + let head = format!( + "POST {path} HTTP/1.1\r\nHost: {hostport}\r\nX-Agent-Token: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + s.write_all(head.as_bytes()) + .and_then(|_| s.write_all(&payload)) + .map_err(|e| format!("queue-broker write failed: {e}"))?; + let mut raw = Vec::new(); + s.read_to_end(&mut raw) + .map_err(|e| format!("queue-broker read failed: {e}"))?; + finish_direct_response(&raw) +} + +/// The UDS leg of the direct path (#6218): the same HTTP/1.1 +/// exchange over the queue-broker's Unix socket. The broker's +/// handler is transport-agnostic (uds_http), so the wire surface +/// -- routes, token auth, JSON envelope -- is identical. +fn direct_uds_roundtrip( + socket: &std::path::Path, + path: &str, + body: &Value, +) -> Result { + let token = direct_token()?; + let payload = serde_json::to_vec(body).unwrap(); + let mut s = UnixStream::connect(socket).map_err(|e| { + format!( + "cannot connect to queue-broker at unix://{}: {e}", + socket.display() + ) + })?; + s.set_read_timeout(Some(Duration::from_secs(300))).ok(); + s.set_write_timeout(Some(Duration::from_secs(60))).ok(); + let head = format!( + "POST {path} HTTP/1.1\r\nHost: localhost\r\nX-Agent-Token: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + s.write_all(head.as_bytes()) + .and_then(|_| s.write_all(&payload)) + .map_err(|e| format!("queue-broker write failed: {e}"))?; + let mut raw = Vec::new(); + s.read_to_end(&mut raw) + .map_err(|e| format!("queue-broker read failed: {e}"))?; + finish_direct_response(&raw) +} + fn broker_roundtrip(path: &str, body: &Value) -> Result { - if let Some(url) = direct_broker_url() { - return direct_roundtrip(&url, path, body); + match direct_route() { + Some(DirectRoute::Tcp(url)) => return direct_tcp_roundtrip(&url, path, body), + Some(DirectRoute::Unix(socket)) => match direct_uds_roundtrip(&socket, path, body) { + Ok(v) => return Ok(v), + // #6218 acceptance: a failed socket attempt falls back + // to TCP within the same connection attempt -- here the + // session-proxy route below, the sandbox's TCP route. + Err(_) => {} + }, + None => {} } let payload = json!({ "method": "POST", @@ -1301,8 +1405,7 @@ fn claim_output(resp: &Value) -> (Value, i32) { // payload-less packet — never print it as a claimed task. Rows // without a payload field keep the #5486 verbatim contract. if let Some(payload) = row.get("payload") { - let missing = payload.is_null() - || payload.as_object().is_some_and(|o| o.is_empty()); + let missing = payload.is_null() || payload.as_object().is_some_and(|o| o.is_empty()); if missing { eprint(&format!( "repo-queue: claim skipped: task {} arrived payload-less (#5444); treating as no claim", @@ -1843,7 +1946,10 @@ mod tests { #[test] fn task_issue_reads_payload_identity() { let row = json!({"payload": {"repo": "developing-today/code", "issue": {"number": 6741}}}); - assert_eq!(task_issue(&row), ("developing-today/code".to_string(), 6741)); + assert_eq!( + task_issue(&row), + ("developing-today/code".to_string(), 6741) + ); assert_eq!(task_issue(&json!({"payload": {}})), (String::new(), 0)); } @@ -1873,8 +1979,7 @@ mod tests { // loudly — it never resolves to the shadow default. let packet = json!({"queue": "repo-health-code-pilot"}); assert_eq!( - resolve_enqueue_queue(Some("repo-health-nix-pilot"), &packet, Some("env-q")) - .unwrap(), + resolve_enqueue_queue(Some("repo-health-nix-pilot"), &packet, Some("env-q")).unwrap(), "repo-health-nix-pilot" ); assert_eq!( @@ -1902,6 +2007,34 @@ mod tests { ); } + #[test] + fn configured_url_routes_unix_and_http_forms() { + // #6218: unix:// selects the socket route; the historical + // http:// form stays TCP; an empty unix path is rejected. + assert_eq!( + route_from_configured_url("unix:///run/fleet/queue-broker.sock"), + Ok(DirectRoute::Unix(std::path::PathBuf::from( + "/run/fleet/queue-broker.sock" + ))) + ); + assert_eq!( + route_from_configured_url("http://100.99.113.103:4801"), + Ok(DirectRoute::Tcp("http://100.99.113.103:4801".to_string())) + ); + assert!(route_from_configured_url("unix://").is_err()); + } + + #[test] + fn finish_direct_response_parses_status_and_body() { + // #6218: both direct legs share this response handling. + let ok = b"HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\n{\"ok\":true}"; + assert_eq!( + finish_direct_response(ok).expect("200 parses"), + json!({"ok": true}) + ); + assert!(finish_direct_response(b"no header split").is_err()); + } + #[test] fn token_file_empty_env_values_use_home_default() { let home_dir = "/home/test"; diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index c6d5de721d..46d770979e 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -13,7 +13,8 @@ //! QUEUE_BROKER_SOCKET (Unix socket dual-bind, #6216; default //! ~/.config/queue-broker/broker.sock via fleet-config), //! QUEUE_BROKER_TOKEN_FILE (default ~/.config/queue-broker/token), -//! QUEUE_BROKER_SECRETS_URL (default http://100.99.113.103:4800), +//! QUEUE_BROKER_SECRETS_URL (default http://100.99.113.103:4800, +//! or unix:// for the secrets broker's socket, #6218), //! QUEUE_BROKER_SECRETS_TOKEN_FILE (default ~/.config/secrets-broker/token). //! //! Backend (#6741): QUEUE_BROKER_BACKEND=postgres (default; the @@ -121,6 +122,9 @@ impl SecretSource for DirectSecrets { name: name.to_string(), detail, }; + if let Some(socket) = self.url.strip_prefix("unix://") { + return self.resolve_uds(name, socket); + } let url = format!("{}/secret/{}", self.url, name); let mut resp = self .agent @@ -130,28 +134,108 @@ impl SecretSource for DirectSecrets { .map_err(|e| unavailable(format!("secrets broker unreachable: {e}")))?; let status = resp.status().as_u16(); let text = resp.body_mut().read_to_string().unwrap_or_default(); - if status == 404 { - return Err(SecretError::NotFound { - source: "secrets-broker", - name: name.to_string(), - }); + secret_from_response(name, status, &text) + } +} + +impl DirectSecrets { + /// The UDS leg (#6218): the same GET /secret/ exchange + /// over the secrets broker's Unix socket -- its handler is + /// transport-agnostic (uds_http), so routes and auth are + /// identical. A connect failure falls back to the TCP endpoint + /// within the same resolve (the #6218 stale-socket rule). + fn resolve_uds(&self, name: &str, socket: &str) -> Result { + use std::io::{Read, Write}; + let unavailable = |detail: String| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail, + }; + let mut stream = match std::os::unix::net::UnixStream::connect(socket) { + Ok(stream) => stream, + Err(_) => { + let tcp = DirectSecrets { + url: "http://100.99.113.103:4800".to_string(), + token: self.token.clone(), + agent: self.agent.clone(), + }; + return tcp.resolve(name); + } + }; + stream.set_read_timeout(Some(Duration::from_secs(90))).ok(); + let req = format!( + "GET /secret/{name} HTTP/1.1\r\nHost: localhost\r\nX-Agent-Token: {}\r\nConnection: close\r\n\r\n", + self.token + ); + stream + .write_all(req.as_bytes()) + .map_err(|e| unavailable(format!("secrets broker unreachable: {e}")))?; + let mut raw = Vec::new(); + stream + .read_to_end(&mut raw) + .map_err(|e| unavailable(format!("secrets broker unreachable: {e}")))?; + let text_raw = String::from_utf8_lossy(&raw).into_owned(); + let mut parts = text_raw.splitn(2, "\r\n\r\n"); + let head = parts.next().unwrap_or(""); + let status: u16 = head + .split_whitespace() + .nth(1) + .and_then(|c| c.parse().ok()) + .unwrap_or(0); + let text = parts.next().unwrap_or("").to_string(); + secret_from_response(name, status, &text) + } +} + +/// The response tail both DirectSecrets legs share: 404 is +/// NotFound, >=300 is Unavailable, a 2xx body must carry `value`. +fn secret_from_response(name: &str, status: u16, text: &str) -> Result { + let unavailable = |detail: String| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail, + }; + if status == 404 { + return Err(SecretError::NotFound { + source: "secrets-broker", + name: name.to_string(), + }); + } + if status >= 300 { + return Err(unavailable(format!( + "secrets broker HTTP {status} for {name}: {}", + trim(text, 200) + ))); + } + let v: Value = serde_json::from_str(text) + .map_err(|e| unavailable(format!("secrets broker bad JSON for {name}: {e}")))?; + v.get("value") + .and_then(|x| x.as_str()) + .map(|s| SecretValue::from_resolved(s.to_string())) + .ok_or(SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: format!("secrets broker response for {name} has no value"), + }) +} + +/// The queue broker's secrets-broker endpoint (#6218): an explicit +/// QUEUE_BROKER_SECRETS_URL wins (http:// or unix:// form); without +/// one, fleet-config's probe-based choice for the secrets-broker +/// role decides -- a live role socket selects the UDS endpoint, +/// otherwise the historical TCP default. +fn default_secrets_url(explicit: Option) -> String { + if let Some(u) = explicit { + if !u.trim().is_empty() { + return u; } - if status >= 300 { - return Err(unavailable(format!( - "secrets broker HTTP {status} for {name}: {}", - trim(&text, 200) - ))); + } + let cfg = fleet_config::Config::load().unwrap_or_default(); + match cfg.role_transport_choice("secrets-broker") { + Some(fleet_config::RoleTransport::Socket(socket)) => { + format!("unix://{}", socket.display()) } - let v: Value = serde_json::from_str(&text) - .map_err(|e| unavailable(format!("secrets broker bad JSON for {name}: {e}")))?; - v.get("value") - .and_then(|x| x.as_str()) - .map(|s| SecretValue::from_resolved(s.to_string())) - .ok_or(SecretError::Unavailable { - source: "secrets-broker", - name: name.to_string(), - detail: format!("secrets broker response for {name} has no value"), - }) + _ => "http://100.99.113.103:4800".to_string(), } } @@ -857,8 +941,7 @@ pub fn run() -> i32 { crate::log::info("queue-broker", &e); std::process::exit(3); }); - let secrets_url = std::env::var("QUEUE_BROKER_SECRETS_URL") - .unwrap_or_else(|_| "http://100.99.113.103:4800".to_string()); + let secrets_url = default_secrets_url(std::env::var("QUEUE_BROKER_SECRETS_URL").ok()); let secrets_token_file = std::env::var("QUEUE_BROKER_SECRETS_TOKEN_FILE") .unwrap_or_else(|_| format!("{home}/.config/secrets-broker/token")); let secrets_token = @@ -1021,6 +1104,84 @@ pub fn run() -> i32 { mod tests { use super::*; + #[test] + fn secrets_url_explicit_wins_and_default_is_a_known_endpoint() { + // #6218: QUEUE_BROKER_SECRETS_URL beats probe selection in + // both forms; empty counts as unset; the default is either + // the probed socket endpoint or the historical TCP one. + assert_eq!( + default_secrets_url(Some("http://127.0.0.1:9".to_string())), + "http://127.0.0.1:9" + ); + assert_eq!( + default_secrets_url(Some("unix:///tmp/s.sock".to_string())), + "unix:///tmp/s.sock" + ); + let default = default_secrets_url(Some(" ".to_string())); + assert!( + default == "http://100.99.113.103:4800" || default.starts_with("unix://"), + "unexpected default endpoint: {default}" + ); + let default_none = default_secrets_url(None); + assert_eq!(default_none, default); + } + + #[test] + fn secret_from_response_maps_statuses() { + // #6218: the shared tail of both DirectSecrets legs. + let ok = secret_from_response("n", 200, "{\"value\":\"v1\"}").expect("200 resolves"); + assert_eq!(ok.expose(), "v1"); + assert!(matches!( + secret_from_response("n", 404, ""), + Err(SecretError::NotFound { .. }) + )); + assert!(matches!( + secret_from_response("n", 500, "boom"), + Err(SecretError::Unavailable { .. }) + )); + assert!(matches!( + secret_from_response("n", 200, "{}"), + Err(SecretError::Unavailable { .. }) + )); + } + + #[test] + fn direct_secrets_resolves_over_a_unix_socket() { + // #6218: the UDS leg speaks the same GET /secret/ + // exchange the TCP leg makes with ureq. + use std::io::{Read, Write}; + let dir = std::env::temp_dir().join(format!("fleet-queue-uds-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create temp dir"); + let socket = dir.join("secrets.sock"); + let listener = std::os::unix::net::UnixListener::bind(&socket).expect("bind socket"); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept"); + let mut buf = [0u8; 2048]; + let _ = stream.read(&mut buf); + let body = "{\"value\":\"uds-secret\"}"; + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + stream.write_all(resp.as_bytes()).expect("write reply"); + }); + let agent: ureq::Agent = ureq::Agent::config_builder() + .http_status_as_error(false) + .build() + .into(); + let source = DirectSecrets { + url: format!("unix://{}", socket.display()), + token: "test-token".to_string(), + agent, + }; + let value = source.resolve("some-name").expect("UDS resolve succeeds"); + assert_eq!(value.expose(), "uds-secret"); + server.join().expect("server thread"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn list_limit_rejects_out_of_range_before_the_postgrest_path() { // #6419: the broker interpolated the limit unchecked, so a diff --git a/pkgs/fleet/crates/fleet-secrets/src/lib.rs b/pkgs/fleet/crates/fleet-secrets/src/lib.rs index 537eb1c133..ce3bf0f376 100644 --- a/pkgs/fleet/crates/fleet-secrets/src/lib.rs +++ b/pkgs/fleet/crates/fleet-secrets/src/lib.rs @@ -153,15 +153,23 @@ impl Resolver { Resolver { sources } } - /// The default chain for a resolved fleet config. + /// The default chain for a resolved fleet config. On a host + /// where the secrets-broker's own socket answers (the laptop, + /// #6218), the direct source comes first: there is no session + /// broker there. On the sandbox the probe selects TCP, no + /// direct source is inserted, and the chain is exactly the + /// historical broker-protocol-then-`bws` shape. pub fn default_chain(config: &fleet_config::Config) -> Resolver { - Resolver::new(vec![ - Box::new(BrokerSource { - broker_socket: config.broker_socket(), - token_file: config.secrets_token_file(), - }), - Box::new(BwsSource::new()), - ]) + let mut sources: Vec> = Vec::new(); + if let Some(direct) = DirectBrokerSource::from_config(config) { + sources.push(Box::new(direct)); + } + sources.push(Box::new(BrokerSource { + broker_socket: config.broker_socket(), + token_file: config.secrets_token_file(), + })); + sources.push(Box::new(BwsSource::new())); + Resolver::new(sources) } pub fn resolve(&self, name: &str) -> Result { @@ -326,6 +334,162 @@ impl SecretSource for BrokerSource { } } +/// The secrets-broker token file for direct (laptop-local) +/// connections: the broker's own config dir, sibling of its socket +/// and of the queue client's direct token default (#6218). +pub const DIRECT_SECRETS_TOKEN_FILE: &str = ".config/secrets-broker/token"; + +/// Source 1b: the secrets-broker protocol, direct over the +/// broker's own Unix socket (#6218) -- the laptop-local path. On +/// the laptop there is no session broker; the secrets broker +/// dual-binds its role socket (#6216) with the same handler, so +/// the exchange is a plain HTTP/1.1 GET. Unlike [`BrokerSource`], +/// which only *names* the token file for the session proxy, this +/// source reads the token file itself -- the value goes into the +/// request header and nowhere else. +pub struct DirectBrokerSource { + pub socket: PathBuf, + pub token_file: PathBuf, +} + +impl DirectBrokerSource { + /// The direct source for a resolved config, when fleet-config's + /// probe-based choice for the secrets-broker role selects the + /// socket (#6218). `None` on the TCP choice (the sandbox): the + /// caller keeps the session-broker source. + pub fn from_config(config: &fleet_config::Config) -> Option { + match config.role_transport_choice("secrets-broker") { + Some(fleet_config::RoleTransport::Socket(socket)) => Some(DirectBrokerSource { + socket, + token_file: fleet_config::Config::home_dir().join(DIRECT_SECRETS_TOKEN_FILE), + }), + _ => None, + } + } + + /// One GET exchange over the broker socket: status + JSON body. + fn get(&self, path: &str, name: &str) -> Result<(u16, serde_json::Value), SecretError> { + use std::io::{Read, Write}; + let unavailable = |detail: String| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail, + }; + let token = std::fs::read_to_string(&self.token_file).map_err(|e| { + unavailable(format!( + "secrets-broker token file {}: {}", + self.token_file.display(), + e.kind() + )) + })?; + let mut stream = UnixStream::connect(&self.socket).map_err(|e| { + unavailable(format!( + "secrets-broker socket {}: {}", + self.socket.display(), + e.kind() + )) + })?; + let req = format!( + "GET {path} HTTP/1.1\r\nHost: localhost\r\nX-Agent-Token: {}\r\nConnection: close\r\n\r\n", + token.trim() + ); + stream + .write_all(req.as_bytes()) + .map_err(|e| unavailable(e.to_string()))?; + let mut raw = Vec::new(); + stream + .read_to_end(&mut raw) + .map_err(|e| unavailable(e.to_string()))?; + let text = String::from_utf8_lossy(&raw).into_owned(); + let mut parts = text.splitn(2, "\r\n\r\n"); + let head = parts.next().unwrap_or(""); + let status: u16 = head + .split_whitespace() + .nth(1) + .and_then(|c| c.parse().ok()) + .ok_or_else(|| unavailable("secrets-broker bad reply".to_string()))?; + let body: serde_json::Value = + serde_json::from_str(parts.next().unwrap_or("")).unwrap_or(serde_json::Value::Null); + Ok((status, body)) + } + + /// The broker's names listing over the direct socket -- the + /// same `GET /secrets` route [`BrokerSource::list_names`] + /// reads through the session broker. Names only. + pub fn list_names(&self) -> Result, SecretError> { + let name = "names"; + let (status, body) = self.get("/secrets", name)?; + match status { + 200 => { + let names = body + .get("names") + .and_then(|v| v.as_array()) + .ok_or_else(|| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: "200 response without a \"names\" array".to_string(), + })?; + names + .iter() + .map(|v| { + v.as_str() + .map(str::to_string) + .ok_or_else(|| SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: "\"names\" array holds a non-string entry".to_string(), + }) + }) + .collect() + } + status => Err(SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: format!("secrets-broker answered HTTP {status}"), + }), + } + } +} + +impl SecretSource for DirectBrokerSource { + fn source_name(&self) -> &'static str { + "secrets-broker" + } + + fn resolve(&self, name: &str) -> Result { + validate_name(name)?; + let (status, body) = self.get(&format!("/secret/{name}"), name)?; + match status { + 200 => { + let value = body.get("value").and_then(|v| v.as_str()).ok_or_else(|| { + SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: "200 response without a string \"value\" field".to_string(), + } + })?; + if value.is_empty() { + return Err(SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: "200 response with an empty \"value\"".to_string(), + }); + } + Ok(SecretValue(value.to_string())) + } + 404 => Err(SecretError::NotFound { + source: "secrets-broker", + name: name.to_string(), + }), + status => Err(SecretError::Unavailable { + source: "secrets-broker", + name: name.to_string(), + detail: format!("secrets-broker answered HTTP {status}"), + }), + } + } +} + /// Runs external commands for the `bws` fallback. Injectable so tests /// never spawn a real `bws` (and never see a real value). pub trait CommandRunner { @@ -669,6 +833,90 @@ mod tests { assert_eq!(v.expose(), "fixture-value-not-a-secret"); } + #[test] + fn direct_broker_source_roundtrip_over_a_temp_socket() { + // #6218: the laptop-local source speaks plain HTTP over + // the broker's own socket, reading its token from the file. + use std::io::{Read, Write}; + use std::os::unix::net::UnixListener; + + let dir = + std::env::temp_dir().join(format!("fleet-secrets-direct-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("secrets.sock"); + let token_file = dir.join("token"); + std::fs::write(&token_file, "test-token\n").unwrap(); + let listener = UnixListener::bind(&sock).unwrap(); + let handle = std::thread::spawn(move || { + for _ in 0..2 { + let (mut stream, _) = listener.accept().unwrap(); + let mut buf = [0u8; 2048]; + let n = stream.read(&mut buf).unwrap(); + let req = String::from_utf8_lossy(&buf[..n]).into_owned(); + assert!(req.contains("X-Agent-Token: test-token"), "req: {req}"); + let body = if req.starts_with("GET /secrets") { + "{\"names\":[\"a.name\",\"b.name\"]}" + } else { + assert!(req.starts_with("GET /secret/wanted.name"), "req: {req}"); + "{\"value\":\"direct-value\"}" + }; + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + stream.write_all(resp.as_bytes()).unwrap(); + } + }); + let source = DirectBrokerSource { + socket: sock, + token_file, + }; + let value = source.resolve("wanted.name").unwrap(); + assert_eq!(value.expose(), "direct-value"); + let names = source.list_names().unwrap(); + assert_eq!(names, vec!["a.name".to_string(), "b.name".to_string()]); + handle.join().unwrap(); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn direct_broker_source_404_is_notfound() { + // #6218: the direct leg maps statuses like the proxied one. + use std::io::{Read, Write}; + use std::os::unix::net::UnixListener; + + let dir = + std::env::temp_dir().join(format!("fleet-secrets-direct-404-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("secrets.sock"); + let token_file = dir.join("token"); + std::fs::write(&token_file, "test-token\n").unwrap(); + let listener = UnixListener::bind(&sock).unwrap(); + let handle = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut buf = [0u8; 1024]; + let _ = stream.read(&mut buf); + stream + .write_all( + b"HTTP/1.1 404 Not Found\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}", + ) + .unwrap(); + }); + let source = DirectBrokerSource { + socket: sock, + token_file, + }; + assert!(matches!( + source.resolve("missing.name"), + Err(SecretError::NotFound { .. }) + )); + handle.join().unwrap(); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn broker_list_names_roundtrip_over_a_temp_socket() { use std::os::unix::net::UnixListener; diff --git a/pkgs/fleet/crates/fleet/src/secrets.rs b/pkgs/fleet/crates/fleet/src/secrets.rs index 76f61b261d..5ce5780881 100644 --- a/pkgs/fleet/crates/fleet/src/secrets.rs +++ b/pkgs/fleet/crates/fleet/src/secrets.rs @@ -138,11 +138,18 @@ fn cmd_list(config: &Config, args: &[String]) -> i32 { eprintln!("usage: fleet secrets list"); return EXIT_USAGE; } - let source = BrokerSource { - broker_socket: config.broker_socket(), - token_file: config.secrets_token_file(), + // #6218: on the laptop the broker's own socket answers + // directly (no session broker exists there); elsewhere the + // session-broker source reads the same route. + let names_result = match fleet_secrets::DirectBrokerSource::from_config(config) { + Some(direct) => direct.list_names(), + None => BrokerSource { + broker_socket: config.broker_socket(), + token_file: config.secrets_token_file(), + } + .list_names(), }; - match source.list_names() { + match names_result { Ok(names) => { let mut out = std::io::stdout().lock(); for name in &names {