rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{collections::BTreeSet, time::Duration};

use pretty_assertions::assert_eq;
use rho_protocol::MAX_LINE_BYTES;
use serde_json::{json, Map, Value};

use futures_util::{SinkExt, StreamExt};
use tokio::{
    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt},
    time::Instant,
};
use tokio_tungstenite::{
    tungstenite::{
        protocol::{frame::coding::CloseCode, Role},
        Message as WsMessage,
    },
    WebSocketStream,
};

use super::{prepare_daemon_line, relay_websocket, TooLarge, ENVIRONMENT_METHODS, IDLE_TIMEOUT};

fn sample_host_env() -> Map<String, Value> {
    Map::from_iter([
        ("PATH".to_owned(), json!("/usr/local/bin:/usr/bin")),
        ("HOME".to_owned(), json!("/home/host")),
    ])
}

/// `line` without its trailing `\n`, which must be its only newline.
fn one_line(mut line: Vec<u8>) -> Vec<u8> {
    assert_eq!(line.pop(), Some(b'\n'));
    assert!(!line.contains(&b'\n') && !line.contains(&b'\r'));
    line
}

// Covers: incoming WebSocket text frames are compacted to one NDJSON line,
// environment-bearing methods inherit host_env with client overrides, malformed
// non-object environment values pass through for daemon validation, and raw
// newlines in invalid JSON cannot smuggle a second JSON-RPC line.
// Owner: daemon_http::bridge.
#[test]
fn prepare_daemon_line_compacts_overlays_env_and_prevents_smuggling() {
    let host_env = sample_host_env();

    // 1. Omitted environment on rho/session/new gets host_env.
    let line = prepare_daemon_line(
        r#"{"jsonrpc":"2.0","id":1,"method":"rho/session/new","params":{"cwd":"/tmp"}}"#,
        &host_env,
    )
    .unwrap();
    let parsed: Value = serde_json::from_slice(&one_line(line.bytes)).unwrap();
    assert_eq!(
        parsed,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "rho/session/new",
            "params": {
                "cwd": "/tmp",
                "environment": {
                    "HOME": "/home/host",
                    "PATH": "/usr/local/bin:/usr/bin"
                }
            }
        })
    );

    // 2. Client environment overlays host_env (client wins on collision).
    let line = prepare_daemon_line(
        r#"{"jsonrpc":"2.0","id":2,"method":"rho/session/prompt","params":{"session":"s1","content":[],"environment":{"PATH":"/custom/bin","EXTRA":"1"}}}"#,
        &host_env,
    )
    .unwrap();
    let parsed: Value = serde_json::from_slice(&line.bytes).unwrap();
    assert_eq!(
        parsed["params"]["environment"],
        json!({
            "HOME": "/home/host",
            "PATH": "/custom/bin",
            "EXTRA": "1"
        })
    );

    // 3. Non-object environment stays untouched so the daemon returns InvalidParams.
    let line = prepare_daemon_line(
        r#"{"jsonrpc":"2.0","id":3,"method":"rho/auth/list","params":{"environment":"bad"}}"#,
        &host_env,
    )
    .unwrap();
    let parsed: Value = serde_json::from_slice(&line.bytes).unwrap();
    assert_eq!(parsed["params"]["environment"], json!("bad"));

    // 4. Pretty-printed non-environment method compacts to one line without
    // injecting an environment field.
    let pretty = "{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 4,\n  \"method\": \"rho/daemon/status\",\n  \"params\": {}\n}";
    let line = prepare_daemon_line(pretty, &host_env).unwrap();
    let parsed: Value = serde_json::from_slice(&one_line(line.bytes)).unwrap();
    assert_eq!(parsed["params"], json!({}));

    // 5. Invalid JSON with embedded newline stays one single line (no smuggling).
    let smuggled = "not json\n{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"rho/daemon/stop\"}";
    one_line(prepare_daemon_line(smuggled, &host_env).unwrap().bytes);

    // 6. Oversized frame is rejected before reaching the daemon.
    let huge = "x".repeat(MAX_LINE_BYTES + 1);
    assert_eq!(
        prepare_daemon_line(&huge, &host_env),
        Err(TooLarge {
            bytes: MAX_LINE_BYTES + 1
        })
    );
}

// Covers: the bridge overlays the host environment on exactly the methods
// whose params carry `environment`, so a method that gains one cannot
// silently miss the overlay.
// Owner: daemon_http::bridge.
#[test]
fn environment_methods_are_the_methods_whose_params_carry_an_environment() {
    let schema = rho_protocol::schema::document();
    let definitions = &schema["$defs"];
    let carrying: BTreeSet<&str> = schema["methods"]
        .as_object()
        .unwrap()
        .iter()
        .filter(|(_, method)| {
            let params = method["params"]["$ref"]
                .as_str()
                .and_then(|reference| reference.rsplit('/').next())
                .map_or(&Value::Null, |name| &definitions[name]);
            params["properties"].get("environment").is_some()
        })
        .map(|(name, _)| name.as_str())
        .collect();
    assert_eq!(carrying, BTreeSet::from(ENVIRONMENT_METHODS));
}

