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
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
//! `rho/forge/fetch`: a forge's pictures, the people who post and the
//! images in a pull request's text, fetched on the daemon's machine, the
//! one sure to reach the forge, ported from rho-ui's `forge/picture.rs`
//! (its `SCRIPT` with `curl`, `fetch_here` and `follow`).
//!
//! That machine may sit in a private network, and anyone who can comment
//! writes a pull request's text, so a fetch goes only to the forge's own
//! hosts and GitHub's image hosts ([`allowed`]), over https, and follows
//! no redirect it hasn't checked the same way ([`follow`]), at most
//! [`FORGE_FETCH_MAX_REDIRECTS`] of them, reading at most
//! [`ForgeFetchParams::byte_limit`] bytes. A picture in a private
//! repository's text needs a sign-in: GitHub answers
//! `github.com/user-attachments/assets/…` with a 404 without one, and with
//! a redirect to a signed, five-minute storage URL with the token of an
//! account that can read the repository. So a fetch from the forge's host
//! exactly, the first hop or a redirect's, sends the token `gh auth token`
//! prints ([`signs_in`]); a host under it or any other never gets it, nor
//! does a log.
//!
//! The allowlist is the whole guard: an allowed host's addresses are not
//! checked and pinned, as `tools::web`'s SSRF check pins a fetch's. Those
//! hosts are GitHub's, whose names only GitHub resolves, and the forge's
//! own, which may well be in a private network, as a GitHub Enterprise
//! server is; a fetch through the login's proxy never resolves a host on
//! this machine, so no pin could hold there; and rho-ui's fetch over ssh
//! pinned nothing either.

use std::{net::SocketAddr, path::Path, time::Duration};

use reqwest::{
    header::{HeaderValue, AUTHORIZATION, LOCATION},
    NoProxy, Proxy, Response,
};
use rho_protocol::{
    methods::{
        ForgeFetchParams, ForgeFetchResponse, FORGE_FETCH, FORGE_FETCH_MAX_BYTES,
        FORGE_FETCH_MAX_REDIRECTS,
    },
    Caller, ClientEnvironment, ErrorCode, HostStreamWriter, RpcError,
};
use tokio::{sync::OnceCell, time::Instant};
use url::Url;

use super::{
    absolute, failed, gh_command, log_call, spawn_stream, supervised_output, var, Machine, Origin,
    FORGE_DEADLINE,
};
use crate::{app::pull_requests::gh_failure, error_causes::with_causes};

/// How long `gh auth token` may take before a fetch goes unsigned, as the
/// wire's `ForgeFetchParams::gh` says.
//
// rho-ui's `TOKEN_DEADLINE`: it took 0.08 s there, so this only stops one
// waiting on a locked keyring.
const GH_TOKEN_DEADLINE: Duration = Duration::from_secs(10);

/// Where GitHub serves an image uploaded to it from, besides the forge's
/// own host: `user-images`, `private-user-images`, `camo`, `raw` and
/// `avatars` under this…
const GITHUB_IMAGES: &str = ".githubusercontent.com";

/// …and the storage `user-attachments` and a repository's `assets`
/// redirect to.
const GITHUB_ATTACHMENTS: &str = "github-production-user-asset-6210df.s3.amazonaws.com";

/// The proxy schemes a login's environment may name that the daemon's
/// fetch can't go through: reqwest is built without its `socks` feature.
const SOCKS: [&str; 4] = ["socks4", "socks4a", "socks5", "socks5h"];

/// How a fetch reaches the web: the machine keeps one [`Web::public`] for
/// the calls. A test serves pictures over http on a port of its own,
/// playing each host it names.
pub(crate) struct Web {
    /// The one scheme fetched.
    scheme: &'static str,
    /// The one port a URL may name: none, the scheme's own, but a test's.
    port: Option<u16>,
    /// How long a fetch may take in all, its picture's bytes included.
    deadline: Duration,
    /// Hosts found at an address, not by DNS: a test's. Its URLs name the
    /// port.
    resolve: Vec<(String, SocketAddr)>,
    /// The client every fetch goes through, made by the first ([`client`])
    /// with the proxy the login's environment names, which is read once
    /// for the daemon's life.
    client: OnceCell<reqwest::Client>,
}

impl Web {
    /// The web: https on its own port, within [`FORGE_DEADLINE`].
    pub(crate) fn public() -> Self {
        Self {
            scheme: "https",
            port: None,
            deadline: FORGE_DEADLINE,
            resolve: Vec::new(),
            client: OnceCell::new(),
        }
    }

