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
156pub async fn request_signed(
164 relay: &str,
165 ca_cert: Option<&Path>,
166 request: &AccountRequest,
167 device: &DeviceKey,
168) -> Result<AccountReply, AccountError> {
169 if request.login_token().is_none() {
170 return self::request(relay, ca_cert, request).await;
171 }
172 let at = std::time::SystemTime::now()
173 .duration_since(std::time::UNIX_EPOCH)
174 .map_err(io::Error::other)?
175 .as_secs();
176 let at = i64::try_from(at).map_err(io::Error::other)?;
177 let proven = prove(device, request, at)?;
178 self::request(relay, ca_cert, &proven).await
179}
180
181fn account_url(relay: &str) -> String {
183 let host_at = relay.find("://").map_or(0, |at| at + 3);
184 let path_at = relay
185 .get(host_at..)
186 .and_then(|rest| rest.find('/'))
187 .map_or(relay.len(), |at| host_at + at);
188 let (origin, path) = relay.split_at(path_at);
189 let path = path.trim_end_matches('/');
190 let path = ["/backend", "/frontend", PATH]
191 .into_iter()
192 .find_map(|endpoint| path.strip_suffix(endpoint))
193 .unwrap_or(path);
194 format!("{origin}{path}{PATH}")
195}
196
197#[cfg(test)]
198mod tests {
199 use super::account_url;
200
201 #[test]
202 fn the_account_service_is_the_relays_account_path() {
203 for relay in [
204 "wss://relay.example.com",
205 "wss://relay.example.com/",
206 "wss://relay.example.com/backend",
207 "wss://relay.example.com/frontend",
208 "wss://relay.example.com/account",
209 ] {
210 assert_eq!(account_url(relay), "wss://relay.example.com/account");
211 }
212 assert_eq!(account_url("ws://backend"), "ws://backend/account");
213 }
214}