Skip to main content

teter_client/
account.rs

1//! The client side of accounts: the crypto (`teter_core::account`, re-exported
2//! here) and the requests to the relay's account service
3//! (`teter_common::account`), with a machine's authentication.
4
5use std::io;
6use std::path::Path;
7
8use futures_util::{SinkExt, StreamExt};
9use teter_common::account::{AccountReply, AccountRequest, PATH};
10use tokio_tungstenite::tungstenite::Message as Frame;
11
12pub use teter_core::account::*;
13
14/// The relay does not know this machine (removed from its account, or
15/// registered with another relay): carried inside the `io::Error` a refusal
16/// gives; [`MachineUnknown::is`] tells it from a passing failure, which an
17/// error kind cannot (a local firewall gives `PermissionDenied` too).
18#[derive(Debug)]
19pub struct MachineUnknown(String);
20
21impl MachineUnknown {
22    /// Whether `error` is this refusal.
23    pub fn is(error: &io::Error) -> bool {
24        error.get_ref().is_some_and(|inner| inner.is::<Self>())
25    }
26}
27
28impl std::fmt::Display for MachineUnknown {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.write_str(&self.0)
31    }
32}
33
34impl std::error::Error for MachineUnknown {}
35
36/// The error a relay's refusal of a machine with `reason` gives: marked
37/// [`MachineUnknown`] when the relay does not know it, a plain one else.
38pub fn machine_refusal(reason: &str) -> io::Error {
39    let message = format!("the relay refused this machine: {reason}");
40    if reason == teter_common::account::MACHINE_UNKNOWN {
41        io::Error::new(io::ErrorKind::PermissionDenied, MachineUnknown(message))
42    } else {
43        io::Error::other(message)
44    }
45}
46
47/// Authenticates machine `id` with `key` on `ws`, a fresh `/backend`
48/// connection (#86, #130): `machine_hello`, the relay's challenge, the
49/// signature of it. The only way a backend gets in.
50///
51/// # Errors
52///
53/// A lost connection, or the relay refusing the machine (unknown, removed,
54/// or registered with another relay).
55pub async fn authenticate_machine<S>(ws: &mut S, id: &str, key: &MachineKey) -> io::Result<()>
56where
57    S: futures_util::Sink<Frame, Error = tokio_tungstenite::tungstenite::Error>
58        + futures_util::Stream<Item = Result<Frame, tokio_tungstenite::tungstenite::Error>>
59        + Unpin,
60{
61    use teter_common::{Message, MessagePayload, MessageType};
62    let hello = Message {
63        msg_type: MessageType::MachineHello,
64        session: None,
65        channel: None,
66        payload: Some(MessagePayload::MachineId {
67            machine: id.to_owned(),
68            protocol: teter_common::PROTOCOL,
69        }),
70    };
71    crate::send(ws, hello).await?;
72    let challenge = crate::recv(ws)
73        .await?
74        .ok_or_else(|| io::Error::other("the relay closed the connection before its challenge"))?;
75    let nonce = match (challenge.msg_type, challenge.payload) {
76        (MessageType::Challenge, Some(MessagePayload::Challenge { nonce, protocol })) => {
77            // A relay older than this teter says so here, not later (#95).
78            teter_common::check_relay_protocol(protocol).map_err(io::Error::other)?;
79            nonce
80        }
81        (MessageType::SessionError, payload) => {
82            let reason = match payload {
83                Some(MessagePayload::ErrorReason { reason }) => reason,
84                _ => "no reason given".to_owned(),
85            };
86            // Only a machine the relay does not know is refused for good
87            // (marked [`MachineUnknown`]); a protocol mismatch, a store that
88            // failed or a bad proof is an error like any other (#138).
89            return Err(machine_refusal(&reason));
90        }
91        (other, _) => {
92            return Err(io::Error::other(format!(
93                "the relay answered the machine's hello with {}",
94                other.to_str()
95            )));
96        }
97    };
98    let proof = Message {
99        msg_type: MessageType::MachineProof,
100        session: None,
101        channel: None,
102        payload: Some(MessagePayload::Signature {
103            signature: key.sign(&teter_common::machine_proof_message(&nonce, id)),
104        }),
105    };
106    crate::send(ws, proof).await
107}
108
109/// Sends `request` to the account service of the relay at `relay` (the
110/// relay's URL, `ws://` or `wss://`, with or without an endpoint path) and
111/// returns its reply.
112///
113/// # Errors
114///
115/// When the relay cannot be reached, or does not answer with a reply.
116pub async fn request(
117    relay: &str,
118    ca_cert: Option<&Path>,
119    request: &AccountRequest,
120) -> Result<AccountReply, AccountError> {
121    let mut ws = crate::connect(&account_url(relay), ca_cert).await?;
122    let text = serde_json::to_string(request).map_err(io::Error::other)?;
123    ws.send(Frame::text(text)).await.map_err(io::Error::other)?;
124    loop {
125        match ws.next().await {
126            Some(Ok(Frame::Text(text))) => {
127                drop(ws.close(None).await);
128                return serde_json::from_str(&text).map_err(|e| {
129                    AccountError::Refused(format!("an answer teter does not read: {e}"))
130                });
131            }
132            Some(Ok(_)) => {}
133            Some(Err(e)) => return Err(io::Error::other(e).into()),
134            None => {
135                return Err(AccountError::Refused(
136                    "the relay closed the connection without an answer".to_owned(),
137                ));
138            }
139        }
140    }
141}
142
143/// The account service's URL at relay `relay`.
144fn account_url(relay: &str) -> String {
145    let host_at = relay.find("://").map_or(0, |at| at + 3);
146    let path_at = relay
147        .get(host_at..)
148        .and_then(|rest| rest.find('/'))
149        .map_or(relay.len(), |at| host_at + at);
150    let (origin, path) = relay.split_at(path_at);
151    let path = path.trim_end_matches('/');
152    let path = ["/backend", "/frontend", PATH]
153        .into_iter()
154        .find_map(|endpoint| path.strip_suffix(endpoint))
155        .unwrap_or(path);
156    format!("{origin}{path}{PATH}")
157}
158
159#[cfg(test)]
160mod tests {
161    use super::account_url;
162
163    #[test]
164    fn the_account_service_is_the_relays_account_path() {
165        for relay in [
166            "wss://relay.example.com",
167            "wss://relay.example.com/",
168            "wss://relay.example.com/backend",
169            "wss://relay.example.com/frontend",
170            "wss://relay.example.com/account",
171        ] {
172            assert_eq!(account_url(relay), "wss://relay.example.com/account");
173        }
174        assert_eq!(account_url("ws://backend"), "ws://backend/account");
175    }
176}