    /// The client fetches go through, with the proxy `environment` names:
    /// made once and kept when the environment is too ([`Origin`]), else
    /// made for this fetch, so a login shell that answers later still
    /// names the proxy.
    async fn client(
        &self,
        environment: &ClientEnvironment,
        origin: Origin,
    ) -> Result<reqwest::Client, RpcError> {
        if origin == Origin::Fallback {
            return client(environment, self);
        }
        self.client
            .get_or_try_init(|| async { client(environment, self) })
            .await
            .cloned()
    }
}

/// Answers `rho/forge/fetch`: follows `url` through the redirects it
/// answers with, each [`allowed`] first and signed where [`signs_in`]
/// says, then streams the picture from a spawned task, up to
/// [`ForgeFetchParams::byte_limit`]. One that says it is longer is refused
/// before any stream opens; one that runs past it ends the stream
/// truncated there. All of it, the picture's bytes included, comes within
/// the web's deadline, or fails.
pub(super) async fn fetch(
    machine: &Machine,
    caller: Caller,
    params: ForgeFetchParams,
    web: &Web,
) -> Result<ForgeFetchResponse, RpcError> {
    let limit = params.byte_limit();
    let ForgeFetchParams { url, host, gh, .. } = params;
    let url = Url::parse(&url);
    let url_shown = url
        .as_ref()
        .map_or_else(|_| "(not a URL)".to_owned(), shown);
    tracing::info_span!("forge_fetch", url = %url_shown, forge = %host)
        .in_scope(|| log_call(&caller, FORGE_FETCH, gh.as_ref()));
    let url = url.map_err(|error| refused(format!("It isn't a URL: {error}.")))?;
    let gh = gh.as_ref().map(absolute).transpose()?;
    let late = format!(
        "It didn't come within {} s (FORGE_DEADLINE_SECS).",
        web.deadline.as_secs()
    );
    let deadline = Instant::now() + web.deadline;
    let answered = tokio::time::timeout_at(deadline, async {
        let (environment, origin) = machine.login_environment_and_origin().await;
        let client = web.client(&environment, origin).await?;
        follow(&client, url, &host, web, gh, &environment).await
    })
    .await;
    let response = answered.map_err(|_| failed(late.clone()))??;
    if let Some(length) = response.content_length().filter(|&length| length > limit) {
        return Err(refused(format!(
            "It's {length} bytes, over the {limit} this fetch takes (max_bytes, up to FORGE_FETCH_MAX_BYTES, {FORGE_FETCH_MAX_BYTES})."
        )));
    }
    let stream = spawn_stream(&caller, |writer| {
        pump(response, limit, deadline, late, writer)
    })?;
    Ok(ForgeFetchResponse::new(stream))
}

/// The response at `url` once it answers with something other than a
/// redirect: each URL is [`allowed`] before it is asked, and a redirect's
/// is read as a browser would, against the URL that names it. A hop that
/// [`signs_in`] sends the token `gh` gives, asked once, at the first such
/// hop; when it fails having gone unsigned, it says why.
async fn follow(
    client: &reqwest::Client,
    mut url: Url,
    host: &str,
    web: &Web,
    gh: Option<&Path>,
    environment: &ClientEnvironment,
) -> Result<Response, RpcError> {
    let token = OnceCell::new();
    for hop in 0..=FORGE_FETCH_MAX_REDIRECTS {
        allowed(&url, host, web)?;
        let signing = match gh {
            Some(gh) if signs_in(&url, host, web) => {
                Some(token.get_or_init(|| ask(gh, host, environment)).await)
            }
            _ => None,
        };
        let unsigned = signing.and_then(|token| token.as_ref().err());
        let hop_failed = |what: String| {
            failed(match unsigned {
                Some(why) => format!("{what}; it went unsigned: {why}."),
                None => format!("{what}."),
            })
        };
        tracing::debug!(
            hop,
            url = %shown(&url),
            signed = matches!(signing, Some(Ok(_))),
            "forge fetch"
        );
        let mut request = client.get(url.clone());
        if let Some(Ok(bearer)) = signing {
            request = request.header(AUTHORIZATION, bearer.clone());
        }
        let response = request
            .send()
            .await
            .map_err(|error| hop_failed(said(error)))?;
        let status = response.status();
        if status.is_success() {
            return Ok(response);
        }
        if !status.is_redirection() {
            return Err(hop_failed(format!("It answered {status}")));
        }
        let location = response
            .headers()
            .get(LOCATION)
            .ok_or_else(|| hop_failed(format!("It answered {status} without saying where to")))?;
        url = location
            .to_str()
            .ok()
            .and_then(|to| url.join(to).ok())
            .ok_or_else(|| refused("It moved somewhere that isn't a URL.".to_owned()))?;
    }
    Err(refused(format!(
        "It redirected more than {FORGE_FETCH_MAX_REDIRECTS} times (FORGE_FETCH_MAX_REDIRECTS)."
    )))
}

