teter-client 26.11.7

Relay connection shared by the teter backend and frontend
Documentation
//! A client's connection to the teter relay, over `ws://` or `wss://`, and
//! the protocol messages sent and received on it. Shared by the backend and
//! the frontend.

pub mod account;
pub mod command;
pub use teter_core::{e2e, history, sessions};

use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use futures_util::{Sink, SinkExt, Stream, StreamExt};
use teter_common::{Message, deserialize_message, serialize_message};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tokio_rustls::rustls;
use tokio_rustls::rustls::pki_types::pem::PemObject;
use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::Uri;
use tokio_tungstenite::tungstenite::{Error as WsError, Message as Frame};

/// A byte stream: plain TCP, or TLS over TCP.
pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}

/// A WebSocket connection to the relay.
pub type Relay = WebSocketStream<Box<dyn Io>>;

/// A client certificate and its private key, as PEM files: what a relay
/// that asks for client certificates (`--client-ca`, #159) takes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
    /// The certificate chain, leaf first.
    pub cert: PathBuf,
    /// The private key: PKCS#8, PKCS#1 (RSA) or SEC1 (EC).
    pub key: PathBuf,
}

/// The environment variable naming the client certificate.
pub const CLIENT_CERT_VAR: &str = "TETER_CLIENT_CERT";
/// The environment variable naming the client certificate's key.
pub const CLIENT_KEY_VAR: &str = "TETER_CLIENT_KEY";

impl Identity {
    /// The identity [`CLIENT_CERT_VAR`] and [`CLIENT_KEY_VAR`] name, if
    /// they are set (an empty one counts as unset).
    ///
    /// # Errors
    ///
    /// Only one of the two is set.
    pub fn from_env() -> io::Result<Option<Self>> {
        let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
        Self::from_vars(var(CLIENT_CERT_VAR), var(CLIENT_KEY_VAR))
    }

    fn from_vars(
        cert: Option<std::ffi::OsString>,
        key: Option<std::ffi::OsString>,
    ) -> io::Result<Option<Self>> {
        match (cert, key) {
            (Some(cert), Some(key)) => Ok(Some(Self {
                cert: cert.into(),
                key: key.into(),
            })),
            (None, None) => Ok(None),
            _ => Err(invalid(format!(
                "a client certificate needs both {CLIENT_CERT_VAR} and {CLIENT_KEY_VAR}"
            ))),
        }
    }
}

/// Connect to `url` (`ws://host:port/path` or `wss://...`). For `wss://`,
/// the relay's certificate must chain to the system's roots, or to
/// `ca_cert` (a PEM file) when given; the client certificate
/// [`Identity::from_env`] names, if any, goes to a relay that asks for one.
pub async fn connect(url: &str, ca_cert: Option<&Path>) -> io::Result<Relay> {
    connect_as(url, ca_cert, Identity::from_env()?.as_ref()).await
}

/// [`connect`], presenting `identity` (a client certificate) over `wss://`
/// rather than the one the environment names.
pub async fn connect_as(
    url: &str,
    ca_cert: Option<&Path>,
    identity: Option<&Identity>,
) -> io::Result<Relay> {
    let uri: Uri = url
        .parse()
        .map_err(|e| invalid(format!("relay URL {url}: {e}")))?;
    let tls = match uri.scheme_str() {
        Some("ws") => false,
        Some("wss") => true,
        _ => return Err(invalid(format!("relay URL {url}: not ws:// or wss://"))),
    };
    let host = uri
        .host()
        .ok_or_else(|| invalid(format!("relay URL {url}: no host")))?
        .trim_start_matches('[')
        .trim_end_matches(']')
        .to_owned();
    let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });

    let tcp = TcpStream::connect((host.as_str(), port)).await?;
    tcp.set_nodelay(true)?;
    let stream: Box<dyn Io> = if tls {
        let connector = TlsConnector::from(Arc::new(client_config(ca_cert, identity)?));
        let name = ServerName::try_from(host.clone())
            .map_err(|e| invalid(format!("relay host {host}: {e}")))?;
        Box::new(connector.connect(name, tcp).await?)
    } else {
        Box::new(tcp)
    };
    let request = url.into_client_request().map_err(io::Error::other)?;
    let (ws, _) = tokio_tungstenite::client_async(request, stream)
        .await
        .map_err(io::Error::other)?;
    Ok(ws)
}

