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(|e| handshake_error(url, e))?;
122    Ok(ws)
123}
124
125/// The handshake's error, saying where a redirect points (#167): a
126/// WebSocket follows none, and a `ws://` URL in front of an HTTPS proxy
127/// gets one to `https://`, which means `wss://`.
128fn handshake_error(url: &str, error: tokio_tungstenite::tungstenite::Error) -> io::Error {
129    let tokio_tungstenite::tungstenite::Error::Http(response) = &error else {
130        return io::Error::other(error);
131    };
132    if !response.status().is_redirection() {
133        return io::Error::other(error);
134    }
135    let location = response
136        .headers()
137        .get("location")
138        .and_then(|location| location.to_str().ok())
139        .unwrap_or("");
140    let secure = url
141        .strip_prefix("ws://")
142        .filter(|rest| {
143            location
144                .strip_prefix("https://")
145                .is_some_and(|to| host_of(to) == host_of(rest))
146        })
147        .map(|rest| format!("wss://{rest}"));
148    io::Error::other(match secure {
149        Some(secure) => format!(
150            "the relay at {url} redirects to https ({}): use {secure}",
151            response.status()
152        ),
153        None if location.is_empty() => format!(
154            "the relay at {url} redirects ({}) without saying where",
155            response.status()
156        ),
157        None => format!(
158            "the relay at {url} redirects ({}) to {location}: use that address, with ws:// or \
159             wss://",
160            response.status()
161        ),
162    })
163}
164
165/// The host and port of a URL's rest after its scheme.
166fn host_of(rest: &str) -> &str {
167    rest.split(['/', '?', '#']).next().unwrap_or("")
168}
169
170fn client_config(
171    ca_cert: Option<&Path>,
172    identity: Option<&Identity>,
173) -> io::Result<rustls::ClientConfig> {
174    let mut roots = rustls::RootCertStore::empty();
175    match ca_cert {
176        Some(path) => {
177            for cert in CertificateDer::pem_file_iter(path)
178                .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?
179            {
180                let cert =
181                    cert.map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
182                roots
183                    .add(cert)
184                    .map_err(|e| invalid(format!("CA certificate {}: {e}", path.display())))?;
185            }
186        }
187        None => {
188            let found = rustls_native_certs::load_native_certs();
189            roots.add_parsable_certificates(found.certs);
190        }
191    }
192    let provider = Arc::new(rustls::crypto::ring::default_provider());
193    let builder = rustls::ClientConfig::builder_with_provider(provider)
194        .with_safe_default_protocol_versions()
195        .map_err(io::Error::other)?
196        .with_root_certificates(roots);
197    let Some(identity) = identity else {
198        return Ok(builder.with_no_client_auth());
199    };
200    let cert_error = |e: &dyn std::fmt::Display| {
201        invalid(format!(
202            "client certificate {}: {e}",
203            identity.cert.display()
204        ))
205    };
206    let certs = CertificateDer::pem_file_iter(&identity.cert)
207        .and_then(|certs| certs.collect::<Result<Vec<_>, _>>())
208        .map_err(|e| cert_error(&e))?;
209    if certs.is_empty() {
210        return Err(cert_error(&"no certificate in the file"));
211    }
212    let key = PrivateKeyDer::from_pem_file(&identity.key).map_err(|e| {
213        invalid(format!(
214            "client certificate key {}: {e}",
215            identity.key.display()
216        ))
217    })?;
218    builder.with_client_auth_cert(certs, key).map_err(|e| {
219        invalid(format!(
220            "client certificate {} with key {}: {e}",
221            identity.cert.display(),
222            identity.key.display()
223        ))
224    })
225}
226
227fn invalid(message: String) -> io::Error {
228    io::Error::new(io::ErrorKind::InvalidInput, message)
229}
230
231/// Send one protocol message on `sink` (a [`Relay`], or its sending half).
232pub async fn send<S>(sink: &mut S, msg: Message) -> io::Result<()>
233where
234    S: Sink<Frame, Error = WsError> + Unpin,
235{
236    let text = serialize_message(&msg).map_err(io::Error::other)?;
237    sink.send(Frame::text(text)).await.map_err(io::Error::other)
238}
239
240/// The next protocol message on `stream` (a [`Relay`], or its receiving
241/// half), or `None` once the relay closed the connection.
242pub async fn recv<S>(stream: &mut S) -> io::Result<Option<Message>>
243where
244    S: Stream<Item = Result<Frame, WsError>> + Unpin,
245{
246    loop {
247        match stream.next().await {
248            Some(Ok(Frame::Text(text))) => {
249                return deserialize_message(&text)
250                    .map(Some)
251                    .map_err(io::Error::other);
252            }
253            Some(Ok(Frame::Close(_))) | None => return Ok(None),
254            Some(Ok(_)) => {}
255            Some(Err(e)) => return Err(io::Error::other(e)),
256        }
257    }
258}
259
260#[cfg(test)]
261mod tests {
262
263    use super::*;
264
265    #[test]
266    fn an_identity_needs_both_files_or_neither() {
267        assert_eq!(Identity::from_vars(None, None).unwrap(), None);
268        assert_eq!(
269            Identity::from_vars(Some("c.pem".into()), Some("k.pem".into())).unwrap(),
270            Some(Identity {
271                cert: "c.pem".into(),
272                key: "k.pem".into()
273            })
274        );
275        for (cert, key) in [(Some("c.pem".into()), None), (None, Some("k.pem".into()))] {
276            let err = Identity::from_vars(cert, key).unwrap_err();
277            assert!(err.to_string().contains(CLIENT_KEY_VAR), "{err}");
278        }
279    }
280}