From a689cd186c2bcbddc67b0831690559c326a58141 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 17 Nov 2026 01:20:07 -0600 Subject: [PATCH 1/2] feat(fleet): laptop-agent domain with transport ladder and verbs Adds fleet-laptop-agent: the verbs exec, run, poll, kill, jobs, health and fetch over the laptop-agent daemon, with the transport ladder broker -> Cloudflare -> Tailscale -> SSH. Mirrors ~/tools/laptop-agent.py (X-Agent-Token, trip ids and trip log, deadline with cancel, 1 MiB capture cap) and keeps the primary-checkout guards (code#10095). The SSH leg is a named stub until ~/tools/laptop-ssh-real.sh exists. Refs #10796 --- pkgs/fleet/Cargo.lock | 13 + pkgs/fleet/Cargo.toml | 3 + .../crates/fleet-laptop-agent/Cargo.toml | 17 + .../crates/fleet-laptop-agent/src/cli.rs | 260 ++++++++++ .../crates/fleet-laptop-agent/src/client.rs | 456 ++++++++++++++++++ .../crates/fleet-laptop-agent/src/guard.rs | 108 +++++ .../crates/fleet-laptop-agent/src/ladder.rs | 252 ++++++++++ .../crates/fleet-laptop-agent/src/legs.rs | 244 ++++++++++ .../crates/fleet-laptop-agent/src/lib.rs | 201 ++++++++ pkgs/fleet/crates/fleet/Cargo.toml | 5 +- pkgs/fleet/crates/fleet/src/main.rs | 6 + 11 files changed, 1564 insertions(+), 1 deletion(-) create mode 100644 pkgs/fleet/crates/fleet-laptop-agent/Cargo.toml create mode 100644 pkgs/fleet/crates/fleet-laptop-agent/src/cli.rs create mode 100644 pkgs/fleet/crates/fleet-laptop-agent/src/client.rs create mode 100644 pkgs/fleet/crates/fleet-laptop-agent/src/guard.rs create mode 100644 pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs create mode 100644 pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs create mode 100644 pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 80f731bc65..a0a547066a 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -566,6 +566,7 @@ dependencies = [ "fleet-config", "fleet-dispatch", "fleet-dispatch-test", + "fleet-laptop-agent", "fleet-proxy", "fleet-proxy-proto", "fleet-queue", @@ -608,6 +609,18 @@ dependencies = [ "ureq", ] +[[package]] +name = "fleet-laptop-agent" +version = "0.1.0" +dependencies = [ + "fleet-config", + "fleet-proxy", + "fleet-secrets", + "serde", + "serde_json", + "sha2", +] + [[package]] name = "fleet-proxy" version = "0.1.0" diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml index c610b33257..5c14a99c6b 100644 --- a/pkgs/fleet/Cargo.toml +++ b/pkgs/fleet/Cargo.toml @@ -24,6 +24,7 @@ members = [ "crates/fleet-dispatch", "crates/fleet-dispatch-test", "crates/fleet-proxy", + "crates/fleet-laptop-agent", "crates/fleet-search", "crates/fleet", ] @@ -44,9 +45,11 @@ fleet-queue = { path = "crates/fleet-queue" } fleet-dispatch = { path = "crates/fleet-dispatch" } fleet-dispatch-test = { path = "crates/fleet-dispatch-test" } fleet-proxy = { path = "crates/fleet-proxy" } +fleet-laptop-agent = { path = "crates/fleet-laptop-agent" } fleet-search = { path = "crates/fleet-search", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" +sha2 = "0.10" toml = "0.9" [profile.release] diff --git a/pkgs/fleet/crates/fleet-laptop-agent/Cargo.toml b/pkgs/fleet/crates/fleet-laptop-agent/Cargo.toml new file mode 100644 index 0000000000..bf8244ff6c --- /dev/null +++ b/pkgs/fleet/crates/fleet-laptop-agent/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fleet-laptop-agent" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The fleet laptop-agent domain: the transport ladder (broker, Cloudflare, Tailscale, SSH) and the verbs over the laptop-agent daemon (epic developing-today/code#5412, issue #10796)." + +[dependencies] +fleet-config = { workspace = true } +# The Cloudflare leg needs fleet-proxy's `serve` feature (connect_cf_tunnel, +# HttpConn::from_tls): the same TLS stack the broker's own leg uses. +fleet-proxy = { workspace = true, features = ["serve"] } +fleet-secrets = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/cli.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/cli.rs new file mode 100644 index 0000000000..02453a13c7 --- /dev/null +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/cli.rs @@ -0,0 +1,260 @@ +//! The `laptop-agent` domain's argument surface. Every option is declared +//! here and parsed strictly: anything unaccounted for is a usage error +//! (exit 2) before any transport is touched. + +use std::sync::Arc; + +use crate::{client, guard, legs}; + +pub const USAGE: &str = "usage: fleet laptop-agent + health + jobs + kill JOB + exec [--cwd DIR] [--timeout SECS] [--shell] -- CMD... + run [--cwd DIR] [--shell] -- CMD... + poll JOB [--wait SECS] + fetch REMOTE_PATH LOCAL_PATH"; + +pub const EXIT_USAGE: i32 = 2; + +#[derive(Debug, PartialEq)] +pub enum Command { + Health, + Jobs, + Kill { job: String }, + Exec { cwd: Option, timeout: u64, shell: bool, cmd: Vec }, + Run { cwd: Option, shell: bool, cmd: Vec }, + Poll { job: String, wait: u64 }, + Fetch { remote: String, dest: String }, +} + +/// A job id goes into a URL path, so only the characters the daemon +/// mints are accepted. +fn valid_job(id: &str) -> bool { + !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +fn number(flag: &str, raw: &str) -> Result { + raw.parse::() + .map_err(|_| format!("{flag} expects a whole number of seconds, got {raw:?}")) +} + +/// Split at the first `--`: the options before it, the command after it. +fn split_cmd(args: &[String]) -> (&[String], &[String]) { + match args.iter().position(|a| a == "--") { + Some(i) => (&args[..i], &args[i + 1..]), + None => (args, &[]), + } +} + +/// Options for `exec` / `run`: `--cwd`, `--timeout` (exec only), `--shell`. +fn parse_exec_opts( + opts: &[String], + allow_timeout: bool, +) -> Result<(Option, u64, bool), String> { + let mut cwd = None; + let mut timeout = 120; + let mut shell = false; + let mut i = 0; + while i < opts.len() { + let arg = opts[i].as_str(); + let (flag, inline) = match arg.split_once('=') { + Some((f, v)) if f.starts_with("--") => (f, Some(v.to_string())), + _ => (arg, None), + }; + match flag { + "--shell" if inline.is_none() => shell = true, + "--cwd" | "--timeout" => { + if flag == "--timeout" && !allow_timeout { + return Err(format!("unknown option {arg:?}")); + } + let value = match inline { + Some(v) => v, + None => { + i += 1; + opts.get(i) + .cloned() + .ok_or_else(|| format!("{flag} needs a value"))? + } + }; + if flag == "--cwd" { + cwd = Some(value); + } else { + timeout = number(flag, &value)?; + } + } + _ => return Err(format!("unknown option {arg:?}")), + } + i += 1; + } + Ok((cwd, timeout, shell)) +} + +pub fn parse(args: &[String]) -> Result { + let Some((verb, rest)) = args.split_first() else { + return Err("no command given".into()); + }; + match verb.as_str() { + "health" if rest.is_empty() => Ok(Command::Health), + "jobs" if rest.is_empty() => Ok(Command::Jobs), + "kill" => match rest { + [job] if valid_job(job) => Ok(Command::Kill { job: job.clone() }), + _ => Err("kill takes one job id".into()), + }, + "exec" | "run" => { + let (opts, cmd) = split_cmd(rest); + if cmd.is_empty() { + return Err("no command given (use -- cmd...)".into()); + } + if verb == "exec" { + let (cwd, timeout, shell) = parse_exec_opts(opts, true)?; + Ok(Command::Exec { cwd, timeout, shell, cmd: cmd.to_vec() }) + } else { + let (cwd, _, shell) = parse_exec_opts(opts, false)?; + Ok(Command::Run { cwd, shell, cmd: cmd.to_vec() }) + } + } + "poll" => { + let (job, opts) = match rest.split_first() { + Some((job, opts)) if valid_job(job) => (job, opts), + _ => return Err("poll takes a job id".into()), + }; + match opts { + [] => Ok(Command::Poll { job: job.clone(), wait: 0 }), + [flag, value] if flag == "--wait" => Ok(Command::Poll { + job: job.clone(), + wait: number("--wait", value)?, + }), + _ => Err("poll takes a job id and an optional --wait SECS".into()), + } + } + "fetch" => match rest { + [remote, dest] if !remote.is_empty() && !dest.is_empty() => Ok(Command::Fetch { + remote: remote.clone(), + dest: dest.clone(), + }), + _ => Err("fetch takes REMOTE_PATH and LOCAL_PATH".into()), + }, + other => Err(format!("unknown command {other:?}")), + } +} + +fn command_words(shell: bool, cmd: &[String]) -> Vec { + if shell { + cmd.join(" ").split_whitespace().map(str::to_string).collect() + } else { + cmd.to_vec() + } +} + +/// Entry point for `fleet laptop-agent …`: returns the process exit code. +pub fn run(config: &fleet_config::Config, args: &[String]) -> i32 { + let command = match parse(args) { + Ok(c) => c, + Err(message) => { + eprintln!("laptop-agent: {message}\n{USAGE}"); + return EXIT_USAGE; + } + }; + let ladder = match legs::ladder(config) { + Ok(l) => Arc::new(l), + Err(message) => { + eprintln!("laptop-agent: {message}"); + return 1; + } + }; + match command { + Command::Health => client::health(&ladder), + Command::Jobs => client::jobs(&ladder), + Command::Kill { job } => client::kill(&ladder, &job), + Command::Exec { cwd, timeout, shell, cmd } => { + if let Err(message) = guard::check_job(cwd.as_deref(), &command_words(shell, &cmd)) { + eprintln!("laptop-agent: {message}"); + return 1; + } + let timeout = match std::env::var(crate::EXTERNAL_DEADLINE_ENV) + .ok() + .and_then(|v| v.parse::().ok()) + { + Some(ext) => timeout.min((ext.max(1.0)) as u64), + None => timeout, + }; + let spec = client::command_spec(cwd.as_deref(), shell, &cmd); + client::exec(&ladder, spec, timeout.max(1)) + } + Command::Run { cwd, shell, cmd } => { + if let Err(message) = guard::check_job(cwd.as_deref(), &command_words(shell, &cmd)) { + eprintln!("laptop-agent: {message}"); + return 1; + } + let spec = client::command_spec(cwd.as_deref(), shell, &cmd); + client::run(&ladder, spec) + } + Command::Poll { job, wait } => client::poll(&ladder, &job, wait), + Command::Fetch { remote, dest } => client::fetch(&ladder, &remote, std::path::Path::new(&dest)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(s: &str) -> Vec { + s.split_whitespace().map(str::to_string).collect() + } + + #[test] + fn exec_parses_options_and_the_command_after_dashdash() { + assert_eq!( + parse(&v("exec --cwd /w --timeout 9 -- make test")).unwrap(), + Command::Exec { + cwd: Some("/w".into()), + timeout: 9, + shell: false, + cmd: v("make test"), + } + ); + assert_eq!( + parse(&v("exec --timeout=5 --shell -- echo hi")).unwrap(), + Command::Exec { cwd: None, timeout: 5, shell: true, cmd: v("echo hi") } + ); + } + + #[test] + fn undeclared_options_are_usage_errors() { + assert!(parse(&v("exec --bogus -- ls")).is_err()); + assert!(parse(&v("run --timeout 5 -- ls")).is_err()); + assert!(parse(&v("exec --timeout x -- ls")).is_err()); + assert!(parse(&v("exec --cwd")).is_err()); + assert!(parse(&v("exec --cwd /w")).is_err(), "a command is required"); + } + + #[test] + fn job_ids_reach_the_path_only_when_well_formed() { + assert!(parse(&v("kill job_1-2")).is_ok()); + assert!(parse(&v("kill ../etc")).is_err()); + assert!(parse(&v("poll a/b")).is_err()); + assert_eq!( + parse(&v("poll job1 --wait 30")).unwrap(), + Command::Poll { job: "job1".into(), wait: 30 } + ); + assert!(parse(&v("poll job1 --wait")).is_err()); + } + + #[test] + fn unknown_verbs_and_stray_arguments_are_refused() { + assert!(parse(&v("frobnicate")).is_err()); + assert!(parse(&v("health now")).is_err()); + assert!(parse(&v("jobs --all")).is_err()); + } + + #[test] + fn fetch_takes_exactly_two_paths() { + assert_eq!( + parse(&v("fetch /a/b.txt /tmp/b.txt")).unwrap(), + Command::Fetch { remote: "/a/b.txt".into(), dest: "/tmp/b.txt".into() } + ); + assert!(parse(&v("fetch /a")).is_err()); + assert!(parse(&v("fetch /a /b /c")).is_err()); + } +} diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/client.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/client.rs new file mode 100644 index 0000000000..1c693bffdf --- /dev/null +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/client.rs @@ -0,0 +1,456 @@ +//! The verbs over the laptop-agent daemon, mirroring `laptop-agent.py`: +//! the same requests, the same output and the same exit codes. +//! +//! The local deadline is a watchdog: the ladder runs on a helper thread +//! and the caller waits for it with a timeout. A leg that hangs past the +//! deadline is abandoned (the process exits soon after), and the +//! deadline path asks the daemon to cancel a running `/exec` by trip. + +use std::io::Write; +use std::sync::Arc; +use std::sync::mpsc; +use std::thread; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use sha2::{Digest, Sha256}; + +use crate::ladder::{Answer, CallError, Failure, Ladder, Request}; +use crate::{CANCEL_BUDGET_S, FILE_CHUNK_MAX, TIMEOUT_EXIT, TRANSPORT_GRACE_S, log_trip, offset_dir}; + +/// The wait for a reply when the verb has no deadline of its own: the +/// Python's 660 s socket timeout, which covers daemon-side exec time. +pub const CALL_DEADLINE_S: u64 = 660; +/// The `run` submit deadline (`_set_deadline(30)` in the Python). +pub const SUBMIT_DEADLINE_S: u64 = 30; + +#[derive(Debug)] +pub enum CallFailure { + /// No reply before the local deadline. + Deadline, + /// Every leg failed, or a non-idempotent request failed mid-flight. + Transport(CallError), + /// The daemon answered with an error status. + Http { status: u16, message: String }, +} + +impl std::fmt::Display for CallFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + CallFailure::Deadline => write!(f, "no reply before the deadline"), + CallFailure::Transport(e) => write!(f, "transport error: {e}"), + CallFailure::Http { status, message } => write!(f, "HTTP {status}: {message}"), + } + } +} + +pub struct Reply { + pub body: Value, + pub leg: &'static str, + pub fallbacks: Vec, +} + +fn dispatch( + ladder: &Arc, + req: Request, + deadline: Option, +) -> Result { + let (tx, rx) = mpsc::channel(); + let shared = Arc::clone(ladder); + thread::spawn(move || { + let _ = tx.send(shared.call(&req)); + }); + let got = match deadline { + Some(d) => rx.recv_timeout(d).map_err(|_| CallFailure::Deadline)?, + None => rx.recv().map_err(|_| CallFailure::Deadline)?, + }; + got.map_err(CallFailure::Transport) +} + +/// One request, logged as one trip. The trip id rides in the header and, +/// for `POST /exec` and `POST /jobs`, in the body (the session proxy +/// forwards bodies verbatim, so the body is the carrier that reaches the +/// daemon). +fn send( + ladder: &Arc, + trip: &str, + method: &'static str, + path: &str, + body: Option, + idempotent: bool, + deadline: Duration, +) -> Result { + let body = match body { + Some(Value::Object(mut map)) if method == "POST" && (path == "/exec" || path == "/jobs") => { + map.insert("trip".to_string(), json!(trip)); + Some(Value::Object(map)) + } + other => other, + }; + let req = Request { + method, + path: path.to_string(), + body, + trip: trip.to_string(), + idempotent, + }; + let started = Instant::now(); + let result = dispatch(ladder, req, Some(deadline)); + let status = result.as_ref().ok().map(|a| a.reply.status); + log_trip(trip, path, started.elapsed().as_millis(), status); + result +} + +pub fn call( + ladder: &Arc, + trip: &str, + method: &'static str, + path: &str, + body: Option, + idempotent: bool, + deadline: Duration, +) -> Result { + let answer = send(ladder, trip, method, path, body, idempotent, deadline)?; + let value: Value = if answer.reply.body.is_empty() { + json!({}) + } else { + serde_json::from_slice(&answer.reply.body).map_err(|e| CallFailure::Http { + status: answer.reply.status, + message: format!("unparseable reply: {e}"), + })? + }; + if answer.reply.status >= 400 { + let message = match value.get("error") { + Some(Value::String(s)) => s.clone(), + Some(other) => other.to_string(), + None => value.to_string(), + }; + return Err(CallFailure::Http { + status: answer.reply.status, + message, + }); + } + Ok(Reply { + body: value, + leg: answer.leg, + fallbacks: answer.fallbacks, + }) +} + +/// Best-effort cancel of an in-flight `/exec` by trip (the Python's +/// `_cancel_in_flight`): a tight budget, and not logged as a trip. +pub fn cancel(ladder: &Arc, trip: &str) -> bool { + let req = Request { + method: "POST", + path: format!("/exec/{trip}/cancel"), + body: Some(json!({ "trip": trip })), + trip: trip.to_string(), + idempotent: true, + }; + dispatch(ladder, req, Some(Duration::from_secs(CANCEL_BUDGET_S))) + .map(|a| a.reply.status == 200) + .unwrap_or(false) +} + +/// The exit code and stderr line for a failed call. +fn fail(err: CallFailure) -> i32 { + match err { + CallFailure::Deadline => { + eprintln!("laptop-agent: command timed out"); + TIMEOUT_EXIT + } + other => { + eprintln!("laptop-agent: {other}"); + 1 + } + } +} + +/// Say which leg answered when earlier legs failed. The Python prints +/// nothing here, so this is the one line the ladder adds. +fn note_fallbacks(reply: &Reply) { + if reply.fallbacks.is_empty() { + return; + } + let tried: Vec<&str> = reply.fallbacks.iter().map(|f| f.leg).collect(); + eprintln!( + "laptop-agent: note: answered by {} after {} failed", + reply.leg, + tried.join(", ") + ); +} + +fn default_deadline() -> Duration { + Duration::from_secs(CALL_DEADLINE_S) +} + +pub fn health(ladder: &Arc) -> i32 { + let trip = crate::new_trip(); + match call(ladder, &trip, "GET", "/health", None, true, default_deadline()) { + Ok(reply) => { + note_fallbacks(&reply); + println!("{}", reply.body); + 0 + } + Err(e) => fail(e), + } +} + +pub fn jobs(ladder: &Arc) -> i32 { + let trip = crate::new_trip(); + match call(ladder, &trip, "GET", "/jobs", None, true, default_deadline()) { + Ok(reply) => { + note_fallbacks(&reply); + println!("{}", serde_json::to_string_pretty(&reply.body).unwrap_or_default()); + 0 + } + Err(e) => fail(e), + } +} + +pub fn kill(ladder: &Arc, job: &str) -> i32 { + let trip = crate::new_trip(); + let path = format!("/jobs/{job}/kill"); + match call(ladder, &trip, "POST", &path, Some(json!({})), true, default_deadline()) { + Ok(reply) => { + note_fallbacks(&reply); + println!("{}", reply.body); + 0 + } + Err(e) => fail(e), + } +} + +/// What a command runs: an argv, or a shell string (`--shell`). +pub fn command_spec(cwd: Option<&str>, shell: bool, cmd: &[String]) -> Value { + if shell { + json!({ "cwd": cwd, "shell": cmd.join(" ") }) + } else { + json!({ "cwd": cwd, "argv": cmd }) + } +} + +pub fn exec( + ladder: &Arc, + spec: Value, + timeout_s: u64, +) -> i32 { + let trip = crate::new_trip(); + let deadline = Duration::from_secs(timeout_s + TRANSPORT_GRACE_S); + let body = json!({ "cmds": [spec], "timeout_s": timeout_s }); + match call(ladder, &trip, "POST", "/exec", Some(body), false, deadline) { + Ok(reply) => { + note_fallbacks(&reply); + print_exec(&reply.body) + } + Err(CallFailure::Deadline) => { + cancel(ladder, &trip); + fail(CallFailure::Deadline) + } + Err(e) => fail(e), + } +} + +fn print_exec(body: &Value) -> i32 { + let Some(r) = body.get("results").and_then(|v| v.get(0)) else { + eprintln!("laptop-agent: reply has no result"); + return 1; + }; + let mut out = std::io::stdout(); + let mut err = std::io::stderr(); + let _ = out.write_all(r.get("stdout").and_then(Value::as_str).unwrap_or("").as_bytes()); + let _ = err.write_all(r.get("stderr").and_then(Value::as_str).unwrap_or("").as_bytes()); + if r.get("truncated").and_then(Value::as_bool).unwrap_or(false) { + eprintln!("laptop-agent: warning: output truncated at the 1 MiB/stream capture cap (tail kept)"); + } + if let Some(e) = r.get("error").filter(|v| !v.is_null()) { + eprintln!("laptop-agent: {}", e.as_str().map(str::to_string).unwrap_or_else(|| e.to_string())); + } + if r.get("timeout").and_then(Value::as_bool).unwrap_or(false) { + eprintln!("laptop-agent: command timed out"); + return TIMEOUT_EXIT; + } + r.get("exit") + .and_then(Value::as_i64) + .map(|v| v as i32) + .unwrap_or(1) +} + +pub fn run(ladder: &Arc, spec: Value) -> i32 { + let trip = crate::new_trip(); + let deadline = Duration::from_secs(SUBMIT_DEADLINE_S + TRANSPORT_GRACE_S); + match call(ladder, &trip, "POST", "/jobs", Some(spec), false, deadline) { + Ok(reply) => { + note_fallbacks(&reply); + match reply.body.get("job_id").and_then(Value::as_str) { + Some(id) => { + println!("{id}"); + 0 + } + None => { + eprintln!("laptop-agent: reply has no job_id"); + 1 + } + } + } + Err(e) => fail(e), + } +} + +#[derive(serde::Serialize, serde::Deserialize, Default)] +struct Offsets { + out: u64, + err: u64, +} + +fn offsets_file(job: &str) -> std::path::PathBuf { + offset_dir().join(format!("{job}.json")) +} + +fn load_offsets(job: &str) -> Offsets { + std::fs::read_to_string(offsets_file(job)) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() +} + +fn save_offsets(job: &str, offs: &Offsets) { + let _ = std::fs::create_dir_all(offset_dir()); + let _ = std::fs::write(offsets_file(job), serde_json::to_string(offs).unwrap_or_default()); +} + +/// Python's rendering of an optional value in the done line (`None`). +fn py_opt(v: &Value) -> String { + match v { + Value::Null => "None".to_string(), + other => other.to_string(), + } +} + +pub fn poll(ladder: &Arc, job: &str, wait_s: u64) -> i32 { + let deadline = Instant::now() + Duration::from_secs(wait_s); + let mut offs = load_offsets(job); + loop { + let trip = crate::new_trip(); + let path = format!("/jobs/{job}?out_off={}&err_off={}", offs.out, offs.err); + let reply = match call(ladder, &trip, "GET", &path, None, true, default_deadline()) { + Ok(reply) => reply, + Err(e) => return fail(e), + }; + let body = &reply.body; + let mut out = std::io::stdout(); + let mut err = std::io::stderr(); + let _ = out.write_all(body.get("stdout").and_then(Value::as_str).unwrap_or("").as_bytes()); + let _ = out.flush(); + let _ = err.write_all(body.get("stderr").and_then(Value::as_str).unwrap_or("").as_bytes()); + let _ = err.flush(); + let (Some(out_next), Some(err_next)) = ( + body.get("out_next").and_then(Value::as_u64), + body.get("err_next").and_then(Value::as_u64), + ) else { + eprintln!("laptop-agent: reply has no out_next/err_next"); + return 1; + }; + offs = Offsets { + out: out_next, + err: err_next, + }; + save_offsets(job, &offs); + if body.get("state").and_then(Value::as_str) == Some("done") { + let exit = body.get("exit").cloned().unwrap_or(Value::Null); + let dur = body.get("duration_ms").cloned().unwrap_or(Value::Null); + eprintln!( + "[laptop-agent] job {job} done exit={} duration_ms={}", + py_opt(&exit), + py_opt(&dur) + ); + return exit.as_i64().map(|v| v as i32).unwrap_or(1); + } + let now = Instant::now(); + if now >= deadline { + eprintln!("[laptop-agent] job {job} still running"); + return 0; + } + thread::sleep((deadline - now).min(Duration::from_secs(3))); + } +} + +/// The sha256 of the remote file, computed on the laptop by `shasum` +/// (present on macOS, where the daemon runs) through `/exec`. +fn remote_sha256(ladder: &Arc, remote: &str) -> Result { + let cmd = vec!["shasum".to_string(), "-a".to_string(), "256".to_string(), remote.to_string()]; + let spec = command_spec(None, false, &cmd); + let trip = crate::new_trip(); + let body = json!({ "cmds": [spec], "timeout_s": 60 }); + let reply = call(ladder, &trip, "POST", "/exec", Some(body), false, Duration::from_secs(60 + TRANSPORT_GRACE_S)) + .map_err(|e| e.to_string())?; + let r = reply.body.get("results").and_then(|v| v.get(0)).ok_or("reply has no result")?; + if r.get("exit").and_then(Value::as_i64) != Some(0) { + let err = r.get("stderr").and_then(Value::as_str).unwrap_or("").trim().to_string(); + return Err(format!("cannot hash {remote}: {err}")); + } + let out = r.get("stdout").and_then(Value::as_str).unwrap_or(""); + out.split_whitespace() + .next() + .filter(|h| h.len() == 64 && h.chars().all(|c| c.is_ascii_hexdigit())) + .map(|h| h.to_ascii_lowercase()) + .ok_or_else(|| format!("unexpected shasum output for {remote}")) +} + +/// One `GET /file` range. Raw bytes, so the reply is not parsed as JSON. +fn fetch_chunk(ladder: &Arc, remote: &str, off: u64) -> Result, CallFailure> { + let trip = crate::new_trip(); + let path = format!( + "/file?path={}&off={off}&len={FILE_CHUNK_MAX}", + percent_encode(remote) + ); + let answer = send(ladder, &trip, "GET", &path, None, true, default_deadline())?; + if answer.reply.status >= 400 { + let message = String::from_utf8_lossy(&answer.reply.body).into_owned(); + return Err(CallFailure::Http { status: answer.reply.status, message }); + } + Ok(answer.reply.body) +} + +fn percent_encode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} + +/// Copy a remote file to `dest`, hash-checked: the bytes are written only +/// when their sha256 matches the remote's own. +pub fn fetch(ladder: &Arc, remote: &str, dest: &std::path::Path) -> i32 { + let want = match remote_sha256(ladder, remote) { + Ok(h) => h, + Err(message) => { + eprintln!("laptop-agent: {message}"); + return 1; + } + }; + let mut data = Vec::new(); + loop { + match fetch_chunk(ladder, remote, data.len() as u64) { + Ok(chunk) if chunk.is_empty() => break, + Ok(chunk) => data.extend_from_slice(&chunk), + Err(e) => return fail(e), + } + } + let got = format!("{:x}", Sha256::digest(&data)); + if got != want { + eprintln!("laptop-agent: sha256 mismatch for {remote}: remote {want}, received {got}; nothing written"); + return 1; + } + if let Err(e) = std::fs::write(dest, &data) { + eprintln!("laptop-agent: cannot write {}: {e}", dest.display()); + return 1; + } + eprintln!("[laptop-agent] fetched {remote} -> {} ({} bytes, sha256 {got})", dest.display(), data.len()); + 0 +} diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/guard.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/guard.rs new file mode 100644 index 0000000000..1bd7b1fe81 --- /dev/null +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/guard.rs @@ -0,0 +1,108 @@ +//! Primary-checkout guards (code#10095). A primary checkout is a +//! directory whose `.git` is a directory; a linked worktree's `.git` is +//! a file. Two refusals, both overridable with `LAPTOP_AGENT_PRIMARY_OK=1`: +//! +//! * a job whose working directory is a primary checkout; +//! * a git mutation (commit, push, reset, ...) whose target is one. +//! +//! The checks run on the path as this client sees it. The daemon's +//! working directory is not visible here, so a job with no `--cwd` is +//! not checked. + +use std::path::Path; + +pub const PRIMARY_OK_ENV: &str = "LAPTOP_AGENT_PRIMARY_OK"; + +/// Git subcommands that change a repository. +const MUTATING: &[&str] = &[ + "add", "am", "apply", "branch", "checkout", "cherry-pick", "clean", "commit", "gc", "merge", + "mv", "pull", "push", "rebase", "reset", "restore", "revert", "rm", "stash", "switch", "tag", + "update-ref", "worktree", +]; + +pub fn is_primary_checkout(dir: &Path) -> bool { + dir.join(".git").is_dir() +} + +/// Refuse a job that would run inside a primary checkout, or a git +/// mutation aimed at one. `words` is the argv, or the shell string split +/// on whitespace for `--shell`. +pub fn check_job(cwd: Option<&str>, words: &[String]) -> Result<(), String> { + if std::env::var(PRIMARY_OK_ENV).as_deref() == Ok("1") { + return Ok(()); + } + if let Some(dir) = cwd + && is_primary_checkout(Path::new(dir)) + { + return Err(format!( + "refusing to run a job in primary checkout {dir} (use a worktree, or {PRIMARY_OK_ENV}=1)" + )); + } + if let Some((sub, target)) = git_mutation(words) { + let base = target.or(cwd); + if let Some(dir) = base + && is_primary_checkout(Path::new(dir)) + { + return Err(format!( + "refusing git {sub} against primary checkout {dir} (use a worktree, or {PRIMARY_OK_ENV}=1)" + )); + } + } + Ok(()) +} + +/// The mutating subcommand and the `-C` target, when `words` is a git +/// command that changes a repository. +fn git_mutation(words: &[String]) -> Option<(String, Option<&str>)> { + if words.first().map(String::as_str) != Some("git") { + return None; + } + let mut target = None; + let mut i = 1; + while i < words.len() { + let w = words[i].as_str(); + if w == "-C" { + target = words.get(i + 1).map(String::as_str); + i += 2; + } else if w.starts_with('-') { + i += 1; + } else { + break; + } + } + let sub = words.get(i)?; + if MUTATING.contains(&sub.as_str()) { + Some((sub.clone(), target)) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn words(s: &str) -> Vec { + s.split_whitespace().map(str::to_string).collect() + } + + #[test] + fn git_mutations_are_found_past_global_options() { + assert_eq!(git_mutation(&words("git -C /x commit -m m")), Some(("commit".into(), Some("/x")))); + assert_eq!(git_mutation(&words("git status")), None); + assert_eq!(git_mutation(&words("ls -la")), None); + } + + #[test] + fn a_worktree_is_not_a_primary_checkout() { + let dir = std::env::temp_dir().join(format!("la-guard-{}", std::process::id())); + let primary = dir.join("primary"); + let worktree = dir.join("worktree"); + std::fs::create_dir_all(primary.join(".git")).unwrap(); + std::fs::create_dir_all(&worktree).unwrap(); + std::fs::write(worktree.join(".git"), "gitdir: /elsewhere").unwrap(); + assert!(is_primary_checkout(&primary)); + assert!(!is_primary_checkout(&worktree)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs new file mode 100644 index 0000000000..0d4354c8c3 --- /dev/null +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs @@ -0,0 +1,252 @@ +//! The transport ladder: an ordered list of legs, tried in turn. +//! +//! The fall-through rule is what keeps the ladder safe to automate: +//! +//! * an absent leg (not configured here) or a leg that failed before +//! the request left this machine is skipped, and the next leg is +//! tried; +//! * a leg that failed after the request was written is retried on +//! the next leg only when the request is idempotent. A non-idempotent +//! request (an exec, a job submit) that may already have run on the +//! laptop is never replayed: the call errors, naming the leg. + +use std::fmt; + +#[derive(Clone, Debug)] +pub struct Request { + pub method: &'static str, + pub path: String, + pub body: Option, + pub trip: String, + pub idempotent: bool, +} + +#[derive(Debug, PartialEq)] +pub struct Reply { + pub status: u16, + pub body: Vec, +} + +#[derive(Debug, PartialEq)] +pub enum LegError { + /// The leg is not configured for this request; nothing was tried. + Absent(String), + /// The leg failed before the request left this machine. + Unsent(String), + /// The request was written, then the leg failed. + Sent(String), +} + +pub trait Leg: Send + Sync { + fn name(&self) -> &'static str; + fn call(&self, req: &Request) -> Result; +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Failure { + pub leg: &'static str, + pub kind: &'static str, + pub reason: String, +} + +#[derive(Debug, PartialEq)] +pub struct Answer { + pub leg: &'static str, + pub reply: Reply, + /// Legs tried before the one that answered, and why each failed. + pub fallbacks: Vec, +} + +#[derive(Debug, PartialEq)] +pub enum CallError { + /// Every leg failed before the request reached the daemon. + AllLegsFailed(Vec), + /// A non-idempotent request failed mid-flight and was not replayed. + NotReplayed { + failure: Failure, + earlier: Vec, + }, +} + +impl fmt::Display for CallError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CallError::AllLegsFailed(failures) => { + write!(f, "all transport legs failed: {}", render(failures)) + } + CallError::NotReplayed { failure, earlier } => { + let mut all = earlier.clone(); + all.push(failure.clone()); + write!( + f, + "{} failed after the request was sent and was not replayed (not idempotent); legs: {}", + failure.leg, + render(&all) + ) + } + } + } +} + +fn render(failures: &[Failure]) -> String { + failures + .iter() + .map(|f| format!("{}: {}", f.leg, f.reason)) + .collect::>() + .join("; ") +} + +pub struct Ladder { + legs: Vec>, +} + +impl Ladder { + pub fn new(legs: Vec>) -> Ladder { + Ladder { legs } + } + + pub fn call(&self, req: &Request) -> Result { + let mut failures: Vec = Vec::new(); + for leg in &self.legs { + let name = leg.name(); + match leg.call(req) { + Ok(reply) => { + return Ok(Answer { + leg: name, + reply, + fallbacks: failures, + }); + } + Err(LegError::Absent(reason)) => failures.push(Failure { + leg: name, + kind: "absent", + reason, + }), + Err(LegError::Unsent(reason)) => failures.push(Failure { + leg: name, + kind: "unsent", + reason, + }), + Err(LegError::Sent(reason)) => { + let failure = Failure { + leg: name, + kind: "sent", + reason, + }; + if !req.idempotent { + return Err(CallError::NotReplayed { + failure, + earlier: failures, + }); + } + failures.push(failure); + } + } + } + Err(CallError::AllLegsFailed(failures)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + struct Fake { + name: &'static str, + outcome: Mutex>>, + calls: Arc, + } + + impl Leg for Fake { + fn name(&self) -> &'static str { + self.name + } + fn call(&self, _req: &Request) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + self.outcome.lock().unwrap().take().expect("one call per fake") + } + } + + fn fake(name: &'static str, outcome: Result) -> (Box, Arc) { + let calls = Arc::new(AtomicUsize::new(0)); + let leg = Fake { + name, + outcome: Mutex::new(Some(outcome)), + calls: calls.clone(), + }; + (Box::new(leg), calls) + } + + fn ok(status: u16) -> Result { + Ok(Reply { + status, + body: b"{}".to_vec(), + }) + } + + fn req(idempotent: bool) -> Request { + Request { + method: "POST", + path: "/exec".into(), + body: None, + trip: "t".into(), + idempotent, + } + } + + #[test] + fn a_dead_leg_degrades_to_the_next_and_names_it() { + let (a, a_calls) = fake("broker", Err(LegError::Absent("no socket".into()))); + let (b, b_calls) = fake("cloudflare", Err(LegError::Unsent("connect refused".into()))); + let (c, _) = fake("tailscale", ok(200)); + let ladder = Ladder::new(vec![a, b, c]); + let answer = ladder.call(&req(false)).unwrap(); + assert_eq!(answer.leg, "tailscale"); + assert_eq!(answer.reply.status, 200); + assert_eq!(answer.fallbacks.len(), 2); + assert_eq!(answer.fallbacks[1].kind, "unsent"); + assert_eq!(answer.fallbacks[1].reason, "connect refused"); + assert_eq!(a_calls.load(Ordering::SeqCst), 1); + assert_eq!(b_calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn total_failure_names_every_leg() { + let (a, _) = fake("broker", Err(LegError::Absent("no socket".into()))); + let (b, _) = fake("tailscale", Err(LegError::Unsent("HTTPS_PROXY unset".into()))); + let err = Ladder::new(vec![a, b]).call(&req(true)).unwrap_err(); + let text = err.to_string(); + assert!(text.contains("broker: no socket"), "{text}"); + assert!(text.contains("tailscale: HTTPS_PROXY unset"), "{text}"); + } + + #[test] + fn a_sent_non_idempotent_request_is_never_replayed() { + let (a, _) = fake("tailscale", Err(LegError::Sent("reset by peer".into()))); + let (b, b_calls) = fake("cloudflare", ok(200)); + let err = Ladder::new(vec![a, b]).call(&req(false)).unwrap_err(); + assert!(matches!(err, CallError::NotReplayed { .. }), "{err:?}"); + assert_eq!(b_calls.load(Ordering::SeqCst), 0); + } + + #[test] + fn a_sent_idempotent_request_falls_through() { + let (a, _) = fake("tailscale", Err(LegError::Sent("reset by peer".into()))); + let (b, _) = fake("cloudflare", ok(200)); + let answer = Ladder::new(vec![a, b]).call(&req(true)).unwrap(); + assert_eq!(answer.leg, "cloudflare"); + assert_eq!(answer.fallbacks[0].kind, "sent"); + } + + #[test] + fn an_http_error_status_is_an_answer_not_a_fallback() { + let (a, _) = fake("broker", ok(401)); + let (b, b_calls) = fake("tailscale", ok(200)); + let answer = Ladder::new(vec![a, b]).call(&req(true)).unwrap(); + assert_eq!(answer.reply.status, 401); + assert_eq!(b_calls.load(Ordering::SeqCst), 0); + } +} diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs new file mode 100644 index 0000000000..b35006d239 --- /dev/null +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs @@ -0,0 +1,244 @@ +//! The four transport legs, in ladder order: the warm broker socket, +//! the Cloudflare tunnel, Tailscale CONNECT, and SSH. +//! +//! Each leg maps its failures onto the ladder's three classes: absent +//! (not configured here), unsent (failed before the request was written) +//! and sent (failed after). See [`crate::ladder`] for why that split +//! decides whether a request may fall through. + +use std::io::{Read, Write}; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; + +use fleet_proxy::http::{HttpConn, HttpError}; +use fleet_proxy::tunnel::{connect_cf_tunnel, connect_tunnel, egress_from_env, egress_from_env_url_port, Egress}; + +use crate::ladder::{Ladder, Leg, LegError, Reply, Request}; +use crate::{broker_socket, read_token, token_file, CF_ACCESS_SECRET, TARGET_HOST, TARGET_PORT}; + +/// The proxy port the Python tailnet CONNECT dials (`PROXY_PORT`). +pub const TAILNET_PROXY_PORT: u16 = 3130; + +/// The broker's framed protocol: an 8-byte big-endian length, then the +/// JSON message; the reply is framed the same way. +pub struct BrokerLeg { + pub socket: PathBuf, +} + +impl Leg for BrokerLeg { + fn name(&self) -> &'static str { + "broker" + } + + fn call(&self, req: &Request) -> Result { + if !self.socket.exists() { + return Err(LegError::Absent(format!( + "no broker socket at {}", + self.socket.display() + ))); + } + let mut s = UnixStream::connect(&self.socket) + .map_err(|e| LegError::Unsent(format!("broker connect: {}", e.kind())))?; + let msg = serde_json::json!({ + "method": req.method, + "path": req.path, + "body": req.body, + "trip": req.trip, + }); + let payload = serde_json::to_vec(&msg).unwrap_or_default(); + let mut frame = (payload.len() as u64).to_be_bytes().to_vec(); + frame.extend_from_slice(&payload); + s.write_all(&frame) + .map_err(|e| LegError::Sent(format!("broker write: {}", e.kind())))?; + let mut header = [0u8; 8]; + s.read_exact(&mut header) + .map_err(|e| LegError::Sent(format!("broker read: {}", e.kind())))?; + let n = u64::from_be_bytes(header); + let mut data = vec![0u8; n as usize]; + s.read_exact(&mut data) + .map_err(|e| LegError::Sent(format!("broker read mid-reply: {}", e.kind())))?; + let obj: serde_json::Value = serde_json::from_slice(&data) + .map_err(|e| LegError::Sent(format!("broker reply not JSON: {e}")))?; + let status = obj + .get("status") + .and_then(|v| v.as_u64()) + .and_then(|v| u16::try_from(v).ok()) + .ok_or_else(|| LegError::Sent("broker reply has no status".into()))?; + let body = serde_json::to_vec(obj.get("body").unwrap_or(&serde_json::Value::Null)) + .unwrap_or_default(); + Ok(Reply { status, body }) + } +} + +/// One HTTP exchange over an established connection. Failures after +/// the connection exists are `Sent`: the request may have reached the +/// daemon, so the ladder decides replay by idempotence. +fn exchange( + conn: Result, + req: &Request, + token: &str, + host_header: &str, + extra: &[(String, String)], +) -> Result { + let mut conn = conn.map_err(|e| LegError::Unsent(e.to_string()))?; + let body = req + .body + .as_ref() + .map(|b| serde_json::to_vec(b).unwrap_or_default()); + let mut headers = extra.to_vec(); + headers.push(("X-Trip-Id".to_string(), req.trip.clone())); + match conn.request_with_extra_headers( + req.method, + &req.path, + host_header, + token, + body.as_deref(), + &headers, + ) { + Ok((status, body)) => Ok(Reply { status, body }), + Err(HttpError::Io(e)) => Err(LegError::Sent(e.to_string())), + Err(e) => Err(LegError::Sent(e.to_string())), + } +} + +/// The Cloudflare leg. Its Access service token is a fleet secret, +/// resolved when the leg is tried (so a healthy broker never pays for +/// it); the value never leaves this process except in the headers. +pub struct CfLeg { + pub token: String, + pub config: fleet_config::Config, + pub cf_host: String, +} + +impl Leg for CfLeg { + fn name(&self) -> &'static str { + "cloudflare" + } + + fn call(&self, req: &Request) -> Result { + let egress: Egress = egress_from_env_url_port() + .map_err(|e| LegError::Absent(e))?; + let resolver = fleet_secrets::Resolver::default_chain(&self.config); + let secret = resolver + .resolve(CF_ACCESS_SECRET) + .map_err(|_| LegError::Absent(format!("secret {CF_ACCESS_SECRET} unavailable")))?; + let headers = cf_access_headers(secret.expose()) + .ok_or_else(|| LegError::Absent(format!("secret {CF_ACCESS_SECRET} is not a service token")))?; + let conn = connect_cf_tunnel(&egress, &self.cf_host) + .and_then(HttpConn::from_tls); + exchange(conn, req, &self.token, &self.cf_host, &headers) + } +} + +/// `CF-Access-*` headers from the secret's JSON (`client_id`, +/// `client_secret`). None when the value is not a service token. +pub fn cf_access_headers(json_text: &str) -> Option> { + let value: serde_json::Value = serde_json::from_str(json_text).ok()?; + let id = value.get("client_id")?.as_str()?; + let secret = value.get("client_secret")?.as_str()?; + if id.is_empty() || secret.is_empty() { + return None; + } + Some(vec![ + ("CF-Access-Client-Id".to_string(), id.to_string()), + ("CF-Access-Client-Secret".to_string(), secret.to_string()), + ]) +} + +/// Tailscale: a CONNECT through the tailnet egress proxy to the +/// laptop's daemon port. +pub struct TailscaleLeg { + pub token: String, +} + +impl Leg for TailscaleLeg { + fn name(&self) -> &'static str { + "tailscale" + } + + fn call(&self, req: &Request) -> Result { + let egress = egress_from_env(TAILNET_PROXY_PORT).map_err(LegError::Absent)?; + let conn = connect_tunnel(Some(&egress), TARGET_HOST, TARGET_PORT).and_then(HttpConn::new); + let host = format!("{TARGET_HOST}:{TARGET_PORT}"); + exchange(conn, req, &self.token, &host, &[]) + } +} + +/// SSH: a named stub. The real leg is `~/tools/laptop-ssh-real.sh`, +/// which is absent from the sandbox, so its semantics are unverified +/// and nothing is attempted here. +pub struct SshLeg; + +impl Leg for SshLeg { + fn name(&self) -> &'static str { + "ssh" + } + + fn call(&self, _req: &Request) -> Result { + Err(LegError::Absent( + "ssh leg not implemented (laptop-ssh-real.sh not verified)".into(), + )) + } +} + +/// The ladder for this process: broker, Cloudflare, Tailscale, SSH. +pub fn ladder(config: &fleet_config::Config) -> Result { + let token = read_token(&token_file())?; + let legs: Vec> = vec![ + Box::new(BrokerLeg { + socket: broker_socket(), + }), + Box::new(CfLeg { + token: token.clone(), + config: config.clone(), + cf_host: config.cf_host().to_string(), + }), + Box::new(TailscaleLeg { + token: token.clone(), + }), + Box::new(SshLeg), + ]; + Ok(Ladder::new(legs)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cf_headers_come_from_a_service_token_only() { + let h = cf_access_headers(r#"{"client_id":"id.access","client_secret":"s"}"#).unwrap(); + assert_eq!(h[0], ("CF-Access-Client-Id".to_string(), "id.access".to_string())); + assert_eq!(h[1].0, "CF-Access-Client-Secret"); + assert!(cf_access_headers(r#"{"client_id":"id"}"#).is_none()); + assert!(cf_access_headers("not json").is_none()); + assert!(cf_access_headers(r#"{"client_id":"","client_secret":"s"}"#).is_none()); + } + + #[test] + fn a_missing_broker_socket_is_absent_not_sent() { + let leg = BrokerLeg { + socket: PathBuf::from("/nonexistent/laptop-agent-test/broker.sock"), + }; + let req = Request { + method: "GET", + path: "/health".into(), + body: None, + trip: "t".into(), + idempotent: true, + }; + assert!(matches!(leg.call(&req), Err(LegError::Absent(_)))); + } + + #[test] + fn ssh_leg_is_an_absent_stub() { + let req = Request { + method: "GET", + path: "/health".into(), + body: None, + trip: "t".into(), + idempotent: true, + }; + assert!(matches!(SshLeg.call(&req), Err(LegError::Absent(_)))); + } +} diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs new file mode 100644 index 0000000000..5ee4741c58 --- /dev/null +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs @@ -0,0 +1,201 @@ +//! The fleet laptop-agent domain (epic developing-today/code#5412, +//! issue developing-today/code#10796): the client for the laptop-agent +//! daemon, in the fleet binary. +//! +//! The behaviour mirrors the Python client it replaces +//! (`~/tools/laptop-agent.py`): the same verbs, the same daemon +//! protocol, the same trip-log record shape. What the binary adds is +//! the transport ladder: broker socket, then the Cloudflare tunnel, +//! then Tailscale CONNECT, then SSH. A dead leg degrades to the next; +//! only a total failure errors, naming every leg that failed. + +pub mod cli; +pub mod client; +pub mod guard; +pub mod ladder; +pub mod legs; + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// The laptop's tailnet address and the daemon port (`TARGET_HOST` / +/// `TARGET_PORT` in the Python client). +pub const TARGET_HOST: &str = "100.99.113.103"; +pub const TARGET_PORT: u16 = 4799; +/// Exit code for a caller deadline (GNU timeout's code, as the Python). +pub const TIMEOUT_EXIT: i32 = 124; +/// Local deadline = remote timeout + this grace (`TRANSPORT_GRACE_S`). +pub const TRANSPORT_GRACE_S: u64 = 15; +/// Time the deadline path may spend asking the daemon to cancel. +pub const CANCEL_BUDGET_S: u64 = 3; +/// Per-stream capture cap the daemon applies to /exec output. +pub const FILE_CHUNK_MAX: u64 = 1 << 20; +/// The fleet secret carrying the Cloudflare Access service token. +pub const CF_ACCESS_SECRET: &str = "cloudflare.access-laptop-agent"; +/// Seconds from now by which an `exec` deadline is clamped (`LAPTOP_AGENT_DEADLINE_S`). +pub const EXTERNAL_DEADLINE_ENV: &str = "LAPTOP_AGENT_DEADLINE_S"; + +pub fn home() -> PathBuf { + fleet_config::Config::home_dir() +} + +pub fn token_file() -> PathBuf { + home().join("tools/laptop-agent-token") +} + +pub fn offset_dir() -> PathBuf { + home().join(".cache/laptop-agent") +} + +pub fn broker_socket() -> PathBuf { + offset_dir().join("broker.sock") +} + +pub fn trip_log() -> PathBuf { + home().join(".local/state/laptop-agent/trips.jsonl") +} + +/// The agent token, trimmed. It is sent as a header only; it never +/// reaches argv, a log line or an error message. +pub fn read_token(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|e| format!("token file {} unreadable: {}", path.display(), e.kind()))?; + let token = text.trim().to_string(); + if token.is_empty() { + return Err(format!("token file {} is empty", path.display())); + } + Ok(token) +} + +/// Twelve hex characters from the kernel's entropy source: one trip id +/// per request, carried in the X-Trip-Id header and the body. +pub fn new_trip() -> String { + let mut bytes = [0u8; 6]; + if let Ok(mut f) = std::fs::File::open("/dev/urandom") + && f.read_exact(&mut bytes).is_ok() + { + return bytes.iter().map(|b| format!("{b:02x}")).collect(); + } + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + format!("{:012x}", (nanos as u64) & 0xffff_ffff_ffff) +} + +/// One client-side trip record. The field names and their order are +/// the Python client's (`_log_trip`): a log reader cannot tell which +/// client wrote a line. +#[derive(serde::Serialize, Debug, PartialEq)] +pub struct TripRecord { + pub ts: String, + pub trip: String, + pub path: String, + pub total_ms: u128, + pub status: Option, +} + +/// Append one trip record with a single O_APPEND write. Logging must +/// never break or visibly delay a call, so every error is swallowed. +pub fn log_trip(trip: &str, path: &str, total_ms: u128, status: Option) { + let _ = append_trip( + &trip_log(), + &TripRecord { + ts: iso_utc(now_secs()), + trip: trip.to_string(), + path: path.to_string(), + total_ms, + status, + }, + ); +} + +fn append_trip(file: &Path, rec: &TripRecord) -> std::io::Result<()> { + use std::io::Write; + if let Some(dir) = file.parent() { + std::fs::create_dir_all(dir)?; + } + let mut line = serde_json::to_string(rec).unwrap_or_default(); + line.push('\n'); + let mut f = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(file)?; + f.write_all(line.as_bytes()) +} + +fn now_secs() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +/// `YYYY-MM-DDTHH:MM:SSZ` for a Unix time, the Python's `strftime` +/// shape (civil-from-days, proleptic Gregorian). +pub fn iso_utc(secs: i64) -> String { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_utc_matches_known_instants() { + assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z"); + assert_eq!(iso_utc(1_700_000_000), "2023-11-14T22:13:20Z"); + assert_eq!(iso_utc(951_782_400), "2000-02-29T00:00:00Z"); + } + + #[test] + fn trip_ids_are_twelve_hex_characters() { + let t = new_trip(); + assert_eq!(t.len(), 12); + assert!(t.chars().all(|c| c.is_ascii_hexdigit())); + } + + #[test] + fn trip_record_keeps_the_python_field_order() { + let rec = TripRecord { + ts: "T".into(), + trip: "t".into(), + path: "/exec".into(), + total_ms: 5, + status: None, + }; + assert_eq!( + serde_json::to_string(&rec).unwrap(), + r#"{"ts":"T","trip":"t","path":"/exec","total_ms":5,"status":null}"# + ); + } + + #[test] + fn empty_token_file_is_refused() { + let dir = std::env::temp_dir().join(format!("la-token-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("token"); + std::fs::write(&p, " \n").unwrap(); + assert!(read_token(&p).unwrap_err().contains("empty")); + std::fs::write(&p, "abc\n").unwrap(); + assert_eq!(read_token(&p).unwrap(), "abc"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 71c4335578..4ef26f1539 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -26,6 +26,9 @@ fleet-proxy = { workspace = true, default-features = false } # fleet-secrets is linked only by builds whose domains resolve secrets; # the connect variant must not carry it (§2: "nothing else"). fleet-secrets = { workspace = true, optional = true } +# The laptop-agent client (developing-today/code#10796): the transport ladder +# and the verbs over the laptop daemon; laptop builds only. +fleet-laptop-agent = { workspace = true, optional = true } serde_json = { workspace = true } # The gh domain (code#8887) mints App installation tokens over the # GitHub API; same ureq pin as fleet-queue/fleet-search (rustls, no @@ -96,4 +99,4 @@ secrets = ["dep:fleet-secrets"] # full only — the serve build's daemons shell out to it externally # if ever needed, it is not a daemon role. gh = ["dep:fleet-secrets", "dep:ureq"] -laptop-agent = ["dep:fleet-secrets"] +laptop-agent = ["dep:fleet-secrets", "dep:fleet-laptop-agent"] diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 0dc960eec6..62a23416d4 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -846,6 +846,12 @@ fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) if d.name == "secrets" { return secrets::run(&surface.config, args); } + // developing-today/code#10796: the laptop-agent domain runs for + // real — the transport ladder and the verbs over the laptop daemon. + #[cfg(feature = "laptop-agent")] + if d.name == "laptop-agent" { + return fleet_laptop_agent::cli::run(&surface.config, args); + } // code#8887: the gh domain runs for real — the real // `gh` binary as a passthrough under the token // rotation (personal, then App installations). From 72c88919e3716a4d53050170fb6d7ddc2ab26e3d Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 17 Nov 2026 03:04:08 -0600 Subject: [PATCH 2/2] fix(fleet-laptop-agent): fetch bypasses the JSON-only broker leg; trip log v2 fields Parity work for #10796 (lane code-d, task 20682): - GET /file replies are raw bytes and cannot cross the broker leg (its protocol is JSON-only; it answered 502 JSONDecodeError). Request gains direct_only; fetch chunks set it, matching the Python client, which bypasses the broker for /file. - TripRecord now writes the Python v2 shape: v, transport (broker/cf/ts/ssh spelling), t_sent, t_returned. Verified: cargo test -p fleet-laptop-agent 19/19; live fetch in broker topology returns sha256-identical bytes; trip line shows v:2 with transport and timestamps. --- .../crates/fleet-laptop-agent/src/client.rs | 43 +++++++++++- .../crates/fleet-laptop-agent/src/ladder.rs | 7 ++ .../crates/fleet-laptop-agent/src/legs.rs | 69 +++++++++++++++++-- .../crates/fleet-laptop-agent/src/lib.rs | 54 ++++++++++++++- 4 files changed, 162 insertions(+), 11 deletions(-) diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/client.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/client.rs index 1c693bffdf..ce90278d14 100644 --- a/pkgs/fleet/crates/fleet-laptop-agent/src/client.rs +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/client.rs @@ -80,6 +80,20 @@ fn send( body: Option, idempotent: bool, deadline: Duration, +) -> Result { + send_ex(ladder, trip, method, path, body, idempotent, deadline, false) +} + +#[allow(clippy::too_many_arguments)] +fn send_ex( + ladder: &Arc, + trip: &str, + method: &'static str, + path: &str, + body: Option, + idempotent: bool, + deadline: Duration, + direct_only: bool, ) -> Result { let body = match body { Some(Value::Object(mut map)) if method == "POST" && (path == "/exec" || path == "/jobs") => { @@ -94,11 +108,28 @@ fn send( body, trip: trip.to_string(), idempotent, + direct_only, }; let started = Instant::now(); + let t_sent = crate::now_ms(); let result = dispatch(ladder, req, Some(deadline)); let status = result.as_ref().ok().map(|a| a.reply.status); - log_trip(trip, path, started.elapsed().as_millis(), status); + let transport = result.as_ref().ok().map(|a| crate::transport_name(a.leg)); + let t_received = result.as_ref().ok().and_then(|a| { + serde_json::from_slice::(&a.reply.body) + .ok() + .and_then(|v| v.get("_t_received").and_then(Value::as_u64)) + }); + log_trip( + trip, + path, + started.elapsed().as_millis(), + status, + transport, + Some(t_sent), + Some(crate::now_ms()), + t_received, + ); result } @@ -112,7 +143,7 @@ pub fn call( deadline: Duration, ) -> Result { let answer = send(ladder, trip, method, path, body, idempotent, deadline)?; - let value: Value = if answer.reply.body.is_empty() { + let mut value: Value = if answer.reply.body.is_empty() { json!({}) } else { serde_json::from_slice(&answer.reply.body).map_err(|e| CallFailure::Http { @@ -120,6 +151,11 @@ pub fn call( message: format!("unparseable reply: {e}"), })? }; + // Trip-log v2 internal echo (code#5702): never surface it to + // callers; send_ex already recorded it in the trip line. + if let Some(obj) = value.as_object_mut() { + obj.remove("_t_received"); + } if answer.reply.status >= 400 { let message = match value.get("error") { Some(Value::String(s)) => s.clone(), @@ -147,6 +183,7 @@ pub fn cancel(ladder: &Arc, trip: &str) -> bool { body: Some(json!({ "trip": trip })), trip: trip.to_string(), idempotent: true, + direct_only: false, }; dispatch(ladder, req, Some(Duration::from_secs(CANCEL_BUDGET_S))) .map(|a| a.reply.status == 200) @@ -405,7 +442,7 @@ fn fetch_chunk(ladder: &Arc, remote: &str, off: u64) -> Result, "/file?path={}&off={off}&len={FILE_CHUNK_MAX}", percent_encode(remote) ); - let answer = send(ladder, &trip, "GET", &path, None, true, default_deadline())?; + let answer = send_ex(ladder, &trip, "GET", &path, None, true, default_deadline(), true)?; if answer.reply.status >= 400 { let message = String::from_utf8_lossy(&answer.reply.body).into_owned(); return Err(CallFailure::Http { status: answer.reply.status, message }); diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs index 0d4354c8c3..8285ff0d30 100644 --- a/pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/ladder.rs @@ -19,6 +19,9 @@ pub struct Request { pub body: Option, pub trip: String, pub idempotent: bool, + /// Raw-byte replies (GET /file) cannot cross the broker leg: its + /// protocol is JSON-only. Direct legs only, like the Python client. + pub direct_only: bool, } #[derive(Debug, PartialEq)] @@ -109,6 +112,9 @@ impl Ladder { let mut failures: Vec = Vec::new(); for leg in &self.legs { let name = leg.name(); + if req.direct_only && name == "broker" { + continue; + } match leg.call(req) { Ok(reply) => { return Ok(Answer { @@ -194,6 +200,7 @@ mod tests { body: None, trip: "t".into(), idempotent, + direct_only: false, } } diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs index b35006d239..fc313c4c18 100644 --- a/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/legs.rs @@ -9,6 +9,8 @@ use std::io::{Read, Write}; use std::os::unix::net::UnixStream; use std::path::PathBuf; +use std::sync::Mutex; +use std::time::{Duration, Instant}; use fleet_proxy::http::{HttpConn, HttpError}; use fleet_proxy::tunnel::{connect_cf_tunnel, connect_tunnel, egress_from_env, egress_from_env_url_port, Egress}; @@ -104,10 +106,67 @@ fn exchange( /// The Cloudflare leg. Its Access service token is a fleet secret, /// resolved when the leg is tried (so a healthy broker never pays for /// it); the value never leaves this process except in the headers. +/// +/// Resolution mirrors the Python client (code#5702 lineage): a success +/// is cached for the life of the process, a failure is cached for +/// 60 s — the resolver chain can take ~2 minutes to fail (broker +/// retries, then the Bitwarden subprocess), and no caller should pay +/// that more than once a minute. The chain's own error is surfaced in +/// the Absent message: SecretError is value-free by design, and "the +/// secret is unavailable" without its reason is undiagnosable (the +/// 2026-11-17 parity pass on #10796 burned its CF budget on exactly +/// that opacity). pub struct CfLeg { pub token: String, pub config: fleet_config::Config, pub cf_host: String, + pub cache: Mutex, +} + +#[derive(Default)] +pub struct CfCache { + ready: Option>, + failed_at: Option, +} + +impl CfLeg { + fn headers(&self) -> Result, LegError> { + let mut cache = self.cache.lock().unwrap(); + if let Some(headers) = &cache.ready { + return Ok(headers.clone()); + } + if let Some(at) = cache.failed_at { + if at.elapsed() < Duration::from_secs(60) { + return Err(LegError::Absent(format!( + "secret {CF_ACCESS_SECRET} unavailable (failure cached <60s)" + ))); + } + } + let resolver = fleet_secrets::Resolver::default_chain(&self.config); + let resolved = resolver.resolve(CF_ACCESS_SECRET).map_err(|e| { + LegError::Absent(format!("secret {CF_ACCESS_SECRET} unavailable: {e}")) + }); + let secret = match resolved { + Ok(secret) => secret, + Err(e) => { + cache.failed_at = Some(Instant::now()); + return Err(e); + } + }; + match cf_access_headers(secret.expose()) { + Some(headers) => { + cache.ready = Some(headers.clone()); + cache.failed_at = None; + Ok(headers) + } + None => { + cache.failed_at = Some(Instant::now()); + Err(LegError::Absent(format!( + "secret {CF_ACCESS_SECRET} is not a service token" + ))) + } + } + } } impl Leg for CfLeg { @@ -118,12 +177,7 @@ impl Leg for CfLeg { fn call(&self, req: &Request) -> Result { let egress: Egress = egress_from_env_url_port() .map_err(|e| LegError::Absent(e))?; - let resolver = fleet_secrets::Resolver::default_chain(&self.config); - let secret = resolver - .resolve(CF_ACCESS_SECRET) - .map_err(|_| LegError::Absent(format!("secret {CF_ACCESS_SECRET} unavailable")))?; - let headers = cf_access_headers(secret.expose()) - .ok_or_else(|| LegError::Absent(format!("secret {CF_ACCESS_SECRET} is not a service token")))?; + let headers = self.headers()?; let conn = connect_cf_tunnel(&egress, &self.cf_host) .and_then(HttpConn::from_tls); exchange(conn, req, &self.token, &self.cf_host, &headers) @@ -192,6 +246,7 @@ pub fn ladder(config: &fleet_config::Config) -> Result { token: token.clone(), config: config.clone(), cf_host: config.cf_host().to_string(), + cache: Mutex::new(CfCache::default()), }), Box::new(TailscaleLeg { token: token.clone(), @@ -226,6 +281,7 @@ mod tests { body: None, trip: "t".into(), idempotent: true, + direct_only: false, }; assert!(matches!(leg.call(&req), Err(LegError::Absent(_)))); } @@ -238,6 +294,7 @@ mod tests { body: None, trip: "t".into(), idempotent: true, + direct_only: false, }; assert!(matches!(SshLeg.call(&req), Err(LegError::Absent(_)))); } diff --git a/pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs b/pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs index 5ee4741c58..69a5daef18 100644 --- a/pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs +++ b/pkgs/fleet/crates/fleet-laptop-agent/src/lib.rs @@ -89,24 +89,69 @@ pub fn new_trip() -> String { /// client wrote a line. #[derive(serde::Serialize, Debug, PartialEq)] pub struct TripRecord { + /// Trip-log schema version; 2 matches the Python client's v2 lines. + pub v: u8, pub ts: String, pub trip: String, pub path: String, pub total_ms: u128, pub status: Option, + /// The leg that answered, in the Python client's spelling + /// (broker / cf / ts / ssh); absent when no leg answered. + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub t_sent: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub t_returned: Option, + /// Daemon-echoed receive time (the reply's `_t_received`), when + /// the reply carried one — the Python client's third v2 stamp. + #[serde(skip_serializing_if = "Option::is_none")] + pub t_received: Option, +} + +/// Milliseconds since the Unix epoch. +pub fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// The Python client's spelling for a ladder leg name. +pub fn transport_name(leg: &str) -> String { + match leg { + "cloudflare" => "cf".to_string(), + "tailscale" => "ts".to_string(), + other => other.to_string(), + } } /// Append one trip record with a single O_APPEND write. Logging must /// never break or visibly delay a call, so every error is swallowed. -pub fn log_trip(trip: &str, path: &str, total_ms: u128, status: Option) { +pub fn log_trip( + trip: &str, + path: &str, + total_ms: u128, + status: Option, + transport: Option, + t_sent: Option, + t_returned: Option, + t_received: Option, +) { let _ = append_trip( &trip_log(), &TripRecord { + v: 2, ts: iso_utc(now_secs()), trip: trip.to_string(), path: path.to_string(), total_ms, status, + transport, + t_sent, + t_returned, + t_received, }, ); } @@ -175,15 +220,20 @@ mod tests { #[test] fn trip_record_keeps_the_python_field_order() { let rec = TripRecord { + v: 2, ts: "T".into(), trip: "t".into(), path: "/exec".into(), total_ms: 5, status: None, + transport: Some("ts".into()), + t_sent: Some(100), + t_returned: Some(105), + t_received: Some(103), }; assert_eq!( serde_json::to_string(&rec).unwrap(), - r#"{"ts":"T","trip":"t","path":"/exec","total_ms":5,"status":null}"# + r#"{"v":2,"ts":"T","trip":"t","path":"/exec","total_ms":5,"status":null,"transport":"ts","t_sent":100,"t_returned":105,"t_received":103}"# ); }