rho-coding-agent 3.11.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use std::sync::{Arc, Mutex};

use pretty_assertions::assert_eq;
use rho_protocol::methods::{HostPath, HostStreamEnd};
use tokio::{
    io::{AsyncReadExt as _, AsyncWriteExt as _},
    net::{TcpListener, TcpStream},
};

use super::*;
use crate::app::daemon_host::machine_test_support::*;
#[cfg(unix)]
use crate::executable::write_program;

/// A request the test server got: the host it named, without its port,
/// what it asked for, and the `Authorization` it sent.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Asked {
    host: String,
    target: String,
    authorization: Option<String>,
}

impl Asked {
    fn new(host: &str, target: &str, authorization: Option<&str>) -> Self {
        Self {
            host: host.to_owned(),
            target: target.to_owned(),
            authorization: authorization.map(str::to_owned),
        }
    }
}

/// What the test server answers a request with, given its port.
type Answer = dyn Fn(&Asked, u16) -> Vec<u8> + Send + Sync;

/// An HTTP/1.1 server on this machine, until the test ends.
struct Server {
    port: u16,
    asked: Arc<Mutex<Vec<Asked>>>,
}

impl Server {
    /// Each request it got, in order.
    fn asked(&self) -> Vec<Asked> {
        self.asked.lock().unwrap().clone()
    }
}

/// Starts a [`Server`] answering each request with `answer`'s bytes, then
/// keeping the connection for the next one until the client closes it, or
/// closing it after an answer that says `Connection: close`. An empty
/// answer leaves the client waiting.
async fn serve(answer: impl Fn(&Asked, u16) -> Vec<u8> + Send + Sync + 'static) -> Server {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let asked = Arc::new(Mutex::new(Vec::new()));
    let answer: Arc<Answer> = Arc::new(answer);
    let seen = Arc::clone(&asked);
    tokio::spawn(async move {
        loop {
            let Ok((socket, _)) = listener.accept().await else {
                return;
            };
            tokio::spawn(answer_each(
                socket,
                port,
                Arc::clone(&answer),
                Arc::clone(&seen),
            ));
        }
    });
    Server { port, asked }
}

/// Answers each request on `socket`, as [`serve`] says.
async fn answer_each(
    mut socket: TcpStream,
    port: u16,
    answer: Arc<Answer>,
    seen: Arc<Mutex<Vec<Asked>>>,
) {
    let mut buffer = Vec::new();
    loop {
        let end = loop {
            if let Some(end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") {
                break end;
            }
            let mut read = [0; 4096];
            match socket.read(&mut read).await {
                Ok(0) | Err(_) => return,
                Ok(count) => buffer.extend_from_slice(&read[..count]),
            }
        };
        let head = String::from_utf8_lossy(&buffer[..end]).into_owned();
        buffer.drain(..end + 4);
        let mut lines = head.split("\r\n");
        // `GET /picture HTTP/1.1`, then its headers.
        let target = lines.next().unwrap().split(' ').nth(1).unwrap();
        let mut asked = Asked::new("", target, None);
        for (name, value) in lines.filter_map(|line| line.split_once(':')) {
            let value = value.trim();
            match name.to_ascii_lowercase().as_str() {
                "host" => asked.host = value.split(':').next().unwrap().to_owned(),
                "authorization" => asked.authorization = Some(value.to_owned()),
                _ => {}
            }
        }
        seen.lock().unwrap().push(asked.clone());
        let response = answer(&asked, port);
        if socket.write_all(&response).await.is_err() {
            return;
        }
        if String::from_utf8_lossy(&response).contains("Connection: close") {
            let _ = socket.shutdown().await;
            return;
        }
    }
}

/// A 200 carrying `body`, which it says the length of.
fn picture(body: &[u8]) -> Vec<u8> {
    let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len());
    [head.as_bytes(), body].concat()
}

/// A 200 carrying `body`, which it doesn't say the length of: it ends
/// when the server closes the connection.
fn unsized_picture(body: &[u8]) -> Vec<u8> {
    [
        b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".as_slice(),
        body,
    ]
    .concat()
}

/// A redirect to `location`.
fn moved(location: &str) -> Vec<u8> {
    format!("HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\n\r\n").into_bytes()
}

fn not_found() -> Vec<u8> {
    b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".to_vec()
}

