Skip to main content

teter_client/
lib.rs

1//! A client's connection to the teter relay, over `ws://` or `wss://`, and
2//! the protocol messages sent and received on it. Shared by the backend and
3//! the frontend.
4
5pub mod account;
6pub mod command;
7pub use teter_core::{e2e, history, sessions};
8
9use std::io;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use futures_util::{Sink, SinkExt, Stream, StreamExt};
14use teter_common::{Message, deserialize_message, serialize_message};
15use tokio::io::{AsyncRead, AsyncWrite};
16use tokio::net::TcpStream;
17use tokio_rustls::TlsConnector;
18use tokio_rustls::rustls;
19use tokio_rustls::rustls::pki_types::pem::PemObject;
20use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
21use tokio_tungstenite::WebSocketStream;
22use tokio_tungstenite::tungstenite::client::IntoClientRequest;
23use tokio_tungstenite::tungstenite::http::Uri;
24use tokio_tungstenite::tungstenite::{Error as WsError, Message as Frame};
25
26/// A byte stream: plain TCP, or TLS over TCP.
27pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
28impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
29
30/// A WebSocket connection to the relay.
31pub type Relay = WebSocketStream<Box<dyn Io>>;
32
33/// A client certificate and its private key, as PEM files: what a relay
34/// that asks for client certificates (`--client-ca`, #159) takes.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Identity {
37    /// The certificate chain, leaf first.
38    pub cert: PathBuf,
39    /// The private key: PKCS#8, PKCS#1 (RSA) or SEC1 (EC).
40    pub key: PathBuf,
41}
42
43/// The environment variable naming the client certificate.
44pub const CLIENT_CERT_VAR: &str = "TETER_CLIENT_CERT";
45/// The environment variable naming the client certificate's key.
46pub const CLIENT_KEY_VAR: &str = "TETER_CLIENT_KEY";
47
48impl Identity {
49    /// The identity [`CLIENT_CERT_VAR`] and [`CLIENT_KEY_VAR`] name, if
50    /// they are set (an empty one counts as unset).
51    ///
52    /// # Errors
53    ///
54    /// Only one of the two is set.
55    pub fn from_env() -> io::Result<Option<Self>> {
56        let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
57        Self::from_vars(var(CLIENT_CERT_VAR), var(CLIENT_KEY_VAR))
58    }
59
60    fn from_vars(
61        cert: Option<std::ffi::OsString>,
62        key: Option<std::ffi::OsString>,
63    ) -> io::Result<Option<Self>> {
64        match (cert, key) {
65            (Some(cert), Some(key)) => Ok(Some(Self {
66                cert: cert.into(),
67                key: key.into(),
68            })),
69            (None, None) => Ok(None),
70            _ => Err(invalid(format!(
71                "a client certificate needs both {CLIENT_CERT_VAR} and {CLIENT_KEY_VAR}"
72            ))),
73        }
74    }
75}
76
77/// Connect to `url` (`ws://host:port/path` or `wss://...`). For `wss://`,
78/// the relay's certificate must chain to the system's roots, or to
79/// `ca_cert` (a PEM file) when given; the client certificate
80/// [`Identity::from_env`] names, if any, goes to a relay that asks for one.
81pub async fn connect(url: &str, ca_cert: Option<&Path>) -> io::Result<Relay> {
82    connect_as(url, ca_cert, Identity::from_env()?.as_ref()).await
83}
84
85/// [`connect`], presenting `identity` (a client certificate) over `wss://`
86/// rather than the one the environment names.
87pub async fn connect_as(
88    url: &str,
89    ca_cert: Option<&Path>,
90    identity: Option<&Identity>,
91) -> io::Result<Relay> {
92    let uri: Uri = url
93        .parse()
94        .map_err(|e| invalid(format!("relay URL {url}: {e}")))?;
95    let tls = match uri.scheme_str() {
96        Some("ws") => false,
97        Some("wss") => true,
98        _ => return Err(invalid(format!("relay URL {url}: not ws:// or wss://"))),
99    };
100    let host = uri
101        .host()
102        .ok_or_else(|| invalid(format!("relay URL {url}: no host")))?
103        .trim_start_matches('[')
104        .trim_end_matches(']')
105        .to_owned();
106    let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
107
108    let tcp = TcpStream::connect((host.as_str(), port)).await?;
109    tcp.set_nodelay(true)?;
110    let stream: Box<dyn Io> = if tls {
111        let connector = TlsConnector::from(Arc::new(client_config(ca_cert, identity)?));
112        let name = ServerName::try_from(host.clone())
113            .map_err(|e| invalid(format!("relay host {host}: {e}")))?;
114        Box::new(connector.connect(name, tcp).await?)
115    } else {
116        Box::new(tcp)
117    };
118    let request = url.into_client_request().map_err(io::Error::other)?;
119    let (ws, _) = tokio_tungstenite::client_async(request, stream)
120        .await
121        .map_err(io::Error::other)?;
122    Ok(ws)
123}
124
125fn client_config(
126    ca_cert: Option<&Path>,
127    identity: Option<&Identity>,
128) -> io::Result<rustls::ClientConfig> {
129    let mut roots = rustls::RootCertStore::empty();
130    match ca_cert {
131        Some(path) => {
132            for cert in CertificateDer::pem_file_iter(path)
133                .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?
134            {
135                let cert =
136                    cert.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
137                roots
138                    .add(cert)
139                    .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
140            }
141        }
142        None => {
143            let found = rustls_native_certs::load_native_certs();
144            roots.add_parsable_certificates(found.certs);
145        }
146    }
147    let provider = Arc::new(rustls::crypto::ring::default_provider());
148    let builder = rustls::ClientConfig::builder_with_provider(provider)
149        .with_safe_default_protocol_versions()
150        .map_err(io::Error::other)?
151        .with_root_certificates(roots);
152    let Some(identity) = identity else {
153        return Ok(builder.with_no_client_auth());
154    };
155    let cert_error = |e: &dyn std::fmt::Display| {
156        invalid(format!(
157            "client certificate {}: {e}",
158            identity.cert.display()
159        ))
160    };
161    let certs = CertificateDer::pem_file_iter(&identity.cert)
162        .and_then(|certs| certs.collect::<Result<Vec<_>, _>>())
163        .map_err(|e| cert_error(&e))?;
164    if certs.is_empty() {
165        return Err(cert_error(&"no certificate in the file"));
166    }
167    let key = PrivateKeyDer::from_pem_file(&identity.key).map_err(|e| {
168        invalid(format!(
169            "client certificate key {}: {e}",
170            identity.key.display()
171        ))
172    })?;
173    builder.with_client_auth_cert(certs, key).map_err(|e| {
174        invalid(format!(
175            "client certificate {} with key {}: {e}",
176            identity.cert.display(),
177            identity.key.display()
178        ))
179    })
180}
181
182fn invalid(message: String) -> io::Error {
183    io::Error::new(io::ErrorKind::InvalidInput, message)
184}
185
186/// Send one protocol message on `sink` (a [`Relay`], or its sending half).
187pub async fn send<S>(sink: &mut S, msg: Message) -> io::Result<()>
188where
189    S: Sink<Frame, Error = WsError> + Unpin,
190{
191    let text = serialize_message(&msg).map_err(io::Error::other)?;
192    sink.send(Frame::text(text)).await.map_err(io::Error::other)
193}
194
195/// The next protocol message on `stream` (a [`Relay`], or its receiving
196/// half), or `None` once the relay closed the connection.
197pub async fn recv<S>(stream: &mut S) -> io::Result<Option<Message>>
198where
199    S: Stream<Item = Result<Frame, WsError>> + Unpin,
200{
201    loop {
202        match stream.next().await {
203            Some(Ok(Frame::Text(text))) => {
204                return deserialize_message(&text)
205                    .map(Some)
206                    .map_err(io::Error::other);
207            }
208            Some(Ok(Frame::Close(_))) | None => return Ok(None),
209            Some(Ok(_)) => {}
210            Some(Err(e)) => return Err(io::Error::other(e)),
211        }
212    }
213}
214
215#[cfg(test)]
216mod tests {
217
218    use super::*;
219
220    #[test]
221    fn an_identity_needs_both_files_or_neither() {
222        assert_eq!(Identity::from_vars(None, None).unwrap(), None);
223        assert_eq!(
224            Identity::from_vars(Some("c.pem".into()), Some("k.pem".into())).unwrap(),
225            Some(Identity {
226                cert: "c.pem".into(),
227                key: "k.pem".into()
228            })
229        );
230        for (cert, key) in [(Some("c.pem".into()), None), (None, Some("k.pem".into()))] {
231            let err = Identity::from_vars(cert, key).unwrap_err();
232            assert!(err.to_string().contains(CLIENT_KEY_VAR), "{err}");
233        }
234    }
235}