rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `POST /pair`: a new device redeems the one-time code `rho/device/pair`
//! minted ([`PairingCodeSet`]) for a bridge token of its own. It has no
//! token yet, so this is the one request the bridge serves without one,
//! after the same `Host` and `Origin` checks as `GET /ws`.
//!
//! The code dies on its first use, whatever the answer: it is taken from
//! the store, and that saved, before the device's token is minted. Being
//! 128 random bits, it needs no limit on attempts; each refusal is logged
//! with the peer's address, never with the code. The answer carries the
//! token, so it is marked `Cache-Control: no-store` and never logged.

use std::{net::SocketAddr, time::SystemTime};

use bytes::Bytes;
use http_body_util::{BodyExt, Full, Limited};
use hyper::{body::Incoming, header, Method, Request, Response, StatusCode};
use rho_protocol::{PairRequest, PairResponse};

use super::{
    pairing_codes::{CodeRefused, DeviceName, PairingCodeSet},
    server::{refusal, Body, TokenLoader},
    tokens::DaemonTokenSet,
};
use crate::app::mcp_server::token_store;

/// The path a device redeems its code at, beside [`super::server::ENDPOINT`].
pub(super) const PAIR_ENDPOINT: &str = "/pair";

/// The most a redeem's body may hold: a code, a name and a platform.
const MAX_BODY_BYTES: usize = 4 * 1024;

/// The longest token name, as `rho daemon token` takes one.
const NAME_MAX: usize = 64;

/// The longest platform kept, such as `ios`.
const PLATFORM_MAX: usize = 32;

/// What a device that names itself is called when its name keeps nothing.
const FALLBACK_NAME: &str = "device";

/// Why a code paired no device.
#[derive(Debug)]
pub(super) enum RedeemRefused {
    /// The code is not one to redeem now.
    Code(CodeRefused),
    /// Reading or saving the codes or the tokens failed.
    Failed(anyhow::Error),
}

/// Takes `code` from the store at `now`, then gives the device it pairs a
/// token, in the credential store rho opened: the production redeem.
pub(super) async fn redeem_in_store(
    code: String,
    device_name: String,
    platform: Option<String>,
) -> Result<PairResponse, RedeemRefused> {
    tokio::task::spawn_blocking(move || {
        let now = unix_now();
        // Saved whatever `take` answers, so the code is spent either way.
        let name = token_store::update(|codes: &mut PairingCodeSet| Ok(codes.take(&code, now)))
            .map_err(RedeemRefused::Failed)?
            .map_err(RedeemRefused::Code)?;
        token_store::update(|tokens: &mut DaemonTokenSet| {
            pair_device(tokens, name, &device_name, platform)
        })
        .map_err(RedeemRefused::Failed)
    })
    .await
    .map_err(|error| RedeemRefused::Failed(error.into()))?
}

/// Mints the token of the device a code pairs, as `rho daemon token rotate`
/// mints one, recording when, and the `platform` the device said it runs.
/// A name the pairing chose is rotated, replacing the device that held it.
/// A device that names itself gets `device_name`, made a token name, with a
/// suffix when another device holds it.
pub(super) fn pair_device(
    tokens: &mut DaemonTokenSet,
    name: DeviceName,
    device_name: &str,
    platform: Option<String>,
) -> anyhow::Result<PairResponse> {
    let name = match name {
        DeviceName::Chosen(name) => name,
        DeviceName::FromDevice => unclaimed(&token_name(device_name), tokens),
    };
    let token = tokens.rotate(&name)?;
    tokens.set_platform(&name, platform);
    Ok(PairResponse::new(token.secret(), name))
}

/// `device_name` as a token name: letters, digits, `-` and `_` kept, a run
/// of anything else between them made one `-`, and at most [`NAME_MAX`]
/// long; [`FALLBACK_NAME`] when nothing is left. "Matthew's iPhone" is
/// `Matthews-iPhone`.
fn token_name(device_name: &str) -> String {
    let mut name = String::new();
    let mut gap = false;
    for character in device_name.chars() {
        if character.is_ascii_alphanumeric() || character == '_' {
            if gap && !name.is_empty() {
                name.push('-');
            }
            gap = false;
            name.push(character);
        } else if character == '-' || character.is_whitespace() || character == '.' {
            gap = true;
        }
        // Anything else, such as an apostrophe or an emoji, is dropped
        // without parting the words around it.
    }
    name.truncate(NAME_MAX);
    let name = name.trim_end_matches('-');
    if name.is_empty() {
        FALLBACK_NAME.to_owned()
    } else {
        name.to_owned()
    }
}