fn client_config(
    ca_cert: Option<&Path>,
    identity: Option<&Identity>,
) -> io::Result<rustls::ClientConfig> {
    let mut roots = rustls::RootCertStore::empty();
    match ca_cert {
        Some(path) => {
            for cert in CertificateDer::pem_file_iter(path)
                .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?
            {
                let cert =
                    cert.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
                roots
                    .add(cert)
                    .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
            }
        }
        None => {
            let found = rustls_native_certs::load_native_certs();
            roots.add_parsable_certificates(found.certs);
        }
    }
    let provider = Arc::new(rustls::crypto::ring::default_provider());
    let builder = rustls::ClientConfig::builder_with_provider(provider)
        .with_safe_default_protocol_versions()
        .map_err(io::Error::other)?
        .with_root_certificates(roots);
    let Some(identity) = identity else {
        return Ok(builder.with_no_client_auth());
    };
    let cert_error = |e: &dyn std::fmt::Display| {
        invalid(format!(
            "client certificate {}: {e}",
            identity.cert.display()
        ))
    };
    let certs = CertificateDer::pem_file_iter(&identity.cert)
        .and_then(|certs| certs.collect::<Result<Vec<_>, _>>())
        .map_err(|e| cert_error(&e))?;
    if certs.is_empty() {
        return Err(cert_error(&"no certificate in the file"));
    }
    let key = PrivateKeyDer::from_pem_file(&identity.key).map_err(|e| {
        invalid(format!(
            "client certificate key {}: {e}",
            identity.key.display()
        ))
    })?;
    builder.with_client_auth_cert(certs, key).map_err(|e| {
        invalid(format!(
            "client certificate {} with key {}: {e}",
            identity.cert.display(),
            identity.key.display()
        ))
    })
}

fn invalid(message: String) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message)
}

/// Send one protocol message on `sink` (a [`Relay`], or its sending half).
pub async fn send<S>(sink: &mut S, msg: Message) -> io::Result<()>
where
    S: Sink<Frame, Error = WsError> + Unpin,
{
    let text = serialize_message(&msg).map_err(io::Error::other)?;
    sink.send(Frame::text(text)).await.map_err(io::Error::other)
}

/// The next protocol message on `stream` (a [`Relay`], or its receiving
/// half), or `None` once the relay closed the connection.
pub async fn recv<S>(stream: &mut S) -> io::Result<Option<Message>>
where
    S: Stream<Item = Result<Frame, WsError>> + Unpin,
{
    loop {
        match stream.next().await {
            Some(Ok(Frame::Text(text))) => {
                return deserialize_message(&text)
                    .map(Some)
                    .map_err(io::Error::other);
            }
            Some(Ok(Frame::Close(_))) | None => return Ok(None),
            Some(Ok(_)) => {}
            Some(Err(e)) => return Err(io::Error::other(e)),
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn an_identity_needs_both_files_or_neither() {
        assert_eq!(Identity::from_vars(None, None).unwrap(), None);
        assert_eq!(
            Identity::from_vars(Some("c.pem".into()), Some("k.pem".into())).unwrap(),
            Some(Identity {
                cert: "c.pem".into(),
                key: "k.pem".into()
            })
        );
        for (cert, key) in [(Some("c.pem".into()), None), (None, Some("k.pem".into()))] {
            let err = Identity::from_vars(cert, key).unwrap_err();
            assert!(err.to_string().contains(CLIENT_KEY_VAR), "{err}");
        }
    }
}