pxp 0.1.0

FIDO Proximity Exchange Protocol (PXP, formerly CTAP hybrid / caBLE) client for Linux, written in Rust
Documentation
//! Transport-agnostic message channel for the hybrid transport.
use async_trait::async_trait;
use futures::{SinkExt, StreamExt};
use tokio::net::TcpStream;
use tokio_tungstenite::tungstenite::{Error, Message};
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use tracing::warn;

use crate::error::PxpError;

/// A bidirectional channel carrying discrete protocol messages: the Noise
/// handshake messages, then the encrypted CTAP frames. caBLE rides this over a
/// WebSocket tunnel; CTAP 2.3 hybrid can also ride it over a BLE L2CAP connection.
#[async_trait]
pub(crate) trait PxpDataChannel: Send {
    /// Sends one message as a discrete unit.
    async fn send(&mut self, message: &[u8]) -> Result<(), PxpError>;

    /// Receives the next message. `Ok(None)` signals a clean close by the peer.
    /// Must be cancel-safe so it can be used as a `tokio::select!` branch.
    async fn recv(&mut self) -> Result<Option<Vec<u8>>, PxpError>;
}

/// [`PxpDataChannel`] over the caBLE WebSocket tunnel. Each protocol message is
/// a single binary WebSocket frame.
pub(crate) struct WebSocketDataChannel {
    stream: WebSocketStream<MaybeTlsStream<TcpStream>>,
}

impl WebSocketDataChannel {
    pub(crate) fn new(stream: WebSocketStream<MaybeTlsStream<TcpStream>>) -> Self {
        Self { stream }
    }
}

#[async_trait]
impl PxpDataChannel for WebSocketDataChannel {
    async fn send(&mut self, message: &[u8]) -> Result<(), PxpError> {
        self.stream
            .send(Message::Binary(message.to_vec().into()))
            .await
            .map_err(|e| {
                warn!(?e, "Failed to send WebSocket message");
                match e {
                    Error::Io(io) => PxpError::from(io),
                    _ => PxpError::ConnectionFailed,
                }
            })
    }

    async fn recv(&mut self) -> Result<Option<Vec<u8>>, PxpError> {
        loop {
            match self.stream.next().await {
                Some(Ok(Message::Binary(data))) => return Ok(Some(data.into())),
                Some(Ok(Message::Ping(_) | Message::Pong(_))) => continue,
                Some(Ok(Message::Close(_))) | None | Some(Err(Error::ConnectionClosed)) => {
                    return Ok(None)
                }
                Some(Ok(other)) => {
                    warn!(?other, "Unexpected WebSocket message type");
                    return Err(PxpError::ConnectionFailed);
                }
                Some(Err(Error::Io(e))) => {
                    warn!(?e, "Failed to read WebSocket message");
                    return Err(PxpError::from(e));
                }
                Some(Err(e)) => {
                    warn!(?e, "Failed to read WebSocket message");
                    return Err(PxpError::ConnectionFailed);
                }
            }
        }
    }
}