/// `base`, or, when a token holds it, the first of `base-2`, `base-3`, …
/// none holds, shortened to stay within [`NAME_MAX`].
fn unclaimed(base: &str, tokens: &DaemonTokenSet) -> String {
    if !tokens.contains(base) {
        return base.to_owned();
    }
    (2_u32..)
        .map(|number| {
            let suffix = format!("-{number}");
            let stem = &base[..base.len().min(NAME_MAX - suffix.len())];
            format!("{stem}{suffix}")
        })
        .find(|name| !tokens.contains(name))
        .expect("some suffix is free")
}

/// What a device says it runs, kept to [`PLATFORM_MAX`] ASCII letters,
/// digits, `-`, `_` and `.`, for its token's record and the log; `None`
/// when nothing is left.
fn platform(raw: Option<&str>) -> Option<String> {
    let platform: String = raw?
        .chars()
        .filter(|character| {
            character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
        })
        .take(PLATFORM_MAX)
        .collect();
    (!platform.is_empty()).then_some(platform)
}

/// Answers `POST /pair` from `peer`, whose `Host` and `Origin` passed,
/// redeeming through `tokens`.
pub(super) async fn serve(
    tokens: &impl TokenLoader,
    request: Request<Incoming>,
    peer: SocketAddr,
) -> Response<Body> {
    let refused = |status: StatusCode, reason: &str| {
        eprintln!("rho daemon serve: refused a pairing from {peer}: {reason}");
        no_store(refusal(status, reason))
    };
    if request.method() != Method::POST {
        let mut response = refused(StatusCode::METHOD_NOT_ALLOWED, "method not allowed");
        response
            .headers_mut()
            .insert(header::ALLOW, header::HeaderValue::from_static("POST"));
        return response;
    }
    if !is_json(&request) {
        return refused(
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "send the pairing as application/json",
        );
    }
    let Ok(body) = Limited::new(request.into_body(), MAX_BODY_BYTES)
        .collect()
        .await
    else {
        return refused(
            StatusCode::BAD_REQUEST,
            "the pairing's body could not be read, or is over 4 KiB",
        );
    };
    let Ok(pair) = serde_json::from_slice::<PairRequest>(&body.to_bytes()) else {
        return refused(
            StatusCode::BAD_REQUEST,
            "the pairing is not {code, device_name, platform}",
        );
    };
    let platform = platform(pair.platform.as_deref());
    let device_name = pair.device_name.clone();
    match tokens
        .redeem(pair.code, pair.device_name, platform.clone())
        .await
    {
        Ok(paired) => {
            eprintln!(
                "rho daemon serve: paired device {:?} ({device_name:?}, platform {platform:?}) from {peer}",
                paired.name
            );
            let body = serde_json::to_vec(&paired).expect("two strings encode");
            let mut response = Response::new(Full::new(Bytes::from(body)).boxed());
            response.headers_mut().insert(
                header::CONTENT_TYPE,
                header::HeaderValue::from_static("application/json"),
            );
            no_store(response)
        }
        Err(RedeemRefused::Code(why @ CodeRefused::Unknown)) => {
            refused(StatusCode::FORBIDDEN, &why.to_string())
        }
        Err(RedeemRefused::Code(why @ CodeRefused::Expired)) => {
            refused(StatusCode::GONE, &why.to_string())
        }
        Err(RedeemRefused::Failed(error)) => {
            eprintln!("rho daemon serve: could not pair a device from {peer}: {error:#}");
            no_store(refusal(
                StatusCode::INTERNAL_SERVER_ERROR,
                "could not pair the device; the bridge's log says why",
            ))
        }
    }
}

/// Whether `request` says its body is JSON. Requiring it keeps a browser
/// from sending one without asking first, as a form cannot.
fn is_json<B>(request: &Request<B>) -> bool {
    request
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.split(';').next())
        .is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json"))
}

/// `response`, which no cache may keep.
fn no_store(mut response: Response<Body>) -> Response<Body> {
    response.headers_mut().insert(
        header::CACHE_CONTROL,
        header::HeaderValue::from_static("no-store"),
    );
    response
}

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs())
        .unwrap_or_default()
}

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