rho-coding-agent 3.13.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
482
483
484
485
486
487
488
489
490
491
//! `rho daemon bridge setup`, `pair` and `remove`: the one-time setup of a
//! machine rho-ui reaches over the WebSocket bridge. Setup leaves
//! `rho daemon serve --http` running as a service that survives reboots,
//! and prints a pairing string ([`rho_protocol::Pairing`]) once. Pair
//! prints one for another device, under a token of its own, from where
//! setup recorded clients reach the bridge. Remove undoes setup.
//!
//! Where the bridge listens ([`Listen`]):
//! - by default, on this machine's Tailscale or NetBird address, port
//!   [`DEFAULT_PORT`], allowing the overlay's DNS names as `Host`;
//! - `--http` names the address itself, which must be loopback or private;
//! - `--url wss://…` pairs through a TLS proxy in front of a loopback bind,
//!   the only way a public address is reached (`ws://` would carry the token
//!   over the internet in the clear).
//!
//! Re-running setup converges: the service is rewritten and restarted only
//! when what it runs changed, and the named token is rotated, since only its
//! hash is kept and a pairing string cannot be shown twice.

use std::{
    net::{IpAddr, Ipv4Addr, SocketAddr},
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

use anyhow::Context as _;
use rho_protocol::{BridgeToken, BridgeUrl, Pairing};
use rho_providers::credentials::CredentialStoreBackend;

use super::{
    cli::NO_SERVICE_MANAGER,
    server::RECHECK_INTERVAL,
    setup_overlay::{find_overlay, Overlay},
    setup_service::{self, Installed, PairWith, ServiceSpec},
    tokens::DaemonTokenSet,
};
use crate::{
    app::{
        config_repository::ConfigRepository,
        http_guard::{is_private, validate_name, AllowedHost},
        mcp_server::token_store,
    },
    cli::{BridgeSetupArgs, Cli},
    daemon::{ServiceFiles, ServiceManager},
};

/// The bridge's port when setup picks its address: the one `docs/daemon.md`
/// gives the bridge, beside `rho mcp serve --http`'s 8765.
const DEFAULT_PORT: u16 = 8766;

/// How long setup waits for the installed bridge to accept the new token.
//
// Tripwire. Measured on Linux under systemd 249, 4 runs with no daemon
// running: the whole setup, the service start, the daemon's start on the
// first upgrade and the probe included, took 1.22 to 2.72 s.
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);

const PROBE_INTERVAL: Duration = Duration::from_millis(200);

/// Where the bridge listens, as the flags ask, before any overlay is asked.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Listen {
    /// On this machine's overlay address, which setup finds.
    Overlay,
    /// On this loopback or private address, paired as `ws://` to it.
    Address(SocketAddr),
    /// On this loopback address, behind a TLS proxy at `url`, whose `host`
    /// is allowed.
    Proxy {
        url: BridgeUrl,
        host: String,
        listen: SocketAddr,
    },
}

impl Listen {
    /// Reads the flags, refusing what would carry the token over the
    /// internet in the clear or leave a proxy nothing to reach.
    pub(super) fn of(args: &BridgeSetupArgs) -> anyhow::Result<Self> {
        match (&args.url, args.http) {
            (Some(url), http) => {
                let url: BridgeUrl = url.parse().context("--url")?;
                if !url.is_secure() {
                    anyhow::bail!(
                        "--url {url} must be wss://: a bridge reached through a proxy carries its token over TLS; for an overlay or LAN address use --http"
                    );
                }
                let host = url::Url::parse(url.as_str())?
                    .host_str()
                    .map(|host| host.trim_matches(['[', ']']).to_owned())
                    .context("--url has no host")?;
                let listen = http.unwrap_or(SocketAddr::from((Ipv4Addr::LOCALHOST, DEFAULT_PORT)));
                if !listen.ip().is_loopback() {
                    anyhow::bail!(
                        "--http {listen} with --url: bind loopback, such as 127.0.0.1:{DEFAULT_PORT}, for the proxy to reach"
                    );
                }
                Ok(Self::Proxy { url, host, listen })
            }
            (None, Some(listen)) if !is_private(listen.ip()) => anyhow::bail!(
                "--http {listen} is not a loopback or private address: a public address needs TLS, so bind 127.0.0.1:{DEFAULT_PORT} behind a TLS proxy and pass its address as --url wss://…"
            ),
            (None, Some(listen)) => Ok(Self::Address(listen)),
            (None, None) => Ok(Self::Overlay),
        }
    }

