rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Private local endpoints of the daemon's own besides the one clients
//! reach: a socket file in a fresh 0700 directory, for what lasts one run
//! (one turn's served tools, see `acp_runtime::agent_tools::bridge`).
//!
//! The directory is in the system's temporary folder, not beside the run's
//! other files: a socket path must fit `sun_path` (107 bytes on Linux, 103
//! on macOS, see `rho_protocol`'s endpoint), and a daemon session's folder,
//! `<rho home>/sessions/<workspace slug>-<16 hex>/<time>_<uuid>/agent`, is
//! 104 bytes before the socket's own name already for workspace `/home/me/p`
//! in `/home/me/.rho`. `tempfile` makes it as the endpoint needs: under a
//! fresh name, with one non-recursive `mkdir` at mode 0700, which fails
//! rather than reuse or follow anything already at the path, so nobody
//! else made it.

use std::{
    ffi::{OsStr, OsString},
    fs, io,
    os::unix::fs::PermissionsExt,
    path::Path,
};

use tokio::net::{UnixListener, UnixStream};

use super::{endpoint::peer_is_owner, files::current_uid};

/// The listener's end of a connection.
pub(crate) type LocalAccepted = UnixStream;
/// The connecting end.
pub(crate) type LocalConnected = UnixStream;

/// A listening endpoint only this user can reach, removed as it drops.
pub(crate) struct LocalListener {
    socket: UnixListener,
    /// The 0700 directory that holds the socket, which only this listener
    /// uses, removed as it drops.
    _dir: tempfile::TempDir,
    uid: u32,
}

impl LocalListener {
    /// Listens on a new endpoint named after `prefix`, and returns it with
    /// the address [`connect_local`] reaches it at.
    pub(crate) fn bind_private(prefix: &str) -> io::Result<(Self, OsString)> {
        let dir = tempfile::Builder::new()
            .prefix(&format!("{prefix}-"))
            .permissions(fs::Permissions::from_mode(0o700))
            .tempdir()?;
        let path = dir.path().join("s");
        let socket = UnixListener::bind(&path)?;
        // The directory is 0700 already; 0600 keeps the socket private
        // should its mode ever be loosened.
        fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
        let listener = Self {
            socket,
            _dir: dir,
            uid: current_uid(),
        };
        Ok((listener, path.into_os_string()))
    }

    /// The next connection from this user. Cancel safe: a connection is
    /// either returned or still waiting in the backlog.
    pub(crate) async fn accept(&mut self) -> io::Result<LocalAccepted> {
        loop {
            let (stream, _) = self.socket.accept().await?;
            if peer_is_owner(&stream, self.uid) {
                return Ok(stream);
            }
        }
    }
}

/// Connects to the endpoint of a [`LocalListener`] at `address`, once it
/// proved to be this user's, so what the caller sends next, such as a
/// token, reaches no other user's listener.
pub(crate) async fn connect_local(address: &OsStr) -> io::Result<LocalConnected> {
    connect_owned_by(address, current_uid()).await
}

/// [`connect_local`], for an endpoint that must be `uid`'s.
async fn connect_owned_by(address: &OsStr, uid: u32) -> io::Result<LocalConnected> {
    let stream = UnixStream::connect(Path::new(address)).await?;
    if !peer_is_owner(&stream, uid) {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "{} is another user's endpoint",
                Path::new(address).display()
            ),
        ));
    }
    Ok(stream)
}

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