rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Finding this machine on an encrypted overlay network, for the address
//! `rho daemon bridge setup` gives the bridge: Tailscale, then NetBird, as
//! each one's CLI reports it.

use std::{
    net::{IpAddr, Ipv4Addr},
    time::Duration,
};

use serde::Deserialize;

/// How long an overlay's CLI may take to report this machine's address.
//
// Tripwire. Measured on Linux with NetBird connected, 7 runs: `netbird
// status --json` took 0.03 s with no terminal on stdin, as setup runs it,
// and up to 1.34 s with one. Ten seconds is a CLI that is wedged.
const OVERLAY_TIMEOUT: Duration = Duration::from_secs(10);

/// This machine on an overlay network.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Overlay {
    pub(super) ip: Ipv4Addr,
    /// Its name there, such as `devbox.tail1234.ts.net`.
    pub(super) fqdn: Option<String>,
}

impl Overlay {
    /// Its names there: the full one, then its first label, which the
    /// overlay's DNS search domain resolves too (MagicDNS's `devbox`).
    pub(super) fn names(&self) -> Vec<String> {
        let Some(fqdn) = &self.fqdn else {
            return Vec::new();
        };
        let mut names = vec![fqdn.clone()];
        if let Some((short, _)) = fqdn.split_once('.') {
            names.push(short.to_owned());
        }
        names
    }
}

/// `tailscale status --json`, as far as setup reads it.
#[derive(Deserialize)]
struct TailscaleStatus {
    #[serde(rename = "BackendState")]
    backend_state: String,
    #[serde(rename = "Self")]
    this: Option<TailscalePeer>,
}

#[derive(Deserialize)]
struct TailscalePeer {
    #[serde(rename = "DNSName", default)]
    dns_name: String,
    #[serde(rename = "TailscaleIPs", default)]
    tailscale_ips: Vec<IpAddr>,
}

/// This machine on Tailscale, from `tailscale status --json`.
pub(super) fn parse_tailscale(json: &[u8]) -> Result<Overlay, String> {
    let status: TailscaleStatus =
        serde_json::from_slice(json).map_err(|error| format!("unreadable status: {error}"))?;
    if status.backend_state != "Running" {
        return Err(format!("state {}", status.backend_state));
    }
    let this = status.this.ok_or("no address")?;
    let ip = this
        .tailscale_ips
        .iter()
        .find_map(|ip| match ip {
            IpAddr::V4(ip) => Some(*ip),
            IpAddr::V6(_) => None,
        })
        .ok_or("no IPv4 address")?;
    let fqdn = this.dns_name.trim_end_matches('.');
    Ok(Overlay {
        ip,
        fqdn: (!fqdn.is_empty()).then(|| fqdn.to_owned()),
    })
}

/// `netbird status --json`, as far as setup reads it.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct NetbirdStatus {
    daemon_status: String,
    #[serde(default)]
    netbird_ip: String,
    #[serde(default)]
    fqdn: String,
}

/// This machine on NetBird, from `netbird status --json`.
pub(super) fn parse_netbird(json: &[u8]) -> Result<Overlay, String> {
    let status: NetbirdStatus =
        serde_json::from_slice(json).map_err(|error| format!("unreadable status: {error}"))?;
    if status.daemon_status != "Connected" {
        return Err(format!("state {}", status.daemon_status));
    }
    let address = status.netbird_ip.split('/').next().unwrap_or_default();
    let ip = address
        .parse()
        .map_err(|_| format!("no IPv4 address in {:?}", status.netbird_ip))?;
    Ok(Overlay {
        ip,
        fqdn: (!status.fqdn.is_empty()).then_some(status.fqdn),
    })
}

/// Reads an overlay CLI's `status --json`.
type ParseStatus = fn(&[u8]) -> Result<Overlay, String>;

/// Asks Tailscale, then NetBird, for this machine's overlay address. The
/// error names what each said.
pub(super) async fn find_overlay() -> Result<Overlay, String> {
    let tailscale: &[&str] = if cfg!(target_os = "macos") {
        // The App Store app puts no `tailscale` on the PATH.
        &[
            "tailscale",
            "/Applications/Tailscale.app/Contents/MacOS/Tailscale",
        ]
    } else {
        &["tailscale"]
    };
    let overlays: [(&str, &[&str], ParseStatus); 2] = [
        ("Tailscale", tailscale, parse_tailscale),
        ("NetBird", &["netbird"], parse_netbird),
    ];
    let mut why = Vec::new();
    for (name, programs, parse) in overlays {
        let mut said = "not installed".to_owned();
        for program in programs {
            match status_json(program).await {
                Ok(Some(json)) => match parse(&json) {
                    Ok(overlay) => return Ok(overlay),
                    Err(error) => said = error,
                },
                Ok(None) => {}
                Err(error) => said = error,
            }
        }
        why.push(format!("{name}: {said}"));
    }
    Err(why.join("; "))
}

/// What `<program> status --json` prints; `None` when there is no such
/// program.
async fn status_json(program: &str) -> Result<Option<Vec<u8>>, String> {
    let child = tokio::process::Command::new(program)
        .args(["status", "--json"])
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true)
        .output();
    match tokio::time::timeout(OVERLAY_TIMEOUT, child).await {
        Err(_) => Err(format!(
            "`{program} status --json` did not answer within OVERLAY_TIMEOUT ({OVERLAY_TIMEOUT:?})"
        )),
        Ok(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Ok(Err(error)) => Err(format!("could not run `{program}`: {error}")),
        Ok(Ok(output)) if output.status.success() => Ok(Some(output.stdout)),
        Ok(Ok(output)) => Err(format!("`{program} status` failed with {}", output.status)),
    }
}

#[cfg(test)]
#[path = "setup_overlay_tests.rs"]
mod tests;