teter-client 26.11.5

Relay connection shared by the teter backend and frontend
Documentation
//! The device's side of commands to a machine (#88): see
//! [`teter_common::command`]. Split in steps so a caller (or a test) can
//! hold a challenge, a sealed command and the channel apart.

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

use teter_common::command::{CHANNEL_PREFIX, Command, FromMachine, MAX_FRAME, Outcome, ToMachine};
use teter_common::{Message, MessagePayload, MessageType, SessionId};

pub use teter_core::command::{Challenge, check_challenge, open_reply, seal_command};

use crate::account::AccountKeys;
use crate::{Relay, recv, send};

/// How long the device waits for each answer of the machine: past what a
/// command that ends a session may take on the machine (reaching its socket,
/// then waiting for its process to go: 35 s), with room for the relay.
pub const ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);

/// A command channel to one machine, joined on its relay session.
pub struct Channel {
    relay: Relay,
    session: SessionId,
    /// The machine's ID.
    pub machine: String,
    /// The machine's public key, which signs its challenges.
    machine_key: Vec<u8>,
}

impl Channel {
    /// Joins relay session `session` with `token` on a fresh command channel
    /// (`url` is the relay's `/frontend` endpoint), for machine `machine`
    /// whose public key is `machine_key`.
    ///
    /// # Errors
    ///
    /// When the relay cannot be reached or refuses the join.
    pub async fn open(
        url: &str,
        ca_cert: Option<&Path>,
        session: SessionId,
        token: String,
        machine: String,
        machine_key: Vec<u8>,
    ) -> io::Result<Self> {
        if machine_key.is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "the relay gives no machine key (too old for commands)",
            ));
        }
        let mut random = [0_u8; 16];
        getrandom::fill(&mut random).map_err(io::Error::other)?;
        let channel = format!("{CHANNEL_PREFIX}{}", teter_common::account::hex(&random));
        let mut relay = crate::connect(url, ca_cert).await?;
        send(&mut relay, Message::auth(token)).await?;
        send(
            &mut relay,
            Message::session_join(session).on_channel(Some(channel)),
        )
        .await?;
        loop {
            let msg = recv(&mut relay)
                .await?
                .ok_or_else(|| io::Error::other("the relay closed before the join"))?;
            if msg.msg_type == MessageType::SessionJoined {
                if let Some(MessagePayload::SessionCreated { protocol, .. }) = &msg.payload {
                    teter_common::check_relay_protocol(*protocol).map_err(io::Error::other)?;
                }
                break;
            }
            if msg.msg_type == MessageType::SessionError {
                return Err(io::Error::other(format!(
                    "the relay refused the join: {}",
                    reason(&msg.payload)
                )));
            }
        }
        Ok(Self {
            relay,
            session,
            machine,
            machine_key,
        })
    }

    /// Sends `frame` to the machine.
    async fn put(&mut self, frame: &ToMachine) -> io::Result<()> {
        let data = serde_json::to_vec(frame).map_err(io::Error::other)?;
        send(&mut self.relay, Message::input(self.session, data)).await
    }

    /// The machine's next frame, within [`ANSWER_TIMEOUT`].
    async fn take(&mut self) -> io::Result<FromMachine> {
        tokio::time::timeout(ANSWER_TIMEOUT, self.next_frame())
            .await
            .map_err(|_elapsed| {
                io::Error::new(io::ErrorKind::TimedOut, "the machine did not answer")
            })?
    }

    /// The machine's next frame.
    async fn next_frame(&mut self) -> io::Result<FromMachine> {
        loop {
            let msg = recv(&mut self.relay)
                .await?
                .ok_or_else(|| io::Error::other("the relay closed the command channel"))?;
            if let (MessageType::Output, Some(MessagePayload::OutputData { data })) =
                (&msg.msg_type, &msg.payload)
            {
                if data.len() > MAX_FRAME {
                    return Err(io::Error::other("a command frame too large"));
                }
                return serde_json::from_slice(data).map_err(io::Error::other);
            }
            if msg.msg_type == MessageType::SessionError {
                return Err(io::Error::other(format!(
                    "the relay ended the command channel: {}",
                    reason(&msg.payload)
                )));
            }
        }
    }

    /// Asks for a challenge, checked against the machine's key.
    ///
    /// # Errors
    ///
    /// A lost channel, or a challenge the machine did not sign.
    pub async fn challenge(&mut self) -> io::Result<Challenge> {
        self.put(&ToMachine::Hello).await?;
        match self.take().await? {
            FromMachine::Challenge {
                nonce,
                key,
                signature,
            } => check_challenge(&self.machine, &self.machine_key, nonce, key, &signature)
                .ok_or_else(|| io::Error::other("the challenge is not signed by the machine")),
            FromMachine::Refused { reason } => Err(io::Error::other(reason)),
            FromMachine::Reply { .. } => Err(io::Error::other("a reply where a challenge was due")),
        }
    }

    /// Sends a sealed command and waits for the machine's answer: the
    /// outcome opened with `account`, or the refusal.
    ///
    /// # Errors
    ///
    /// A lost channel, a refusal, or a reply that does not open.
    pub async fn send_sealed(
        &mut self,
        account: &AccountKeys,
        nonce: &[u8],
        sealed: Vec<u8>,
    ) -> io::Result<Outcome> {
        self.put(&ToMachine::Command { sealed }).await?;
        match self.take().await? {
            FromMachine::Reply { sealed, signature } => open_reply(
                account,
                &self.machine,
                &self.machine_key,
                nonce,
                &sealed,
                &signature,
            ),
            FromMachine::Refused { reason } => Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!("the machine refused the command: {reason}"),
            )),
            FromMachine::Challenge { .. } => {
                Err(io::Error::other("a challenge where a reply was due"))
            }
        }
    }

    /// Runs `command` on the machine, signed by `account`.
    ///
    /// # Errors
    ///
    /// As [`Channel::challenge`] and [`Channel::send_sealed`].
    pub async fn run(&mut self, account: &AccountKeys, command: Command) -> io::Result<Outcome> {
        let challenge = self.challenge().await?;
        let sealed = seal_command(account, &self.machine, &challenge, command)?;
        self.send_sealed(account, &challenge.nonce, sealed).await
    }
}

/// The reason a relay's error carries.
fn reason(payload: &Option<MessagePayload>) -> &str {
    match payload {
        Some(MessagePayload::ErrorReason { reason }) => reason,
        _ => "no reason given",
    }
}