/// `line` as one client text frame, which must be masked; a zero mask
/// leaves the payload as is.
fn masked_text_frame(line: &[u8]) -> Vec<u8> {
    let length = u8::try_from(line.len()).ok().filter(|length| *length < 126);
    let mut frame = vec![0x81, 0x80 | length.expect("a one-byte length"), 0, 0, 0, 0];
    frame.extend_from_slice(line);
    frame
}

// Covers: a client is alive while any of its bytes arrive, so one frame
// trickling in slower than IDLE_TIMEOUT (a large message on a slow uplink)
// reaches the daemon whole, and a client that then sends nothing is dropped
// IDLE_TIMEOUT after its last byte.
// Owner: daemon_http::bridge.
#[tokio::test(start_paused = true)]
async fn a_client_lives_while_its_bytes_arrive_and_goes_once_silent() {
    let (mut client, socket) = tokio::io::duplex(64 * 1024);
    let (mut daemon, daemon_side) = tokio::io::duplex(64 * 1024);
    let relay = tokio::spawn(async move {
        let (draining, cut_off) = (std::future::pending(), std::future::pending());
        relay_websocket(socket, daemon_side, &Map::new(), draining, cut_off).await;
    });
    let line = br#"{"jsonrpc":"2.0","id":1,"method":"rho/daemon/status"}"#;

    for (at, byte) in masked_text_frame(line).into_iter().enumerate() {
        if at > 0 {
            tokio::time::sleep(IDLE_TIMEOUT * 3 / 4).await;
        }
        client.write_all(&[byte]).await.unwrap();
    }
    let mut forwarded = vec![0; line.len() + 1];
    daemon.read_exact(&mut forwarded).await.unwrap();
    assert_eq!(forwarded, [&line[..], b"\n"].concat());

    let quiet = Instant::now();
    let mut after = Vec::new();
    daemon.read_to_end(&mut after).await.unwrap();
    assert_eq!(after, b"");
    assert_eq!(quiet.elapsed(), IDLE_TIMEOUT);
    relay.await.unwrap();
}

// Covers: a client that sends nothing but takes what the bridge sends it,
// slower than one frame per IDLE_TIMEOUT (a large message on a slow
// downlink), stays connected to the daemon.
// Owner: daemon_http::bridge.
#[tokio::test(start_paused = true)]
async fn a_client_lives_while_it_takes_a_large_message_slowly() {
    let (mut client, socket) = tokio::io::duplex(4 * 1024);
    let (mut daemon, daemon_side) = tokio::io::duplex(64 * 1024);
    tokio::spawn(async move {
        let (draining, cut_off) = (std::future::pending(), std::future::pending());
        relay_websocket(socket, daemon_side, &Map::new(), draining, cut_off).await;
    });
    let message = format!(r#"{{"pad":"{}"}}"#, "x".repeat(64 * 1024));
    daemon.write_all(message.as_bytes()).await.unwrap();
    daemon.write_all(b"\n").await.unwrap();

    let mut taken = 0;
    while taken < message.len() {
        tokio::time::sleep(IDLE_TIMEOUT * 3 / 4).await;
        let mut chunk = [0; 4 * 1024];
        taken += client.read(&mut chunk).await.unwrap();
    }

    // Still connected, though taking it took far longer than IDLE_TIMEOUT:
    // the daemon's side is open, with nothing to read.
    let mut byte = [0; 1];
    let read = tokio::time::timeout(Duration::from_secs(1), daemon.read(&mut byte)).await;
    assert!(
        read.is_err(),
        "the bridge closed the daemon connection: {read:?}"
    );
}

/// A `rho/hello` with `id`, offering zstd.
fn offering_hello(id: i64) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "method": "rho/hello",
        "params": {"protocol": {"major": 0, "minor": 1}, "compression": ["zstd"]},
    })
}

/// The daemon's success answer to request `id`, naming `codec` if any.
fn answer(id: i64, codec: Option<&str>) -> Vec<u8> {
    let mut result = json!({"protocol": {"major": 0, "minor": 1}});
    if let Some(codec) = codec {
        result["compression"] = json!(codec);
    }
    json!({"jsonrpc": "2.0", "id": id, "result": result})
        .to_string()
        .into_bytes()
}

/// `line` and its newline.
fn sent(line: &[u8]) -> Vec<u8> {
    [line, b"\n"].concat()
}

