rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
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, Relayed as Relay, 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();
    let host_env = Relay {
        host_env: &host_env,
        device: None,
    };

    // 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 daemon hears only the bridge's word for which device opened
// a connection: a hello's `bridge_device` is set to the WebSocket's token,
// replacing a forged one, and stripped when the bridge names none, while
// a request that is not a hello keeps the field as sent.
// Owner: daemon_http::bridge.
#[test]
fn a_hello_carries_the_bridges_device_never_the_clients() {
    let env = Map::new();
    let sent = |frame: Value, device: Option<&str>| -> Value {
        let relayed = Relay {
            host_env: &env,
            device,
        };
        let line = prepare_daemon_line(&frame.to_string(), &relayed).unwrap();
        serde_json::from_slice(&one_line(line.bytes)).unwrap()
    };
    let hello =
        |params: Value| json!({"jsonrpc": "2.0", "id": 1, "method": "rho/hello", "params": params});
    let forged = json!({"protocol": {"major": 0, "minor": 1}, "bridge_device": "victim"});
    let other = json!({"jsonrpc": "2.0", "id": 2, "method": "rho/daemon/status", "params": {"bridge_device": "x"}});
    assert_eq!(
        [
            sent(hello(forged.clone()), Some("phone"))["params"]["bridge_device"].clone(),
            sent(hello(forged), None)["params"]
                .get("bridge_device")
                .cloned()
                .unwrap_or(Value::Null),
            sent(hello(json!({})), Some("phone"))["params"]["bridge_device"].clone(),
            sent(hello(json!(["not", "an", "object"])), Some("phone"))["params"]["bridge_device"]
                .clone(),
            sent(other.clone(), Some("phone"))["params"]["bridge_device"].clone(),
        ],
        [
            json!("phone"),
            Value::Null,
            json!("phone"),
            json!("phone"),
            json!("x")
        ]
    );
}

// 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());
        let empty = Map::new();
        let relayed = Relay {
            host_env: &empty,
            device: None,
        };
        relay_websocket(socket, daemon_side, &relayed, 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());
        let empty = Map::new();
        let relayed = Relay {
            host_env: &empty,
            device: None,
        };
        relay_websocket(socket, daemon_side, &relayed, 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());
            let empty = Map::new();
            let relayed = Relay {
                host_env: &empty,
                device: None,
            };
            relay_websocket(socket, daemon_side, &relayed, 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>),
}