rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho/device/*`: the devices paired with the daemon's WebSocket bridge
//! (`docs/bridge.md`, "Pairing from a connected client"). Pairing mints a
//! one-time code in the credential store the daemon's config selects, which
//! the new device redeems on the bridge for a token of its own. Listing
//! reads the tokens and marks the devices connected now; revoking deletes
//! one.
//!
//! Each call is logged with who made it, never with the code it mints, and
//! a failure is logged with why, as a pairing that did not happen leaves
//! nothing else behind.

use std::{
    collections::{BTreeSet, HashMap},
    sync::Mutex,
};

use rho_protocol::{
    Caller, ConnectionId, DeviceListParams, DeviceListResponse, DevicePairParams,
    DevicePairResponse, DeviceRevokeParams, DeviceRevokeResponse, DeviceService, ErrorCode,
    RpcError,
};

use super::{
    auth::off_workers,
    jobs::unix_now,
    mcp_secrets::{open_store, store_error},
};
use crate::app::daemon_http::{
    device_pair::{self, PairRefused},
    devices,
    pairing_codes::DeviceName,
};

/// The daemon's answers to `rho/device/*`, which the machine hands out,
/// and the bridge devices with a connection open now.
#[derive(Default)]
pub(super) struct Devices {
    /// Each open connection the bridge opened, and the device it named.
    bridged: Mutex<HashMap<ConnectionId, String>>,
}

impl Devices {
    /// The devices with a connection open now.
    fn connected(&self) -> BTreeSet<String> {
        self.bridged
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .values()
            .cloned()
            .collect()
    }
}

impl DeviceService for Devices {
    fn bridged(&self, caller: &Caller) {
        if let Some(device) = caller.bridge_device() {
            self.bridged
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .insert(caller.connection, device.to_owned());
        }
    }

    fn left(&self, connection: ConnectionId) {
        self.bridged
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .remove(&connection);
    }

    async fn list(
        &self,
        caller: Caller,
        _: DeviceListParams,
    ) -> Result<DeviceListResponse, RpcError> {
        log_call(&caller, "listed the paired devices");
        let connected = self.connected();
        let listed = off_workers(move || {
            open_store()?;
            devices::list(&connected).map_err(store_error)
        })
        .await?;
        let listed = log_failure(&caller, "list the paired devices", listed)?;
        Ok(DeviceListResponse::new(
            listed,
            caller.bridge_device().map(str::to_owned),
        ))
    }

    async fn revoke(
        &self,
        caller: Caller,
        params: DeviceRevokeParams,
    ) -> Result<DeviceRevokeResponse, RpcError> {
        let DeviceRevokeParams { name, .. } = params;
        let device = name.clone();
        let revoked = off_workers(move || {
            open_store()?;
            devices::revoke(&name).map_err(store_error)
        })
        .await?;
        let revoked = log_failure(&caller, "revoke a device", revoked)?;
        tracing::info!(
            connection = ?caller.connection,
            client = ?caller.client.name,
            client_version = ?caller.client.version,
            by_device = ?caller.bridge_device(),
            device = %device,
            revoked,
            "revoked a paired device"
        );
        Ok(DeviceRevokeResponse::new(revoked))
    }

    async fn pair(
        &self,
        caller: Caller,
        params: DevicePairParams,
    ) -> Result<DevicePairResponse, RpcError> {
        let DevicePairParams { name, .. } = params;
        let chosen = name.is_some();
        let answer = mint(name).await;
        match &answer {
            Ok(_) => tracing::info!(
                connection = ?caller.connection,
                client = ?caller.client.name,
                client_version = ?caller.client.version,
                chosen_name = chosen,
                "minted a device pairing code"
            ),
            Err(error) => tracing::warn!(
                connection = ?caller.connection,
                client = ?caller.client.name,
                client_version = ?caller.client.version,
                code = error.code,
                why = %error.message,
                "could not mint a device pairing code"
            ),
        }
        answer
    }
}

/// Logs that `caller` asked for `what`.
fn log_call(caller: &Caller, what: &str) {
    tracing::info!(
        connection = ?caller.connection,
        client = ?caller.client.name,
        client_version = ?caller.client.version,
        by_device = ?caller.bridge_device(),
        "{what}"
    );
}

/// `answer`, logging why when `caller` could not `what`.
fn log_failure<T>(caller: &Caller, what: &str, answer: Result<T, RpcError>) -> Result<T, RpcError> {
    if let Err(error) = &answer {
        tracing::warn!(
            connection = ?caller.connection,
            code = error.code,
            why = %error.message,
            "could not {what}"
        );
    }
    answer
}

/// Mints a code for a device `name`d, or naming itself, in the store the
/// daemon's config selects now.
async fn mint(name: Option<String>) -> Result<DevicePairResponse, RpcError> {
    let name = match name {
        Some(name) => DeviceName::chosen(name)
            .map_err(|error| RpcError::new(ErrorCode::InvalidParams, format!("{error:#}")))?,
        None => DeviceName::FromDevice,
    };
    off_workers(move || {
        open_store()?;
        let paired = device_pair::pair(name, unix_now()).map_err(|refused| match refused {
            PairRefused::NoBridge(why) => RpcError::new(ErrorCode::BridgeNotSetUp, why),
            PairRefused::Failed(error) => store_error(error),
        })?;
        if paired.pruned > 0 {
            tracing::debug!(pruned = paired.pruned, "pruned expired pairing codes");
        }
        Ok(DevicePairResponse::new(
            paired.pairing.to_string(),
            paired.expires_at,
        ))
    })
    .await?
}