/// The web a test's server plays, on `port`: http, with `forge.test`, a
/// host under it and one of GitHub's image hosts all found on this
/// machine, within `deadline`.
fn web(port: u16, deadline: Duration) -> Web {
    let here = SocketAddr::from(([127, 0, 0, 1], 0));
    let hosts = ["forge.test", "img.forge.test", "x.githubusercontent.com"];
    Web {
        scheme: "http",
        port: Some(port),
        deadline,
        resolve: hosts.map(|host| (host.to_owned(), here)).to_vec(),
        client: OnceCell::new(),
    }
}

/// Fetches `url` for the forge `forge.test` on `machine`, signed in with
/// `gh`, up to `max_bytes`.
async fn fetch_on(
    machine: &Machine,
    caller: &Caller,
    web: &Web,
    url: String,
    gh: Option<HostPath>,
    max_bytes: u64,
) -> Result<ForgeFetchResponse, RpcError> {
    let params = ForgeFetchParams::new(url, "forge.test", gh, max_bytes);
    fetch(machine, caller.clone(), params, web).await
}

// Covers: a fetch goes only to the forge's host, the hosts under it and
// GitHub's image hosts, over https, with no user, password or port, as
// reqwest reads the URL: no lookalike, userinfo, backslash or port reaches
// another host, such as one in the machine's private network.
// Owner: daemon host calls.
#[test]
fn only_the_forges_hosts_are_fetched() {
    let cases = [
        ("https://github.com/user-attachments/assets/1", true),
        ("https://GitHub.com/a.png", true),
        ("https://github.com:443/a.png", true),
        ("https://api.github.com/x", true),
        (
            "https://private-user-images.githubusercontent.com/1.png",
            true,
        ),
        (
            "https://github-production-user-asset-6210df.s3.amazonaws.com/1.png",
            true,
        ),
        ("http://github.com/a.png", false),
        ("https://githubusercontent.com/a.png", false),
        ("https://example.com/a.png", false),
        ("https://169.254.169.254/latest/meta-data", false),
        ("https://localhost/a.png", false),
        ("https://github.com.evil.example/a.png", false),
        ("https://x.githubusercontent.com@10.0.0.1/a.png", false),
        ("https://github.com:x@github.com/a.png", false),
        ("https://10.0.0.1\\.githubusercontent.com/a.png", false),
        (
            "https://user-images.githubusercontent.com:8080/a.png",
            false,
        ),
        ("file:///etc/passwd", false),
        ("https:///a.png", false),
    ];
    for (url, fetched) in cases {
        let parsed = Url::parse(url).unwrap();
        let answer = allowed(&parsed, "github.com", &Web::public());
        assert_eq!(answer.is_ok(), fetched, "{url}");
        if let Err(error) = answer {
            assert_eq!(error.code, ErrorCode::ForgeFetchRefused.code(), "{url}");
        }
    }
}

// Covers: the token goes to the forge's host exactly, its case aside, over
// https: never over http, to a host under it, one that only starts like
// it, one behind a user, or one on another port.
// Owner: daemon host calls.
#[test]
fn the_token_goes_to_the_forge_alone() {
    let cases = [
        ("https://github.com/user-attachments/assets/1", true),
        ("https://GitHub.com/a.png", true),
        ("https://github.com?x", true),
        ("http://github.com/a.png", false),
        ("https://api.github.com/a.png", false),
        ("https://avatars.githubusercontent.com/u/1", false),
        ("https://github.com.evil.example/a.png", false),
        ("https://github.com@evil.example/a.png", false),
        ("https://github.com:8443/a.png", false),
    ];
    for (url, sends) in cases {
        let parsed = Url::parse(url).unwrap();
        assert_eq!(
            signs_in(&parsed, "GitHub.com", &Web::public()),
            sends,
            "{url}"
        );
    }
}

