rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::net::{Ipv4Addr, SocketAddr};

use pretty_assertions::assert_eq;

use clap::Parser as _;

use super::{plan, serve_args, Listen, Plan};
use crate::{
    app::daemon_http::setup_overlay::Overlay,
    cli::{BridgeSetupArgs, Cli, Command, DaemonCommand},
};

fn args(http: Option<&str>, url: Option<&str>, allow_host: &[&str]) -> BridgeSetupArgs {
    BridgeSetupArgs {
        http: http.map(|http| http.parse().expect("an address")),
        url: url.map(str::to_owned),
        allow_host: allow_host.iter().map(|host| (*host).to_owned()).collect(),
        token: "rho-ui".to_owned(),
    }
}

fn tailnet() -> Result<Overlay, String> {
    Ok(Overlay {
        ip: Ipv4Addr::new(100, 101, 102, 103),
        fqdn: Some("devbox.tail1234.ts.net".to_owned()),
    })
}

/// What setup plans for `args` where finding the overlay gives `overlay`,
/// which is asked only when the flags want it.
fn plan_of(
    args: &BridgeSetupArgs,
    overlay: impl FnOnce() -> Result<Overlay, String>,
) -> anyhow::Result<Plan> {
    let listen = Listen::of(args)?;
    let overlay = listen.wants_overlay().then(overlay);
    plan(listen, overlay, &args.allow_host)
}

fn expected(listen: &str, hosts: &[&str], url: &str) -> Plan {
    Plan {
        listen: listen.parse::<SocketAddr>().expect("an address"),
        allow_hosts: hosts.iter().map(|host| (*host).to_owned()).collect(),
        url: url.parse().expect("a bridge URL"),
    }
}

// Covers: where setup has the bridge listen, which Host names it allows, and
// the address it pairs: the overlay's by default with its MagicDNS names,
// `--http` as given (with the names only on the overlay's own address), and
// `--url` through a TLS proxy on loopback.
// Owner: bridge setup plan (pure).
#[test]
fn setup_plans_the_address_hosts_and_pairing_url() {
    let cases = [
        (
            args(None, None, &[]),
            expected(
                "100.101.102.103:8766",
                &["devbox.tail1234.ts.net", "devbox"],
                "ws://100.101.102.103:8766/ws",
            ),
        ),
        (
            args(None, None, &["devbox", "rho.example.com:443"]),
            expected(
                "100.101.102.103:8766",
                &["devbox.tail1234.ts.net", "devbox", "rho.example.com:443"],
                "ws://100.101.102.103:8766/ws",
            ),
        ),
        (
            args(Some("100.101.102.103:9000"), None, &[]),
            expected(
                "100.101.102.103:9000",
                &["devbox.tail1234.ts.net", "devbox"],
                "ws://100.101.102.103:9000/ws",
            ),
        ),
        (
            args(Some("192.168.1.20:8766"), None, &[]),
            expected("192.168.1.20:8766", &[], "ws://192.168.1.20:8766/ws"),
        ),
        (
            args(Some("[fd00::20]:8766"), None, &[]),
            expected("[fd00::20]:8766", &[], "ws://[fd00::20]:8766/ws"),
        ),
        (
            args(None, Some("wss://devbox.example.com/rho/ws"), &[]),
            expected(
                "127.0.0.1:8766",
                &["devbox.example.com"],
                "wss://devbox.example.com/rho/ws",
            ),
        ),
        (
            args(
                Some("127.0.0.1:9100"),
                Some("wss://devbox.example.com"),
                &[],
            ),
            expected(
                "127.0.0.1:9100",
                &["devbox.example.com"],
                "wss://devbox.example.com/ws",
            ),
        ),
    ];
    for (args, expected) in cases {
        assert_eq!(
            plan_of(&args, tailnet).expect("a plan"),
            expected,
            "{args:?}"
        );
    }
}

// Covers: setup refuses, before installing anything, a bridge whose token
// would cross the internet in the clear (a public bind, a ws:// proxy
// address), a proxy that could not reach a non-loopback bind, a machine with
// no overlay and no address given, and a Host the bridge would refuse to
// start with.
// Owner: bridge setup plan (pure).
#[test]
fn setup_refuses_plans_that_would_leak_the_token_or_not_start() {
    let no_overlay = || Err("Tailscale: not installed; NetBird: not installed".to_owned());
    let cases = [
        args(Some("203.0.113.7:8766"), None, &[]),
        args(Some("0.0.0.0:8766"), None, &[]),
        args(None, Some("ws://devbox.example.com/ws"), &[]),
        args(None, Some("https://devbox.example.com/ws"), &[]),
        args(
            Some("192.168.1.20:8766"),
            Some("wss://devbox.example.com"),
            &[],
        ),
        args(None, None, &[]),
        args(Some("192.168.1.20:8766"), None, &["not a host"]),
    ];
    for args in cases {
        assert!(plan_of(&args, no_overlay).is_err(), "{args:?}");
    }
}

// Covers: the service's arguments are ones `rho daemon serve` reads as
// the plan's address and hosts; a flag it no longer takes would leave the
// service restarting forever.
// Owner: bridge setup plan, against the CLI it runs.
#[test]
fn the_service_serves_the_plan() {
    let plan = expected(
        "100.101.102.103:8766",
        &["devbox.tail1234.ts.net", "devbox"],
        "ws://100.101.102.103:8766/ws",
    );
    let cli = Cli::try_parse_from(std::iter::once("rho".to_owned()).chain(serve_args(&plan)))
        .expect("rho daemon serve reads the service's arguments");
    let Some(Command::Daemon {
        command: Some(DaemonCommand::Serve(serve)),
    }) = cli.command
    else {
        panic!("not rho daemon serve: {:?}", cli.command);
    };
    assert_eq!(
        (serve.http, serve.allow_host),
        (plan.listen, plan.allow_hosts)
    );
}

// Covers: a bridge service saved by hand, as `docs/daemon.md` shows, keeps
// its own settings (a provider key, a proxy's bind): setup refuses to
// replace it, before it stops it or asks the service manager anything.
// Owner: bridge setup install.
#[test]
fn setup_leaves_a_service_saved_by_hand_alone() {
    let home = tempfile::tempdir().expect("a home");
    let service = crate::daemon::ServiceFiles::daemon_http(
        crate::daemon::ServiceManager::Systemd,
        home.path(),
        None,
    );
    let by_hand = "[Service]\nExecStart=/usr/bin/rho daemon serve --http 127.0.0.1:8766\nEnvironment=OPENAI_API_KEY=sk-mine\n";
    std::fs::create_dir_all(service.definition.parent().expect("a directory")).expect("mkdir");
    std::fs::write(&service.definition, by_hand).expect("a unit");

    let installed = super::install(
        &service,
        "# rendered\n",
        "127.0.0.1:0".parse().expect("an address"),
    );

    assert!(installed.is_err());
    assert_eq!(
        std::fs::read_to_string(&service.definition).expect("the unit"),
        by_hand
    );
}