/// The host of `url`, lowercased, when nothing else in its authority could
/// take a fetch elsewhere: over the web's scheme, with no user, password,
/// or port but the web's. `url` is read as reqwest reads it, so no user,
/// escape or backslash makes it reach another host than this names.
fn plain_host(url: &Url, web: &Web) -> Option<String> {
    let plain = url.scheme() == web.scheme
        && url.username().is_empty()
        && url.password().is_none()
        && url.port() == web.port;
    if !plain {
        return None;
    }
    url.host_str().map(str::to_ascii_lowercase)
}

/// Refuses `url` unless it is [`plain_host`]'s and its host is the forge
/// `host`, one under it, or one of GitHub's image hosts.
fn allowed(url: &Url, host: &str, web: &Web) -> Result<(), RpcError> {
    let forge = host.to_ascii_lowercase();
    let ours = plain_host(url, web).is_some_and(|to| {
        to == forge
            || (!forge.is_empty() && to.ends_with(&format!(".{forge}")))
            || to.ends_with(GITHUB_IMAGES)
            || to == GITHUB_ATTACHMENTS
    });
    if ours {
        Ok(())
    } else {
        Err(refused(format!(
            "The daemon fetches pictures over {} from {host}, the hosts under it and GitHub's image hosts alone, with no user or port.",
            web.scheme
        )))
    }
}

/// Whether a fetch of `url` sends the forge's token: only to the forge
/// `host` exactly, its case aside, as the forge's own pages would.
fn signs_in(url: &Url, host: &str, web: &Web) -> bool {
    plain_host(url, web).is_some_and(|to| to.eq_ignore_ascii_case(host))
}

/// `Bearer` and the token `gh auth token` prints for `host`, marked
/// sensitive; or, when `gh` fails, prints nothing, or takes past
/// [`GH_TOKEN_DEADLINE`], why the fetch goes unsigned. The token is never
/// logged.
async fn ask(
    gh: &Path,
    host: &str,
    environment: &ClientEnvironment,
) -> Result<HeaderValue, String> {
    let mut command = gh_command(gh, environment);
    command
        .args(["auth", "token"])
        .arg(format!("--hostname={host}"));
    let asked = tokio::time::timeout(GH_TOKEN_DEADLINE, supervised_output(&mut command)).await;
    let late = asked.is_err();
    let unsigned = match asked {
        Ok(Ok(output)) if output.status.success() => {
            let token = output.stdout.trim_ascii();
            if token.is_empty() {
                "gh auth token printed no token".to_owned()
            } else {
                let bearer = HeaderValue::from_bytes(&[b"Bearer ".as_slice(), token].concat());
                match bearer {
                    Ok(mut bearer) => {
                        bearer.set_sensitive(true);
                        return Ok(bearer);
                    }
                    Err(_) => "gh auth token printed what a header can't carry".to_owned(),
                }
            }
        }
        Ok(Ok(output)) => format!(
            "gh auth token failed: {}",
            gh_failure(&output.stderr, output.status).trim_end_matches('.')
        ),
        Ok(Err(error)) => format!("Couldn't run gh: {error}"),
        Err(_) => format!(
            "gh gave no token within {} s (GH_TOKEN_DEADLINE)",
            GH_TOKEN_DEADLINE.as_secs()
        ),
    };
    // The caller hears why when a signed hop fails; only a stuck keyring is
    // worth a warning each time.
    if late {
        tracing::warn!("a forge fetch goes unsigned: {unsigned}");
    } else {
        tracing::debug!("a forge fetch goes unsigned: {unsigned}");
    }
    Err(unsigned)
}

/// The client for `web`'s fetches, which follows no redirect itself
/// ([`follow`] checks each) and goes through the proxy the login's
/// environment names ([`proxy`]).
fn client(environment: &ClientEnvironment, web: &Web) -> Result<reqwest::Client, RpcError> {
    let mut builder = crate::web_client::no_redirect_builder()
        .no_proxy()
        .user_agent(concat!("rho/", env!("CARGO_PKG_VERSION")));
    if let Some(proxy) = proxy(environment)? {
        builder = builder.proxy(proxy);
    }
    for (name, address) in &web.resolve {
        builder = builder.resolve(name, *address);
    }
    builder.build().map_err(|error| {
        failed(format!(
            "Couldn't make the fetch's client: {}.",
            said(error)
        ))
    })
}

