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. The account's key
50/// rotations the challenge carries (#89), for the machine to follow.
51///
52/// # Errors
53///
54/// A lost connection, or the relay refusing the machine (unknown, removed,
55/// or registered with another relay).
56pub async fn authenticate_machine<S>(
57    ws: &mut S,
58    id: &str,
59    key: &MachineKey,
60) -> io::Result<Vec<teter_common::account::KeyRotation>>
61where
62    S: futures_util::Sink<Frame, Error = tokio_tungstenite::tungstenite::Error>
63        + futures_util::Stream<Item = Result<Frame, tokio_tungstenite::tungstenite::Error>>
64        + Unpin,
65{
66    use teter_common::{Message, MessagePayload, MessageType};
67    let hello = Message {
68        msg_type: MessageType::MachineHello,
69        session: None,
70        channel: None,
71        payload: Some(MessagePayload::MachineId {
72            machine: id.to_owned(),
73            protocol: teter_common::PROTOCOL,
74        }),
75    };
76    crate::send(ws, hello).await?;
77    let challenge = crate::recv(ws)
78        .await?
79        .ok_or_else(|| io::Error::other("the relay closed the connection before its challenge"))?;
80    let (nonce, rotations) = match (challenge.msg_type, challenge.payload) {
81        (
82            MessageType::Challenge,
83            Some(MessagePayload::Challenge {
84                nonce,
85                protocol,
86                rotations,
87            }),
88        ) => {
89            // A relay older than this teter says so here, not later (#95).
90            teter_common::check_relay_protocol(protocol).map_err(io::Error::other)?;
91            (nonce, rotations)
92        }
93        (MessageType::SessionError, payload) => {
94            let reason = match payload {
95                Some(MessagePayload::ErrorReason { reason }) => reason,
96                _ => "no reason given".to_owned(),
97            };
98            // Only a machine the relay does not know is refused for good
99            // (marked [`MachineUnknown`]); a protocol mismatch, a store that
100            // failed or a bad proof is an error like any other (#138).
101            return Err(machine_refusal(&reason));
102        }
103        (other, _) => {
104            return Err(io::Error::other(format!(
105                "the relay answered the machine's hello with {}",
106                other.to_str()
107            )));
108        }
109    };
110    let proof = Message {
111        msg_type: MessageType::MachineProof,
112        session: None,
113        channel: None,
114        payload: Some(MessagePayload::Signature {
115            signature: key.sign(&teter_common::machine_proof_message(&nonce, id)),
116        }),
117    };
118    crate::send(ws, proof).await?;
119    Ok(rotations)
120}
121
122/// Sends `request` to the account service of the relay at `relay` (the
123/// relay's URL, `ws://` or `wss://`, with or without an endpoint path) and
124/// returns its reply.
125///
126/// # Errors
127///
128/// When the relay cannot be reached, or does not answer with a reply.
129pub async fn request(
130    relay: &str,
131    ca_cert: Option<&Path>,
132    request: &AccountRequest,
133) -> Result<AccountReply, AccountError> {
134    let mut ws = crate::connect(&account_url(relay), ca_cert).await?;
135    let text = serde_json::to_string(request).map_err(io::Error::other)?;
136    ws.send(Frame::text(text)).await.map_err(io::Error::other)?;
137    loop {
138        match ws.next().await {
139            Some(Ok(Frame::Text(text))) => {
140                drop(ws.close(None).await);
141                return serde_json::from_str(&text).map_err(|e| {
142                    AccountError::Refused(format!("an answer teter does not read: {e}"))
143                });
144            }
145            Some(Ok(_)) => {}
146            Some(Err(e)) => return Err(io::Error::other(e).into()),
147            None => {
148                return Err(AccountError::Refused(
149                    "the relay closed the connection without an answer".to_owned(),
150                ));
151            }
152        }
153    }
154}
155
156/// The account service's URL at relay `relay`.
157fn account_url(relay: &str) -> String {
158    let host_at = relay.find("://").map_or(0, |at| at + 3);
159    let path_at = relay
160        .get(host_at..)
161        .and_then(|rest| rest.find('/'))
162        .map_or(relay.len(), |at| host_at + at);
163    let (origin, path) = relay.split_at(path_at);
164    let path = path.trim_end_matches('/');
165    let path = ["/backend", "/frontend", PATH]
166        .into_iter()
167        .find_map(|endpoint| path.strip_suffix(endpoint))
168        .unwrap_or(path);
169    format!("{origin}{path}{PATH}")
170}
171
172#[cfg(test)]
173mod tests {
174    use super::account_url;
175
176    #[test]
177    fn the_account_service_is_the_relays_account_path() {
178        for relay in [
179            "wss://relay.example.com",
180            "wss://relay.example.com/",
181            "wss://relay.example.com/backend",
182            "wss://relay.example.com/frontend",
183            "wss://relay.example.com/account",
184        ] {
185            assert_eq!(account_url(relay), "wss://relay.example.com/account");
186        }
187        assert_eq!(account_url("ws://backend"), "ws://backend/account");
188    }
189}