Skip to main content

teter_client/
command.rs

1//! The device's side of commands to a machine (#88): see
2//! [`teter_common::command`]. Split in steps so a caller (or a test) can
3//! hold a challenge, a sealed command and the channel apart.
4
5use std::io;
6use std::path::Path;
7
8use teter_common::command::{CHANNEL_PREFIX, Command, FromMachine, MAX_FRAME, Outcome, ToMachine};
9use teter_common::{Message, MessagePayload, MessageType, SessionId};
10
11pub use teter_core::command::{Challenge, check_challenge, open_reply, seal_command};
12
13use crate::account::AccountKeys;
14use crate::{Relay, recv, send};
15
16/// How long the device waits for each answer of the machine: past what a
17/// command that ends a session may take on the machine (reaching its socket,
18/// then waiting for its process to go: 35 s), with room for the relay.
19pub const ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
20
21/// A command channel to one machine, joined on its relay session.
22pub struct Channel {
23    relay: Relay,
24    session: SessionId,
25    /// The machine's ID.
26    pub machine: String,
27    /// The machine's public key, which signs its challenges.
28    machine_key: Vec<u8>,
29}
30
31impl Channel {
32    /// Joins relay session `session` with `token` on a fresh command channel
33    /// (`url` is the relay's `/frontend` endpoint), for machine `machine`
34    /// whose public key is `machine_key`.
35    ///
36    /// # Errors
37    ///
38    /// When the relay cannot be reached or refuses the join.
39    pub async fn open(
40        url: &str,
41        ca_cert: Option<&Path>,
42        session: SessionId,
43        token: String,
44        machine: String,
45        machine_key: Vec<u8>,
46    ) -> io::Result<Self> {
47        if machine_key.is_empty() {
48            return Err(io::Error::new(
49                io::ErrorKind::Unsupported,
50                "the relay gives no machine key (too old for commands)",
51            ));
52        }
53        let mut random = [0_u8; 16];
54        getrandom::fill(&mut random).map_err(io::Error::other)?;
55        let channel = format!("{CHANNEL_PREFIX}{}", teter_common::account::hex(&random));
56        let mut relay = crate::connect(url, ca_cert).await?;
57        send(&mut relay, Message::auth(token)).await?;
58        send(
59            &mut relay,
60            Message::session_join(session).on_channel(Some(channel)),
61        )
62        .await?;
63        loop {
64            let msg = recv(&mut relay)
65                .await?
66                .ok_or_else(|| io::Error::other("the relay closed before the join"))?;
67            if msg.msg_type == MessageType::SessionJoined {
68                if let Some(MessagePayload::SessionCreated { protocol, .. }) = &msg.payload {
69                    teter_common::check_relay_protocol(*protocol).map_err(io::Error::other)?;
70                }
71                break;
72            }
73            if msg.msg_type == MessageType::SessionError {
74                return Err(io::Error::other(format!(
75                    "the relay refused the join: {}",
76                    reason(&msg.payload)
77                )));
78            }
79        }
80        Ok(Self {
81            relay,
82            session,
83            machine,
84            machine_key,
85        })
86    }
87
88    /// Sends `frame` to the machine.
89    async fn put(&mut self, frame: &ToMachine) -> io::Result<()> {
90        let data = serde_json::to_vec(frame).map_err(io::Error::other)?;
91        send(&mut self.relay, Message::input(self.session, data)).await
92    }
93
94    /// The machine's next frame, within [`ANSWER_TIMEOUT`].
95    async fn take(&mut self) -> io::Result<FromMachine> {
96        tokio::time::timeout(ANSWER_TIMEOUT, self.next_frame())
97            .await
98            .map_err(|_elapsed| {
99                io::Error::new(io::ErrorKind::TimedOut, "the machine did not answer")
100            })?
101    }
102
103    /// The machine's next frame.
104    async fn next_frame(&mut self) -> io::Result<FromMachine> {
105        loop {
106            let msg = recv(&mut self.relay)
107                .await?
108                .ok_or_else(|| io::Error::other("the relay closed the command channel"))?;
109            if let (MessageType::Output, Some(MessagePayload::OutputData { data })) =
110                (&msg.msg_type, &msg.payload)
111            {
112                if data.len() > MAX_FRAME {
113                    return Err(io::Error::other("a command frame too large"));
114                }
115                return serde_json::from_slice(data).map_err(io::Error::other);
116            }
117            if msg.msg_type == MessageType::SessionError {
118                return Err(io::Error::other(format!(
119                    "the relay ended the command channel: {}",
120                    reason(&msg.payload)
121                )));
122            }
123        }
124    }
125
126    /// Asks for a challenge, checked against the machine's key.
127    ///
128    /// # Errors
129    ///
130    /// A lost channel, or a challenge the machine did not sign.
131    pub async fn challenge(&mut self) -> io::Result<Challenge> {
132        self.put(&ToMachine::Hello).await?;
133        match self.take().await? {
134            FromMachine::Challenge {
135                nonce,
136                key,
137                signature,
138            } => check_challenge(&self.machine, &self.machine_key, nonce, key, &signature)
139                .ok_or_else(|| io::Error::other("the challenge is not signed by the machine")),
140            FromMachine::Refused { reason } => Err(io::Error::other(reason)),
141            FromMachine::Reply { .. } => Err(io::Error::other("a reply where a challenge was due")),
142        }
143    }
144
145    /// Sends a sealed command and waits for the machine's answer: the
146    /// outcome opened with `account`, or the refusal.
147    ///
148    /// # Errors
149    ///
150    /// A lost channel, a refusal, or a reply that does not open.
151    pub async fn send_sealed(
152        &mut self,
153        account: &AccountKeys,
154        nonce: &[u8],
155        sealed: Vec<u8>,
156    ) -> io::Result<Outcome> {
157        self.put(&ToMachine::Command { sealed }).await?;
158        match self.take().await? {
159            FromMachine::Reply { sealed, signature } => open_reply(
160                account,
161                &self.machine,
162                &self.machine_key,
163                nonce,
164                &sealed,
165                &signature,
166            ),
167            FromMachine::Refused { reason } => Err(io::Error::new(
168                io::ErrorKind::PermissionDenied,
169                format!("the machine refused the command: {reason}"),
170            )),
171            FromMachine::Challenge { .. } => {
172                Err(io::Error::other("a challenge where a reply was due"))
173            }
174        }
175    }
176
177    /// Runs `command` on the machine, signed by `account`.
178    ///
179    /// # Errors
180    ///
181    /// As [`Channel::challenge`] and [`Channel::send_sealed`].
182    pub async fn run(&mut self, account: &AccountKeys, command: Command) -> io::Result<Outcome> {
183        let challenge = self.challenge().await?;
184        let sealed = seal_command(account, &self.machine, &challenge, command)?;
185        self.send_sealed(account, &challenge.nonce, sealed).await
186    }
187}
188
189/// The reason a relay's error carries.
190fn reason(payload: &Option<MessagePayload>) -> &str {
191    match payload {
192        Some(MessagePayload::ErrorReason { reason }) => reason,
193        _ => "no reason given",
194    }
195}