rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! One-time pairing codes (`rho/device/pair`), kept in rho's credential
//! store under an account of their own, apart from the bridge's tokens
//! ([`super::tokens`]).
//!
//! A code is 128 random bits, kept only as its SHA-256, good once and for
//! [`PAIRING_CODE_TTL_SECS`]. Being that long, it needs no limit on
//! attempts. The set is pruned of expired codes whenever it changes, so it
//! holds at most the codes of the last few minutes.
//!
//! The time is always passed in, as Unix seconds, so tests run on a clock
//! of their own.

use anyhow::Context as _;
use rho_protocol::{PairingCode, PAIRING_CODE_TTL_SECS};
use serde::{Deserialize, Serialize};

use crate::app::{
    http_guard::{sha256_hex, validate_name},
    mcp_server::token_store::StoredSet,
};

/// Credential-store account for pairing codes.
const ACCOUNT: &str = "daemon-pairing-codes";

/// Cross-process lock file for pairing code updates. Its own, not the
/// tokens': a redeem takes the code, which dies whatever follows, before
/// it gives the device a token.
const LOCK_FILE: &str = ".rho-daemon-pairing-codes.lock";

/// Random bytes in a code: 128 bits.
const CODE_BYTES: usize = 16;

/// Every pairing code not yet redeemed or pruned.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct PairingCodeSet {
    codes: Vec<PairingCodeRecord>,
}

/// One pairing code: the hex SHA-256 of its secret, the name it gives the
/// device's token if one was chosen, and when it expires.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct PairingCodeRecord {
    sha256: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    /// Unix seconds; the code is good while the time is before it.
    expires_at: u64,
}

impl StoredSet for PairingCodeSet {
    const ACCOUNT: &'static str = ACCOUNT;
    const WHAT: &'static str = "daemon pairing codes";
    const LOCK_FILE: &'static str = LOCK_FILE;
    const GUARDED: &'static str = "daemon pairing codes";
}

/// What the token of the device a code pairs is named.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DeviceName {
    /// The name the pairing chose ([`Self::chosen`]): a token of that name
    /// is replaced once the code is redeemed, as `rho daemon bridge pair`
    /// replaces one, never before.
    Chosen(String),
    /// The device names itself when it redeems the code, and a name
    /// another device holds gets a suffix: it never replaces a token.
    FromDevice,
}

impl DeviceName {
    /// `name`, chosen at pairing, once it is one `rho daemon token` takes.
    pub(crate) fn chosen(name: String) -> anyhow::Result<Self> {
        validate_name("device", &name)?;
        Ok(Self::Chosen(name))
    }
}

/// A code just minted, shown once.
#[derive(Debug)]
pub(crate) struct MintedCode {
    pub(crate) code: PairingCode,
    /// Unix seconds after which the code is no longer good.
    pub(crate) expires_at: u64,
    /// How many expired codes the mint pruned.
    pub(crate) pruned: usize,
}

/// Why a presented code pairs nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum CodeRefused {
    /// No code has that secret: it was never minted, was already
    /// redeemed, or expired and was pruned.
    #[error("the pairing code is not one this machine issued, or it was already used")]
    Unknown,
    /// The code expired before it was presented.
    #[error("the pairing code expired; pair the device again")]
    Expired,
}

impl PairingCodeSet {
    /// Mints a code that pairs the device as `name` says until
    /// [`PAIRING_CODE_TTL_SECS`] after `now`, pruning the expired ones.
    pub(crate) fn mint(&mut self, name: DeviceName, now: u64) -> anyhow::Result<MintedCode> {
        let name = match name {
            DeviceName::Chosen(name) => Some(name),
            DeviceName::FromDevice => None,
        };
        let pruned = self.prune(now);
        let code: PairingCode = format!(
            "{}{}",
            PairingCode::PREFIX,
            crate::secrets::random_hex::<CODE_BYTES>()
        )
        .parse()
        .context("minted a pairing code clients would refuse")?;
        let expires_at = now + PAIRING_CODE_TTL_SECS;
        self.codes.push(PairingCodeRecord {
            sha256: sha256_hex(code.secret()),
            name,
            expires_at,
        });
        Ok(MintedCode {
            code,
            expires_at,
            pruned,
        })
    }

    /// Takes the code whose secret is `presented`, at `now`: the seam
    /// `POST /pair` redeems through. The code is gone afterwards, whether
    /// it was good or expired, and so are the other expired ones. The
    /// secret is compared with every code's in constant time, so the time
    /// taken does not tell which matched.
    pub(crate) fn take(&mut self, presented: &str, now: u64) -> Result<DeviceName, CodeRefused> {
        let presented = sha256_hex(presented);
        let found = self
            .codes
            .iter()
            .enumerate()
            .fold(None, |found, (index, code)| {
                if crate::secrets::constant_time_eq(code.sha256.as_bytes(), presented.as_bytes()) {
                    Some(index)
                } else {
                    found
                }
            });
        let taken = found.map(|index| self.codes.remove(index));
        self.prune(now);
        let taken = taken.ok_or(CodeRefused::Unknown)?;
        if now >= taken.expires_at {
            return Err(CodeRefused::Expired);
        }
        Ok(taken
            .name
            .map_or(DeviceName::FromDevice, DeviceName::Chosen))
    }

    /// Removes the codes expired at `now`; returns how many.
    fn prune(&mut self, now: u64) -> usize {
        let before = self.codes.len();
        self.codes.retain(|code| now < code.expires_at);
        before - self.codes.len()
    }
}

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