use std::io;
use std::path::Path;
use futures_util::{SinkExt, StreamExt};
use teter_common::account::{AccountReply, AccountRequest, PATH};
use tokio_tungstenite::tungstenite::Message as Frame;
pub use teter_core::account::*;
#[derive(Debug)]
pub struct MachineUnknown(String);
impl MachineUnknown {
pub fn is(error: &io::Error) -> bool {
error.get_ref().is_some_and(|inner| inner.is::<Self>())
}
}
impl std::fmt::Display for MachineUnknown {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for MachineUnknown {}
pub fn machine_refusal(reason: &str) -> io::Error {
let message = format!("the relay refused this machine: {reason}");
if reason == teter_common::account::MACHINE_UNKNOWN {
io::Error::new(io::ErrorKind::PermissionDenied, MachineUnknown(message))
} else {
io::Error::other(message)
}
}
pub async fn authenticate_machine<S>(
ws: &mut S,
id: &str,
key: &MachineKey,
) -> io::Result<Vec<teter_common::account::KeyRotation>>
where
S: futures_util::Sink<Frame, Error = tokio_tungstenite::tungstenite::Error>
+ futures_util::Stream<Item = Result<Frame, tokio_tungstenite::tungstenite::Error>>
+ Unpin,
{
use teter_common::{Message, MessagePayload, MessageType};
let hello = Message {
msg_type: MessageType::MachineHello,
session: None,
channel: None,
payload: Some(MessagePayload::MachineId {
machine: id.to_owned(),
protocol: teter_common::PROTOCOL,
}),
};
crate::send(ws, hello).await?;
let challenge = crate::recv(ws)
.await?
.ok_or_else(|| io::Error::other("the relay closed the connection before its challenge"))?;
let (nonce, rotations) = match (challenge.msg_type, challenge.payload) {
(
MessageType::Challenge,
Some(MessagePayload::Challenge {
nonce,
protocol,
rotations,
}),
) => {
teter_common::check_relay_protocol(protocol).map_err(io::Error::other)?;
(nonce, rotations)
}
(MessageType::SessionError, payload) => {
let reason = match payload {
Some(MessagePayload::ErrorReason { reason }) => reason,
_ => "no reason given".to_owned(),
};
return Err(machine_refusal(&reason));
}
(other, _) => {
return Err(io::Error::other(format!(
"the relay answered the machine's hello with {}",
other.to_str()
)));
}
};
let proof = Message {
msg_type: MessageType::MachineProof,
session: None,
channel: None,
payload: Some(MessagePayload::Signature {
signature: key.sign(&teter_common::machine_proof_message(&nonce, id)),
}),
};
crate::send(ws, proof).await?;
Ok(rotations)
}
pub async fn request(
relay: &str,
ca_cert: Option<&Path>,
request: &AccountRequest,
) -> Result<AccountReply, AccountError> {
let mut ws = crate::connect(&account_url(relay), ca_cert).await?;
let text = serde_json::to_string(request).map_err(io::Error::other)?;
ws.send(Frame::text(text)).await.map_err(io::Error::other)?;
loop {
match ws.next().await {
Some(Ok(Frame::Text(text))) => {
drop(ws.close(None).await);
return serde_json::from_str(&text).map_err(|e| {
AccountError::Refused(format!("an answer teter does not read: {e}"))
});
}
Some(Ok(_)) => {}
Some(Err(e)) => return Err(io::Error::other(e).into()),
None => {
return Err(AccountError::Refused(
"the relay closed the connection without an answer".to_owned(),
));
}
}
}
}
pub async fn request_signed(
relay: &str,
ca_cert: Option<&Path>,
request: &AccountRequest,
device: &DeviceKey,
) -> Result<AccountReply, AccountError> {
if request.login_token().is_none() {
return self::request(relay, ca_cert, request).await;
}
let at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(io::Error::other)?
.as_secs();
let at = i64::try_from(at).map_err(io::Error::other)?;
let proven = prove(device, request, at)?;
self::request(relay, ca_cert, &proven).await
}
fn account_url(relay: &str) -> String {
let host_at = relay.find("://").map_or(0, |at| at + 3);
let path_at = relay
.get(host_at..)
.and_then(|rest| rest.find('/'))
.map_or(relay.len(), |at| host_at + at);
let (origin, path) = relay.split_at(path_at);
let path = path.trim_end_matches('/');
let path = ["/backend", "/frontend", PATH]
.into_iter()
.find_map(|endpoint| path.strip_suffix(endpoint))
.unwrap_or(path);
format!("{origin}{path}{PATH}")
}
#[cfg(test)]
mod tests {
use super::account_url;
#[test]
fn the_account_service_is_the_relays_account_path() {
for relay in [
"wss://relay.example.com",
"wss://relay.example.com/",
"wss://relay.example.com/backend",
"wss://relay.example.com/frontend",
"wss://relay.example.com/account",
] {
assert_eq!(account_url(relay), "wss://relay.example.com/account");
}
assert_eq!(account_url("ws://backend"), "ws://backend/account");
}
}