Cotton code
175 lines · 7.6 KB · RustRaw
//! `devices.*` — this phone as the APPROVING device.//!//! ## Why this family is not `pairing.*`//!//! Design P15 says the pairing mechanism is "already Rust … the FFI's `connect.*`//! and `pairing.*`". **That is stale for the phone, and the code wins**//! ([feedback-should-be-a-primitive-weigh-it-by-who-said-it-and-how-m]).//! The local Mac approves ordinary household devices in process. The shared//! `pairing.pending` and `pairing.approve` methods use this//! transport on a remote owner device, or the membership claim routes for an//! invite-held database administered by another person.//!//! A phone holds no registry. Its joining half is `join.*` — landed in 4b — and//! its APPROVING half is this family: the same seven questions, asked of the//! server over HTTP. The two are different route sets and must never be merged.//!//! ## The rule this module exists to keep//!//! **The joining KEY is never on the wire. The digits are, and that changed.**//!//! They used to be a secret the approver typed off the joining phone's screen,//! so a pending list that carried them would have handed the second factor to//! whoever could read the list. They are not a secret any more: the server//! derives them from the joining key and the pairing id and gives the same six//! to everybody who has a right to the question — the joining screen, this//! list, the push. Knowing them proves nothing; **seeing the same ones is the//! whole of the second factor**, and a row that withheld the number would leave//! the screen with nothing to ask (*"Does it show 482 913?"*).//!//! ## The second verb//!//! `devices.revoke` carries `erase`, and it is the same route either way://! *Remove* takes a device out, *Remove and erase* also tells it to wipe//! itself the next time it reaches any of the person's devices. See the arm.//!//! The digits still travel up in the approve body, as an ECHO: not a proof of//! who is asking, but a proof of WHICH request the person was looking at. A//! queue that moved between the draw and the tap refuses rather than admitting//! the wrong device (`devices/pairing.rs`).use cotton_client::transport::ServerFetch;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::owner;/// The method names this module answers.pub const METHODS: [&str; 6] = [    "devices.approvePending",    "devices.declinePending",    "devices.list",    "devices.pending",    "devices.rename",    "devices.revoke",];/// How many digits the second factor is.////// The server's own `digits_of` takes six ASCII numerals and nothing else./// Checked here as well — not for a keypad any more, since nobody types these,/// but as an ECHO GUARD: `devices.approvePending` sends back the digits the ROW/// showed, and a caller that sent something else is a screen that lost track of/// which request the person was looking at. Refusing here says so in a sentence/// rather than spending a round trip on the server's `bad_digits`.const DIGITS: usize = 6;/// `devices.*` — dispatch, with this device's signed transport.pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    // No Mac holds a pairing queue: nobody can be waiting, and that is a    // state, never a failure (rigbyfix-c).    if method == "devices.pending" {        return Err(super::database_calls::not_served(method));    }    let answer = super::database_calls::with_fetch(handle, request, |fetch| over(fetch, method, request))?;    if method == "devices.revoke" { handle.client().wake_sync_loop(); }    Ok(answer)}/// The same, over a NAMED transport.////// The split is what makes every method here testable: a suite drives a/// scripted [`ServerFetch`] and asserts the request that actually went out —/// the verb, the path and the body bytes — and the answer or refusal that came/// back. A `CottonHandle` would drag a data directory, a runtime and a device/// key into a test about one route's shape.pub fn over(fetch: &dyn ServerFetch, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        // The approved list, whole. `{ devices, thisDevice }` — `thisDevice` is        // the server's own answer to "which of these am I", and the list screen        // marks the row with it rather than comparing ids in the app.        "devices.list" => owner::send(            fetch,            cotton_client::transport::ClientRequest::get("/v1/devices/approved"),        ),        "devices.approvePending" => {            let pairing_id = owner::text(request, "pairingId")?;            let digits = digits(request)?;            owner::send(                fetch,                owner::post(                    format!(                        "/v1/devices/pending/{}/approve",                        owner::segment(&pairing_id)                    ),                    &json!({ "digits": digits }),                ),            )        }        // An EMPTY OBJECT, not an absent body: the signature is over the bytes        // as sent (`owner::post`).        "devices.declinePending" => {            let pairing_id = owner::text(request, "pairingId")?;            owner::send(                fetch,                owner::post(                    format!(                        "/v1/devices/pending/{}/decline",                        owner::segment(&pairing_id)                    ),                    &json!({}),                ),            )        }        // **Two verbs on one route.** `{erase: false}` is *Remove* — the        // device is out and whatever it holds is its own. `{erase: true}` is        // *Remove and erase*: the row is filed with `revoked_reason =        // "erased"`, and the chokepoint's `403 device_revoked` then carries        // `erase: true`, so the first request that device makes is the one        // that tells it to wipe itself.        //        // The flag is ALWAYS spelled, never omitted for the ordinary case: the        // server's `erase_asked` reads every shape but a literal `{"erase":        // true}` as an ordinary revocation, and a body that says `false` out        // loud is a body a person reading the wire can tell apart from one that        // forgot to ask.        "devices.revoke" => {            let device_id = owner::text(request, "deviceId")?;            let answer = fetch.remove_device(&device_id, owner::flag(request, "erase"), owner::optional_text(request, "database").as_deref()).map_err(owner::refused)?;            if answer.body.iter().all(u8::is_ascii_whitespace) { Ok(Value::Null) } else { answer.json().map_err(owner::refused) }        }        "devices.rename" => {            let device_id = owner::text(request, "deviceId")?;            let name = owner::text(request, "name")?;            owner::send(                fetch,                owner::patch(                    format!("/v1/devices/approved/{}", owner::segment(&device_id)),                    &json!({ "name": name }),                ),            )        }        other => Err(MethodError::new(            "unknown_method",            format!("`{other}` is not a devices method"),        )),    }}/// The six digits, as the approving person typed them.fn digits(request: &Value) -> Result<String, MethodError> {    let echoed = owner::text(request, "digits")?;    if echoed.len() != DIGITS || !echoed.bytes().all(|byte| byte.is_ascii_digit()) {        return Err(MethodError::new(            "bad_request",            format!("the number on the other device is {DIGITS} digits"),        ));    }    Ok(echoed)}