    /// Whether [`plan`] reads the overlay: for its address, or for the
    /// names of an address that may be the overlay's.
    pub(super) fn wants_overlay(&self) -> bool {
        match self {
            Self::Overlay => true,
            Self::Address(listen) => !listen.ip().is_loopback(),
            Self::Proxy { .. } => false,
        }
    }
}

/// Where the bridge listens and how clients reach it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Plan {
    pub(super) listen: SocketAddr,
    pub(super) allow_hosts: Vec<String>,
    pub(super) url: BridgeUrl,
}

/// Decides where the bridge listens. `overlay` is what finding this
/// machine's overlay gave, present exactly when `listen` wants it, and
/// `extra_hosts` are `--allow-host`'s.
pub(super) fn plan(
    listen: Listen,
    overlay: Option<Result<Overlay, String>>,
    extra_hosts: &[String],
) -> anyhow::Result<Plan> {
    let (listen, mut allow_hosts, url) = match listen {
        Listen::Proxy { url, host, listen } => (listen, vec![host], url),
        Listen::Address(listen) => {
            let names = overlay
                .and_then(Result::ok)
                .filter(|found| IpAddr::V4(found.ip) == listen.ip())
                .map(|found| found.names())
                .unwrap_or_default();
            (listen, names, ws_url(listen)?)
        }
        Listen::Overlay => {
            let found = overlay
                .unwrap_or_else(|| Err("not asked".to_owned()))
                .map_err(|why| {
                    anyhow::anyhow!(
                        "found no Tailscale or NetBird address for the bridge ({why}); pass --http with this machine's private address, such as 192.168.1.20:{DEFAULT_PORT}, or --url wss://… for a TLS proxy"
                    )
                })?;
            let listen = SocketAddr::from((found.ip, DEFAULT_PORT));
            (listen, found.names(), ws_url(listen)?)
        }
    };
    for host in extra_hosts {
        if !allow_hosts.contains(host) {
            allow_hosts.push(host.clone());
        }
    }
    for host in &allow_hosts {
        AllowedHost::parse(host)?;
    }
    Ok(Plan {
        listen,
        allow_hosts,
        url,
    })
}

fn ws_url(listen: SocketAddr) -> anyhow::Result<BridgeUrl> {
    Ok(format!("ws://{listen}/ws").parse()?)
}

/// The service arguments that run the bridge as `plan` says.
pub(super) fn serve_args(plan: &Plan) -> Vec<String> {
    let mut args = vec![
        "daemon".to_owned(),
        "serve".to_owned(),
        "--http".to_owned(),
        plan.listen.to_string(),
    ];
    for host in &plan.allow_hosts {
        args.extend(["--allow-host".to_owned(), host.clone()]);
    }
    args
}

/// The service manager setup installs the bridge under on this OS.
fn this_manager() -> anyhow::Result<ServiceManager> {
    if cfg!(target_os = "linux") {
        Ok(ServiceManager::Systemd)
    } else if cfg!(target_os = "macos") {
        Ok(ServiceManager::Launchd)
    } else {
        anyhow::bail!("{NO_SERVICE_MANAGER}")
    }
}

/// The `rho` the service runs: as this command was started, so a service
/// keeps following a symlink an update moves, rather than the file it
/// pointed to.
fn installed_rho() -> anyhow::Result<PathBuf> {
    let started = std::env::args_os().next().map(PathBuf::from);
    // A bare name ran from the PATH, so find it there as the shell did.
    if let Some(found) = started
        .filter(|name| name.components().count() == 1)
        .and_then(|name| which::which(name).ok())
    {
        return Ok(found);
    }
    crate::daemon::started_path().context("could not find the rho executable")
}

/// The variables the service runs with: this shell's `PATH`, which the
/// sessions it starts look tools up on, and which rho home and credential
/// store it serves.
fn service_environment() -> Vec<(String, String)> {
    ["PATH", "RHO_HOME", "RHO_CREDENTIAL_STORE"]
        .into_iter()
        .filter_map(|name| Some((name.to_owned(), std::env::var(name).ok()?)))
        .collect()
}

/// The bridge's service on this OS, saved or not, and the home it is in.
pub(super) fn bridge_service() -> anyhow::Result<(ServiceFiles, PathBuf)> {
    let manager = this_manager()?;
    let home = crate::paths::home_dir().context("could not determine the home directory")?;
    let xdg_config_home = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
    let service = ServiceFiles::daemon_http(manager, &home, xdg_config_home.as_deref());
    Ok((service, home))
}