// Covers: a fetch follows up to FORGE_FETCH_MAX_REDIRECTS redirects, full
// or relative, each checked as the URL was, signing only the requests to
// the forge's host with the token gh gives: never a host under it or one a
// redirect names. One more redirect, or one to a host not allowed, is
// refused, and that host is never asked.
// Owner: daemon host calls.
#[cfg(unix)]
#[tokio::test]
async fn a_fetch_follows_checked_redirects_and_signs_the_forge_alone() {
    let server = serve(|asked, port| match asked.target.as_str() {
        "/moved" => moved(&format!("http://img.forge.test:{port}/under")),
        "/under" => moved(&format!("http://x.githubusercontent.com:{port}/storage")),
        "/storage" => moved("/picture"),
        "/picture" => picture(b"PNG"),
        "/away" => moved(&format!("http://elsewhere.test:{port}/picture")),
        "/loop" => moved("/loop"),
        _ => not_found(),
    })
    .await;
    let dir = tempfile::tempdir().unwrap();
    let gh = dir.path().join("gh");
    write_program(
        &gh,
        "#!/bin/sh\n[ \"$*\" = 'auth token --hostname=forge.test' ] && echo secret\n",
    );
    let (machine, caller) = (machine_in(&[]), caller());
    let web = web(server.port, FORGE_DEADLINE);
    let at = |path: &str| format!("http://forge.test:{}{path}", server.port);
    let fetch = |path: &str| fetch_on(&machine, &caller, &web, at(path), Some(host(&gh)), 1 << 20);

    let fetched = fetch("/moved").await.unwrap();
    assert_eq!(
        read_out(&caller, fetched.stream).await,
        (b"PNG".to_vec(), HostStreamEnd::Done)
    );
    let signed = Some("Bearer secret");
    assert_eq!(
        server.asked(),
        [
            Asked::new("forge.test", "/moved", signed),
            Asked::new("img.forge.test", "/under", None),
            Asked::new("x.githubusercontent.com", "/storage", None),
            Asked::new("x.githubusercontent.com", "/picture", None),
        ]
    );

    let looped = fetch("/loop").await.unwrap_err();
    let away = fetch("/away").await.unwrap_err();
    for refused in [&looped, &away] {
        assert_eq!(
            refused.code,
            ErrorCode::ForgeFetchRefused.code(),
            "{refused:?}"
        );
    }
    let mut asked = server.asked();
    let after = asked.split_off(4);
    let looping = Asked::new("forge.test", "/loop", signed);
    let expected = [
        vec![looping; 1 + FORGE_FETCH_MAX_REDIRECTS as usize],
        vec![Asked::new("forge.test", "/away", signed)],
    ]
    .concat();
    assert_eq!(after, expected);
}

// Covers: a picture that says it is longer than max_bytes is refused
// before any stream opens, naming its length and the limit; one that
// doesn't say so streams max_bytes and ends truncated; one exactly
// max_bytes long is whole; an error status fails, retryably, saying it.
// Owner: daemon host calls.
#[tokio::test]
async fn a_picture_past_the_limit_is_refused_or_cut() {
    let server = serve(|asked, _| match asked.target.as_str() {
        "/said" => picture(&[b'x'; 2000]),
        "/unsaid" => unsized_picture(&[b'x'; 2000]),
        "/exact" => picture(&[b'x'; 1000]),
        _ => not_found(),
    })
    .await;
    let (machine, caller) = (machine_in(&[]), caller());
    let web = web(server.port, FORGE_DEADLINE);
    let at = |path: &str| format!("http://forge.test:{}{path}", server.port);
    let fetch = |path: &str| fetch_on(&machine, &caller, &web, at(path), None, 1000);

    let said = fetch("/said").await.unwrap_err();
    assert_eq!(said.code, ErrorCode::ForgeFetchRefused.code());
    assert!(
        said.message.contains("2000") && said.message.contains("1000"),
        "{}",
        said.message
    );
    let unsaid = fetch("/unsaid").await.unwrap();
    assert_eq!(
        read_out(&caller, unsaid.stream).await,
        (vec![b'x'; 1000], HostStreamEnd::Truncated)
    );
    let exact = fetch("/exact").await.unwrap();
    assert_eq!(
        read_out(&caller, exact.stream).await,
        (vec![b'x'; 1000], HostStreamEnd::Done)
    );
    let gone = fetch("/gone").await.unwrap_err();
    assert_eq!(
        (gone.code, gone.message.as_str()),
        (
            ErrorCode::HostCallFailed.code(),
            "It answered 404 Not Found."
        )
    );
}

