1use 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#[derive(Debug)]
19pub struct MachineUnknown(String);
20
21impl MachineUnknown {
22 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
36pub 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
47pub 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 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 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
122pub 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
156fn 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}