// Covers: requests reach the daemon whole, compression offers included; only
// the daemon's answer to a forwarded hello, in order, naming a codec switches
// what follows to binary frames that join into exactly the bytes it sent,
// including bytes that arrived with the answer; an answer naming none, an
// error answer, or another request's answer keeps text frames; and the
// daemon closing ends either mode with `Normal`.
// Owner: daemon_http::bridge.
#[tokio::test]
async fn only_a_hello_answer_naming_a_codec_relays_the_rest_as_binary_frames() {
    struct Case {
        name: &'static str,
        requests: Vec<Value>,
        /// What the daemon sends, one write each.
        writes: Vec<Vec<u8>>,
        relayed: Vec<Relayed>,
    }
    let stream = vec![0x28, 0xb5, 0x2f, 0xfd, 0xff, b'\n', 0x00];
    let line = br#"{"jsonrpc":"2.0","method":"rho/job/changed","params":{}}"#.to_vec();
    let refused = br#"{"jsonrpc":"2.0","id":7,"error":{"code":-32000,"message":"no"}}"#.to_vec();
    let status = json!({"jsonrpc": "2.0", "id": 8, "method": "rho/daemon/status"});
    let cases = [
        Case {
            name: "a codec named",
            requests: vec![offering_hello(7)],
            writes: vec![
                [sent(&answer(7, Some("zstd"))), stream.clone()].concat(),
                stream.clone(),
            ],
            relayed: vec![
                Relayed::Text(answer(7, Some("zstd"))),
                Relayed::Binary([&stream[..], &stream[..]].concat()),
            ],
        },
        Case {
            name: "no codec named",
            requests: vec![offering_hello(7)],
            writes: vec![[sent(&answer(7, None)), sent(&line)].concat()],
            relayed: vec![Relayed::Text(answer(7, None)), Relayed::Text(line.clone())],
        },
        Case {
            name: "another request's answer",
            requests: vec![offering_hello(7), status],
            writes: vec![[sent(&answer(8, Some("zstd"))), sent(&line)].concat()],
            relayed: vec![
                Relayed::Text(answer(8, Some("zstd"))),
                Relayed::Text(line.clone()),
            ],
        },
        Case {
            name: "an error answer, then a retry",
            requests: vec![offering_hello(7), offering_hello(8)],
            writes: vec![[
                sent(&refused),
                sent(&answer(8, Some("zstd"))),
                stream.clone(),
            ]
            .concat()],
            relayed: vec![
                Relayed::Text(refused.clone()),
                Relayed::Text(answer(8, Some("zstd"))),
                Relayed::Binary(stream.clone()),
            ],
        },
    ];
    for case in cases {
        let (client, socket) = tokio::io::duplex(64 * 1024);
        let (daemon, daemon_side) = tokio::io::duplex(64 * 1024);
        let relay = tokio::spawn(async move {
            let (draining, cut_off) = (std::future::pending(), std::future::pending());
            relay_websocket(socket, daemon_side, &Map::new(), draining, cut_off).await;
        });
        let mut client = WebSocketStream::from_raw_socket(client, Role::Client, None).await;
        for request in &case.requests {
            client
                .send(WsMessage::text(request.to_string()))
                .await
                .unwrap();
        }
        let mut daemon = tokio::io::BufReader::new(daemon);
        for request in &case.requests {
            let mut forwarded = String::new();
            daemon.read_line(&mut forwarded).await.unwrap();
            let forwarded: Value = serde_json::from_str(&forwarded).unwrap();
            assert_eq!(&forwarded, request, "{}", case.name);
        }
        for write in &case.writes {
            daemon.get_mut().write_all(write).await.unwrap();
        }
        drop(daemon);

        let mut relayed = Vec::new();
        let mut close = None;
        while let Some(Ok(message)) = client.next().await {
            match (message, relayed.last_mut()) {
                (WsMessage::Text(text), _) => relayed.push(Relayed::Text(text.as_bytes().to_vec())),
                (WsMessage::Binary(payload), Some(Relayed::Binary(joined))) => {
                    joined.extend_from_slice(&payload);
                }
                (WsMessage::Binary(payload), _) => relayed.push(Relayed::Binary(payload.to_vec())),
                (WsMessage::Close(frame), _) => {
                    close = frame.map(|frame| frame.code);
                    break;
                }
                _ => {}
            }
        }
        assert_eq!(relayed, case.relayed, "{}", case.name);
        assert_eq!(close, Some(CloseCode::Normal), "{}", case.name);
        relay.await.unwrap();
    }
}

/// What the client got: a text frame, or consecutive binary frames joined.
#[derive(Debug, PartialEq, Eq)]
enum Relayed {
    Text(Vec<u8>),
    Binary(Vec<u8>),
}