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        login: Option<String>,
47    ) -> io::Result<Self> {
48        if machine_key.is_empty() {
49            return Err(io::Error::new(
50                io::ErrorKind::Unsupported,
51                "the relay gives no machine key (too old for commands)",
52            ));
53        }
54        let mut random = [0_u8; 16];
55        getrandom::fill(&mut random).map_err(io::Error::other)?;
56        let channel = format!("{CHANNEL_PREFIX}{}", teter_common::account::hex(&random));
57        let mut relay = crate::connect(url, ca_cert).await?;
58        send(&mut relay, Message::auth_as(token, login)).await?;
59        send(
60            &mut relay,
61            Message::session_join(session).on_channel(Some(channel)),
62        )
63        .await?;
64        loop {
65            let msg = recv(&mut relay)
66                .await?
67                .ok_or_else(|| io::Error::other("the relay closed before the join"))?;
68            if msg.msg_type == MessageType::SessionJoined {
69                if let Some(MessagePayload::SessionCreated { protocol, .. }) = &msg.payload {
70                    teter_common::check_relay_protocol(*protocol).map_err(io::Error::other)?;
71                }
72                break;
73            }
74            if msg.msg_type == MessageType::SessionError {
75                return Err(io::Error::other(format!(
76                    "the relay refused the join: {}",
77                    reason(&msg.payload)
78                )));
79            }
80        }
81        Ok(Self {
82            relay,
83            session,
84            machine,
85            machine_key,
86        })
87    }
88
89    /// Sends `frame` to the machine.
90    async fn put(&mut self, frame: &ToMachine) -> io::Result<()> {
91        let data = serde_json::to_vec(frame).map_err(io::Error::other)?;
92        send(&mut self.relay, Message::input(self.session, data)).await
93    }
94
95    /// The machine's next frame, within [`ANSWER_TIMEOUT`].
96    async fn take(&mut self) -> io::Result<FromMachine> {
97        tokio::time::timeout(ANSWER_TIMEOUT, self.next_frame())
98            .await
99            .map_err(|_elapsed| {
100                io::Error::new(io::ErrorKind::TimedOut, "the machine did not answer")
101            })?
102    }
103
104    /// The machine's next frame.
105    async fn next_frame(&mut self) -> io::Result<FromMachine> {
106        loop {
107            let msg = recv(&mut self.relay)
108                .await?
109                .ok_or_else(|| io::Error::other("the relay closed the command channel"))?;
110            if let (MessageType::Output, Some(MessagePayload::OutputData { data })) =
111                (&msg.msg_type, &msg.payload)
112            {
113                if data.len() > MAX_FRAME {
114                    return Err(io::Error::other("a command frame too large"));
115                }
116                return serde_json::from_slice(data).map_err(io::Error::other);
117            }
118            if msg.msg_type == MessageType::SessionError {
119                return Err(io::Error::other(format!(
120                    "the relay ended the command channel: {}",
121                    reason(&msg.payload)
122                )));
123            }
124        }
125    }
126
127    /// Asks for a challenge, checked against the machine's key.
128    ///
129    /// # Errors
130    ///
131    /// A lost channel, or a challenge the machine did not sign.
132    pub async fn challenge(&mut self) -> io::Result<Challenge> {
133        self.put(&ToMachine::Hello).await?;
134        match self.take().await? {
135            FromMachine::Challenge {
136                nonce,
137                key,
138                signature,
139            } => check_challenge(&self.machine, &self.machine_key, nonce, key, &signature)
140                .ok_or_else(|| io::Error::other("the challenge is not signed by the machine")),
141            FromMachine::Refused { reason } => Err(io::Error::other(reason)),
142            FromMachine::Reply { .. } => Err(io::Error::other("a reply where a challenge was due")),
143        }
144    }
145
146    /// Sends a sealed command and waits for the machine's answer: the
147    /// outcome opened with `account`, or the refusal.
148    ///
149    /// # Errors
150    ///
151    /// A lost channel, a refusal, or a reply that does not open.
152    pub async fn send_sealed(
153        &mut self,
154        account: &AccountKeys,
155        nonce: &[u8],
156        sealed: Vec<u8>,
157    ) -> io::Result<Outcome> {
158        self.put(&ToMachine::Command { sealed }).await?;
159        match self.take().await? {
160            FromMachine::Reply { sealed, signature } => open_reply(
161                account,
162                &self.machine,
163                &self.machine_key,
164                nonce,
165                &sealed,
166                &signature,
167            ),
168            FromMachine::Refused { reason } => Err(io::Error::new(
169                io::ErrorKind::PermissionDenied,
170                format!("the machine refused the command: {reason}"),
171            )),
172            FromMachine::Challenge { .. } => {
173                Err(io::Error::other("a challenge where a reply was due"))
174            }
175        }
176    }
177
178    /// Runs `command` on the machine, signed by `account`.
179    ///
180    /// # Errors
181    ///
182    /// As [`Channel::challenge`] and [`Channel::send_sealed`].
183    pub async fn run(&mut self, account: &AccountKeys, command: Command) -> io::Result<Outcome> {
184        let challenge = self.challenge().await?;
185        let sealed = seal_command(account, &self.machine, &challenge, command)?;
186        self.send_sealed(account, &challenge.nonce, sealed).await
187    }
188}
189
190/// The reason a relay's error carries.
191fn reason(payload: &Option<MessagePayload>) -> &str {
192    match payload {
193        Some(MessagePayload::ErrorReason { reason }) => reason,
194        _ => "no reason given",
195    }
196}