// Covers: a fetch has its deadline in all: a forge that never answers
// fails the call, and one that stops partway through the picture fails
// its stream, rather than holding either open.
// Owner: daemon host calls.
#[tokio::test]
async fn a_fetch_that_hangs_fails_at_its_deadline() {
    let server = serve(|asked, _| match asked.target.as_str() {
        "/picture" => picture(b"PNG"),
        "/partway" => b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\npartial".to_vec(),
        _ => Vec::new(),
    })
    .await;
    let (machine, caller) = (machine_in(&[]), caller());
    // The window holds a connection on this machine and its answer's
    // headers alone: the client is made by the first fetch, before it.
    // `/partway` answered within it in 192 us (median of 34; 4.4 ms at
    // most) under the whole parallel `rho-coding-agent` lib suite, on a
    // 24-core Linux machine (2026-12-03).
    let web = web(server.port, Duration::from_secs(1));
    let at = |path: &str| format!("http://forge.test:{}{path}", server.port);
    let late = "It didn't come within";

    let warm = fetch_on(&machine, &caller, &web, at("/picture"), None, 1000)
        .await
        .unwrap();
    assert_eq!(read_out(&caller, warm.stream).await.1, HostStreamEnd::Done);
    let partway = fetch_on(&machine, &caller, &web, at("/partway"), None, 1000)
        .await
        .unwrap();
    let (bytes, end) = read_out(&caller, partway.stream).await;
    assert_eq!(bytes, b"partial");
    assert!(
        matches!(&end, HostStreamEnd::Failed { message, .. } if message.starts_with(late)),
        "{end:?}"
    );
    let silent = fetch_on(&machine, &caller, &web, at("/silent"), None, 1000)
        .await
        .unwrap_err();
    assert_eq!(silent.code, ErrorCode::HostCallFailed.code());
    assert!(silent.message.starts_with(late), "{}", silent.message);
}

// Covers: a fetch goes through the proxy the login's environment names,
// as curl did for rho-ui, so a machine that reaches the web through one
// still loads pictures.
// Owner: daemon host calls.
#[tokio::test]
async fn a_fetch_goes_through_the_logins_proxy() {
    let proxy = serve(|_, _| picture(b"PNG")).await;
    let address = format!("http://127.0.0.1:{}", proxy.port);
    let (machine, caller) = (machine_in(&[("https_proxy", address.as_str())]), caller());
    // No host is found on this machine: only the proxy reaches it.
    let web = Web {
        resolve: Vec::new(),
        ..web(9, FORGE_DEADLINE)
    };
    let url = "http://forge.test:9/picture";

    let fetched = fetch_on(&machine, &caller, &web, url.to_owned(), None, 1000)
        .await
        .unwrap();
    assert_eq!(
        read_out(&caller, fetched.stream).await,
        (b"PNG".to_vec(), HostStreamEnd::Done)
    );
    assert_eq!(proxy.asked(), [Asked::new("forge.test", url, None)]);
}

// Covers: a SOCKS proxy in the login's environment, which the daemon's
// fetch can't go through, fails the fetch naming the variable, rather
// than being passed by or used as an http one, and the message never
// carries the proxy's password.
// Owner: daemon host calls.
#[tokio::test]
async fn a_socks_proxy_is_refused_by_name() {
    let (machine, caller) = (
        machine_in(&[("all_proxy", "SOCKS5H://rho:hunter2@127.0.0.1:1080")]),
        caller(),
    );
    let web = web(9, FORGE_DEADLINE);
    let url = "http://forge.test:9/picture".to_owned();

    let refused = fetch_on(&machine, &caller, &web, url, None, 1000)
        .await
        .unwrap_err();
    assert_eq!(refused.code, ErrorCode::HostCallFailed.code());
    assert_eq!(
        refused.message,
        "The login's all_proxy names a socks5h proxy, which the daemon can't fetch through: only an http or https one."
    );
}

// Covers: a hop to the forge's host that fails after gh gave no token says
// why it went unsigned, in gh's words, as a private repository's picture
// answers 404 to an unsigned fetch; a hop to another host, never signed,
// says nothing of it.
// Owner: daemon host calls.
#[cfg(unix)]
#[tokio::test]
async fn a_failed_fetch_says_why_it_went_unsigned() {
    let server = serve(|_, _| not_found()).await;
    let dir = tempfile::tempdir().unwrap();
    let gh = dir.path().join("gh");
    write_program(
        &gh,
        "#!/bin/sh\necho 'no oauth token found for forge.test' >&2\nexit 1\n",
    );
    let (machine, caller) = (machine_in(&[]), caller());
    let web = web(server.port, FORGE_DEADLINE);
    let fetch = |to: &str| {
        let url = format!("http://{to}:{}/picture", server.port);
        fetch_on(&machine, &caller, &web, url, Some(host(&gh)), 1000)
    };

    let forge = fetch("forge.test").await.unwrap_err();
    assert_eq!(
        forge.message,
        "It answered 404 Not Found; it went unsigned: gh auth token failed: no oauth token found for forge.test."
    );
    let image_host = fetch("x.githubusercontent.com").await.unwrap_err();
    assert_eq!(image_host.message, "It answered 404 Not Found.");
}