/// The proxy the login's environment names for https, as `curl`, which
/// rho-ui fetched with, reads it: `https_proxy`, else `all_proxy`, each
/// lowercase first, less the hosts `no_proxy` names. Every URL fetched is
/// https but a test's, so it proxies every scheme. One that isn't a URL, or
/// is a SOCKS proxy ([`SOCKS`]), fails the fetch, naming the variable,
/// rather than being passed by.
fn proxy(environment: &ClientEnvironment) -> Result<Option<Proxy>, RpcError> {
    let first = |names: [&'static str; 2]| {
        names.into_iter().find_map(|name| {
            let value = var(environment, name).filter(|value| !value.is_empty())?;
            Some((name, value))
        })
    };
    let Some((name, address)) =
        first(["https_proxy", "HTTPS_PROXY"]).or_else(|| first(["all_proxy", "ALL_PROXY"]))
    else {
        return Ok(None);
    };
    let scheme = address
        .split_once("://")
        .map(|(scheme, _)| scheme.to_ascii_lowercase());
    if let Some(scheme) = scheme.filter(|scheme| SOCKS.contains(&scheme.as_str())) {
        return Err(failed(format!(
            "The login's {name} names a {scheme} proxy, which the daemon can't fetch through: only an http or https one."
        )));
    }
    // Its error would quote the address, which may hold a password.
    let proxy = Proxy::all(address)
        .map_err(|_| failed(format!("The login's {name} isn't a proxy's URL.")))?;
    let bypass = first(["no_proxy", "NO_PROXY"]).and_then(|(_, hosts)| NoProxy::from_string(hosts));
    Ok(Some(proxy.no_proxy(bypass)))
}

/// How [`copy`] ended.
enum Ended {
    Done,
    /// The picture ran past the limit.
    Cut,
    Failed(String),
    /// The client closed the stream.
    Closed,
}

/// Streams the picture `response` carries to `writer`, up to `limit`
/// bytes, until `deadline`, past which the stream fails saying `late`.
async fn pump(
    mut response: Response,
    limit: u64,
    deadline: Instant,
    late: String,
    mut writer: HostStreamWriter,
) {
    let ended = tokio::time::timeout_at(deadline, copy(&mut response, limit, &mut writer)).await;
    match ended {
        Ok(Ended::Done) => writer.finish(),
        Ok(Ended::Cut) => {
            tracing::debug!(
                limit,
                "a forge fetch ran past its limit, so its stream ends truncated"
            );
            writer.truncate();
        }
        Ok(Ended::Failed(message)) => writer.fail(message),
        Ok(Ended::Closed) => {}
        Err(_) => writer.fail(late),
    }
}

/// Writes what `response` carries to `writer` as it comes, up to `limit`
/// bytes, until it ends or the client closes the stream.
async fn copy(response: &mut Response, limit: u64, writer: &mut HostStreamWriter) -> Ended {
    let mut room = limit;
    loop {
        let chunk = tokio::select! {
            chunk = response.chunk() => chunk,
            () = writer.closed() => return Ended::Closed,
        };
        let mut chunk = match chunk {
            Ok(Some(chunk)) => chunk,
            Ok(None) => return Ended::Done,
            Err(error) => return Ended::Failed(format!("{}.", said(error))),
        };
        let length = chunk.len() as u64;
        let over = length > room;
        if over {
            // Under `chunk.len()`, so it fits.
            chunk.truncate(room as usize);
        }
        room -= chunk.len() as u64;
        if !chunk.is_empty() && writer.write(chunk.into()).await.is_err() {
            return Ended::Closed;
        }
        if over {
            return Ended::Cut;
        }
    }
}

/// `url` as the daemon logs it: its scheme, host and path, never its
/// query, which may sign it, nor a user and password.
fn shown(url: &Url) -> String {
    format!(
        "{}://{}{}",
        url.scheme(),
        url.host_str().unwrap_or_default(),
        url.path()
    )
}

/// Why a request failed, for people: reqwest's words and their causes'
/// ([`with_causes`]), without the URL, whose query may sign it.
fn said(error: reqwest::Error) -> String {
    with_causes(&error.without_url())
}

/// A fetch that asking again won't change, for the reason `message` gives
/// people.
fn refused(message: String) -> RpcError {
    RpcError::new(ErrorCode::ForgeFetchRefused, message)
}

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