/// `rho daemon bridge setup`.
pub(crate) async fn setup(args: &BridgeSetupArgs, cli: &Cli) -> anyhow::Result<()> {
    let (service, home) = bridge_service()?;
    validate_name("token", &args.token)?;
    let listen = Listen::of(args)?;
    let overlay = if listen.wants_overlay() {
        Some(find_overlay().await)
    } else {
        None
    };
    let plan = plan(listen, overlay, &args.allow_host)?;
    ConfigRepository::new(cli.config.clone()).open_credential_store()?;
    if service.manager == ServiceManager::Systemd
        && crate::credential_store::configured_backend()? == CredentialStoreBackend::Os
    {
        // The bridge reads its tokens per connection, and the Secret
        // Service's login keyring stays locked until a desktop login.
        eprintln!(
            "the bridge's tokens are in the OS keyring, which stays locked after a reboot until you log in to the desktop; for a bridge that answers from boot, run `rho credential-store set file` and set it up again"
        );
    }
    // The service reads the config this command did, for the same store.
    let config = match &cli.config {
        Some(path) => vec![
            "--config".to_owned(),
            std::path::absolute(path)?
                .to_str()
                .context("--config is not UTF-8")?
                .to_owned(),
        ],
        None => Vec::new(),
    };
    let spec = ServiceSpec {
        program: installed_rho()?,
        args: config.into_iter().chain(serve_args(&plan)).collect(),
        environment: service_environment(),
        pair_with: PairWith {
            url: plan.url.clone(),
            listen: plan.listen,
        },
    };
    let text = setup_service::render(&service, &spec, &home)?;
    install(&service, &text, plan.listen)?;
    if service.manager == ServiceManager::Systemd {
        match crate::daemon::keep_user_services_running() {
            Ok(true) => {}
            Ok(false) => eprintln!(
                "turned on systemd linger for this user, so the bridge starts at boot and keeps running after logout"
            ),
            Err(error) => eprintln!(
                "could not turn on systemd linger, so the bridge stops when you log out and waits for a login after a reboot: {error}; run `sudo loginctl enable-linger $USER`"
            ),
        }
    }
    issue_pairing(
        &service,
        &home,
        &spec.pair_with,
        &args.token,
        "rho daemon bridge setup",
    )
    .await?;
    eprintln!(
        "the bridge serves {} as {}; paste the line above in rho-ui. It holds token {:?} and is shown only this once: running setup again replaces it.",
        plan.url, service.unit, args.token
    );
    Ok(())
}

/// Gives token `name` a new secret, checks the bridge `target` accepts it,
/// and prints its pairing string, alone on stdout so a script can capture
/// it. `again` is the command to run again if the bridge does not.
async fn issue_pairing(
    service: &ServiceFiles,
    home: &Path,
    target: &PairWith,
    name: &str,
    again: &str,
) -> anyhow::Result<()> {
    let (rotated, token) = token_store::update(|tokens: &mut DaemonTokenSet| {
        Ok((tokens.contains(name), tokens.rotate(name)?))
    })?;
    if rotated {
        eprintln!(
            "rotated token {name:?}: the device it paired before stops reaching the bridge within {} s",
            RECHECK_INTERVAL.as_secs()
        );
    }
    probe(target.listen, &token).await.with_context(|| {
        let earlier = if rotated {
            format!(", and token {name:?}'s earlier pairing no longer works")
        } else {
            String::new()
        };
        format!(
            "the bridge did not accept the new token on {}{earlier}. See {}; a bridge set up with another RHO_HOME, RHO_CREDENTIAL_STORE or --config reads another store, so run `{again}` with the same",
            target.listen,
            setup_service::log_location(service, home)
        )
    })?;
    let machine = gethostname::gethostname().to_string_lossy().into_owned();
    let machine = machine.split('.').next().unwrap_or_default().to_owned();
    println!("{}", Pairing::new(target.url.clone(), token, machine));
    Ok(())
}

/// How long pair waits for the bridge to take a TCP connection before it
/// rotates anything.
//
// Tripwire. The bridge listens on this machine's own address: measured 5
// connects to it, open and closed ports alike, each answered in under 10 ms.
const LISTENING_TIMEOUT: Duration = Duration::from_secs(5);

