teter-client 26.11.6

Relay connection shared by the teter backend and frontend
Documentation
//! The client side of accounts: the crypto (`teter_core::account`, re-exported
//! here) and the requests to the relay's account service
//! (`teter_common::account`), with a machine's authentication.

use std::io;
use std::path::Path;

use futures_util::{SinkExt, StreamExt};
use teter_common::account::{AccountReply, AccountRequest, PATH};
use tokio_tungstenite::tungstenite::Message as Frame;

pub use teter_core::account::*;

/// The relay does not know this machine (removed from its account, or
/// registered with another relay): carried inside the `io::Error` a refusal
/// gives; [`MachineUnknown::is`] tells it from a passing failure, which an
/// error kind cannot (a local firewall gives `PermissionDenied` too).
#[derive(Debug)]
pub struct MachineUnknown(String);

impl MachineUnknown {
    /// Whether `error` is this refusal.
    pub fn is(error: &io::Error) -> bool {
        error.get_ref().is_some_and(|inner| inner.is::<Self>())
    }
}

impl std::fmt::Display for MachineUnknown {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for MachineUnknown {}

/// The error a relay's refusal of a machine with `reason` gives: marked
/// [`MachineUnknown`] when the relay does not know it, a plain one else.
pub fn machine_refusal(reason: &str) -> io::Error {
    let message = format!("the relay refused this machine: {reason}");
    if reason == teter_common::account::MACHINE_UNKNOWN {
        io::Error::new(io::ErrorKind::PermissionDenied, MachineUnknown(message))
    } else {
        io::Error::other(message)
    }
}

/// Authenticates machine `id` with `key` on `ws`, a fresh `/backend`
/// connection (#86, #130): `machine_hello`, the relay's challenge, the
/// signature of it. The only way a backend gets in. The account's key
/// rotations the challenge carries (#89), for the machine to follow.
///
/// # Errors
///
/// A lost connection, or the relay refusing the machine (unknown, removed,
/// or registered with another relay).
pub async fn authenticate_machine<S>(
    ws: &mut S,
    id: &str,
    key: &MachineKey,
) -> io::Result<Vec<teter_common::account::KeyRotation>>
where
    S: futures_util::Sink<Frame, Error = tokio_tungstenite::tungstenite::Error>
        + futures_util::Stream<Item = Result<Frame, tokio_tungstenite::tungstenite::Error>>
        + Unpin,
{
    use teter_common::{Message, MessagePayload, MessageType};
    let hello = Message {
        msg_type: MessageType::MachineHello,
        session: None,
        channel: None,
        payload: Some(MessagePayload::MachineId {
            machine: id.to_owned(),
            protocol: teter_common::PROTOCOL,
        }),
    };
    crate::send(ws, hello).await?;
    let challenge = crate::recv(ws)
        .await?
        .ok_or_else(|| io::Error::other("the relay closed the connection before its challenge"))?;
    let (nonce, rotations) = match (challenge.msg_type, challenge.payload) {
        (
            MessageType::Challenge,
            Some(MessagePayload::Challenge {
                nonce,
                protocol,
                rotations,
            }),
        ) => {
            // A relay older than this teter says so here, not later (#95).
            teter_common::check_relay_protocol(protocol).map_err(io::Error::other)?;
            (nonce, rotations)
        }
        (MessageType::SessionError, payload) => {
            let reason = match payload {
                Some(MessagePayload::ErrorReason { reason }) => reason,
                _ => "no reason given".to_owned(),
            };
            // Only a machine the relay does not know is refused for good
            // (marked [`MachineUnknown`]); a protocol mismatch, a store that
            // failed or a bad proof is an error like any other (#138).
            return Err(machine_refusal(&reason));
        }
        (other, _) => {
            return Err(io::Error::other(format!(
                "the relay answered the machine's hello with {}",
                other.to_str()
            )));
        }
    };
    let proof = Message {
        msg_type: MessageType::MachineProof,
        session: None,
        channel: None,
        payload: Some(MessagePayload::Signature {
            signature: key.sign(&teter_common::machine_proof_message(&nonce, id)),
        }),
    };
    crate::send(ws, proof).await?;
    Ok(rotations)
}

/// Sends `request` to the account service of the relay at `relay` (the
/// relay's URL, `ws://` or `wss://`, with or without an endpoint path) and
/// returns its reply.
///
/// # Errors
///
/// When the relay cannot be reached, or does not answer with a reply.
pub async fn request(
    relay: &str,
    ca_cert: Option<&Path>,
    request: &AccountRequest,
) -> Result<AccountReply, AccountError> {
    let mut ws = crate::connect(&account_url(relay), ca_cert).await?;
    let text = serde_json::to_string(request).map_err(io::Error::other)?;
    ws.send(Frame::text(text)).await.map_err(io::Error::other)?;
    loop {
        match ws.next().await {
            Some(Ok(Frame::Text(text))) => {
                drop(ws.close(None).await);
                return serde_json::from_str(&text).map_err(|e| {
                    AccountError::Refused(format!("an answer teter does not read: {e}"))
                });
            }
            Some(Ok(_)) => {}
            Some(Err(e)) => return Err(io::Error::other(e).into()),
            None => {
                return Err(AccountError::Refused(
                    "the relay closed the connection without an answer".to_owned(),
                ));
            }
        }
    }
}

/// The account service's URL at relay `relay`.
fn account_url(relay: &str) -> String {
    let host_at = relay.find("://").map_or(0, |at| at + 3);
    let path_at = relay
        .get(host_at..)
        .and_then(|rest| rest.find('/'))
        .map_or(relay.len(), |at| host_at + at);
    let (origin, path) = relay.split_at(path_at);
    let path = path.trim_end_matches('/');
    let path = ["/backend", "/frontend", PATH]
        .into_iter()
        .find_map(|endpoint| path.strip_suffix(endpoint))
        .unwrap_or(path);
    format!("{origin}{path}{PATH}")
}

#[cfg(test)]
mod tests {
    use super::account_url;

    #[test]
    fn the_account_service_is_the_relays_account_path() {
        for relay in [
            "wss://relay.example.com",
            "wss://relay.example.com/",
            "wss://relay.example.com/backend",
            "wss://relay.example.com/frontend",
            "wss://relay.example.com/account",
        ] {
            assert_eq!(account_url(relay), "wss://relay.example.com/account");
        }
        assert_eq!(account_url("ws://backend"), "ws://backend/account");
    }
}