/// `rho daemon bridge pair`: pairs device `name` with the bridge setup
/// installed, leaving the service as it is.
pub(crate) async fn pair(name: &str, cli: &Cli) -> anyhow::Result<()> {
    let (service, home) = bridge_service()?;
    validate_name("token", name)?;
    let target = Installed::of(&service)?.pair_with()?;
    // A token rotated for a bridge that is down cuts its device off for
    // nothing.
    match tokio::time::timeout(LISTENING_TIMEOUT, tokio::net::TcpStream::connect(target.listen)).await {
        Ok(Ok(_)) => {}
        Ok(Err(error)) => anyhow::bail!(
            "the bridge does not answer on {}: {error}; start it with {}",
            target.listen,
            setup_service::start_command(&service)
        ),
        Err(_) => anyhow::bail!(
            "the bridge did not answer on {} within LISTENING_TIMEOUT ({LISTENING_TIMEOUT:?}); start it with {}",
            target.listen,
            setup_service::start_command(&service)
        ),
    }
    ConfigRepository::new(cli.config.clone()).open_credential_store()?;
    issue_pairing(&service, &home, &target, name, "rho daemon bridge pair").await?;
    eprintln!(
        "paired {name:?} with the bridge at {}; paste the line above in rho-ui on that device. It is shown only this once: running pair again with this name replaces it.",
        target.url
    );
    Ok(())
}

/// Leaves `service` running `text`. An unchanged definition is only
/// started; a changed one replaces the old once `listen` is known free,
/// and the old one keeps running when it is not.
fn install(service: &ServiceFiles, text: &str, listen: SocketAddr) -> anyhow::Result<()> {
    let replaced = match Installed::of(service)? {
        Installed::ByHand => anyhow::bail!(
            "{} was saved by hand, so setup leaves it alone; move it aside to let setup manage the bridge",
            service.definition.display()
        ),
        Installed::BySetup(installed) if installed == text => return Ok(service.start()?),
        Installed::BySetup(_) => true,
        Installed::Absent => false,
    };
    if replaced {
        // Not loaded, as after a reboot without linger, is no error.
        let _ = service.stop();
    }
    if let Err(error) = std::net::TcpListener::bind(listen) {
        if replaced {
            let _ = service.start();
        }
        return Err(error).with_context(|| {
            format!("could not listen on {listen}; pass --http with a free port")
        });
    }
    service
        .install(text)
        .with_context(|| format!("could not install {}", service.definition.display()))
}

/// Opens a WebSocket on the bridge at `listen` with `token`, retrying until
/// it upgrades or [`PROBE_TIMEOUT`] passes, and returns the last refusal.
async fn probe(listen: SocketAddr, token: &BridgeToken) -> anyhow::Result<()> {
    use tokio_tungstenite::tungstenite::{client::IntoClientRequest, http::HeaderValue};

    let started = Instant::now();
    loop {
        let mut request = format!("ws://{listen}/ws").into_client_request()?;
        request.headers_mut().insert(
            "authorization",
            HeaderValue::from_str(&format!("Bearer {}", token.secret()))?,
        );
        let error = match tokio_tungstenite::connect_async(request).await {
            Ok((mut socket, _)) => {
                let _ = socket.close(None).await;
                return Ok(());
            }
            Err(error) => error,
        };
        let waited = started.elapsed();
        if waited >= PROBE_TIMEOUT {
            anyhow::bail!("{error} (PROBE_TIMEOUT {PROBE_TIMEOUT:?}; waited {waited:?})");
        }
        tokio::time::sleep(PROBE_INTERVAL).await;
    }
}

/// `rho daemon bridge remove`: stops and deletes the bridge's service and
/// revokes `token`. What is already gone is no error.
pub(crate) fn remove(token: &str, cli: &Cli) -> anyhow::Result<()> {
    let (service, _home) = bridge_service()?;
    ConfigRepository::new(cli.config.clone()).open_credential_store()?;
    let installed = match Installed::of(&service)? {
        Installed::ByHand => {
            eprintln!(
                "left {}: it was saved by hand, not by setup",
                service.definition.display()
            );
            false
        }
        Installed::BySetup(_) => true,
        Installed::Absent => false,
    };
    if installed {
        if let Err(error) = service.stop() {
            eprintln!("could not stop {}: {error}", service.unit);
        }
        service.delete()?;
        if let Err(error) = service.forget() {
            eprintln!(
                "could not have the service manager forget {}: {error}",
                service.unit
            );
        }
        println!("removed {}", service.unit);
    }
    let (revoked, left) = token_store::update(|tokens: &mut DaemonTokenSet| {
        let revoked = tokens.revoke(token);
        let left: Vec<String> = tokens
            .tokens
            .iter()
            .map(|token| token.name.clone())
            .collect();
        Ok((revoked, left))
    })?;
    if revoked {
        println!("revoked daemon token {token:?}");
    }
    if !installed && !revoked {
        println!("no bridge service or daemon token {token:?} to remove");
    }
    // Other devices' tokens are left: a bridge run by hand may use them.
    if !left.is_empty() {
        println!(
            "daemon tokens still valid: {}; unpair each with `rho daemon token revoke <name>`",
            left.join(", ")
        );
    }
    Ok(())
}

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