Skip to main content

matrix_sdk_crypto/gossiping/
mod.rs

1// Copyright 2020 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod machine;
16
17use std::{
18    collections::{BTreeMap, BTreeSet},
19    sync::Arc,
20};
21
22pub(crate) use machine::GossipMachine;
23use matrix_sdk_common::locks::RwLock as StdRwLock;
24use ruma::{
25    DeviceId, OwnedDeviceId, OwnedTransactionId, OwnedUserId, TransactionId, UserId,
26    events::{
27        AnyToDeviceEventContent, ToDeviceEventType,
28        room_key_request::{Action, ToDeviceRoomKeyRequestEventContent},
29        secret::request::{
30            RequestAction, SecretName, SecretRequestAction,
31            ToDeviceSecretRequestEvent as SecretRequestEvent,
32            ToDeviceSecretRequestEventContent as SecretRequestEventContent,
33        },
34    },
35    serde::Raw,
36    to_device::DeviceIdOrAllDevices,
37};
38use serde::{Deserialize, Serialize};
39
40use crate::{
41    Device,
42    types::{
43        events::{
44            olm_v1::DecryptedSecretSendEvent,
45            room_key_request::{RoomKeyRequestContent, RoomKeyRequestEvent, SupportedKeyInfo},
46        },
47        requests::{OutgoingRequest, ToDeviceRequest},
48    },
49};
50
51/// Struct containing a `m.secret.send` event and its accompanying info.
52///
53/// This struct is created only iff the following three things are true:
54///
55/// 1. We requested the secret.
56/// 2. The secret was received over an encrypted channel.
57/// 3. The secret it was received from one ouf our own verified devices.
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct GossippedSecret {
60    /// The name of the secret.
61    pub secret_name: SecretName,
62    /// The [`GossipRequest`] that has requested the secret.
63    pub gossip_request: GossipRequest,
64    /// The `m.secret.send` event containing the actual secret.
65    pub event: DecryptedSecretSendEvent,
66}
67
68/// An error describing why a key share request won't be honored.
69#[cfg(feature = "automatic-room-key-forwarding")]
70#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
71pub enum KeyForwardDecision {
72    /// The key request is from a device that we don't own, we're only sharing
73    /// sessions that we know the requesting device already was supposed to get.
74    #[error("can't find an active outbound group session")]
75    MissingOutboundSession,
76    /// The key request is from a device that we don't own and the device wasn't
77    /// meant to receive the session in the original key share.
78    #[error("outbound session wasn't shared with the requesting device")]
79    OutboundSessionNotShared,
80    /// The key request is from a device we own, yet we don't trust it.
81    #[error("requesting device isn't trusted")]
82    UntrustedDevice,
83    /// The outbound session was shared with the device, but the device either
84    /// accidentally or maliciously changed their curve25519 sender key.
85    #[error("the device has changed their curve25519 sender key")]
86    ChangedSenderKey,
87}
88
89/// A struct describing an outgoing key request.
90#[derive(Debug, Clone, Serialize, Deserialize)]
91pub struct GossipRequest {
92    /// The user we requested the secret from
93    pub request_recipient: OwnedUserId,
94    /// The unique id of the secret request.
95    pub request_id: OwnedTransactionId,
96    /// The info of the requested secret.
97    pub info: SecretInfo,
98    /// Has the request been sent out.
99    pub sent_out: bool,
100}
101
102/// An enum over the various secret request types we can have.
103#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
104pub enum SecretInfo {
105    /// Info for the `m.room_key_request` variant
106    KeyRequest(SupportedKeyInfo),
107    /// Info for the `m.secret.request` variant
108    SecretRequest(SecretName),
109}
110
111impl SecretInfo {
112    /// Serialize `SecretInfo` into `String` for usage as database keys and
113    /// comparison.
114    pub fn as_key(&self) -> String {
115        match &self {
116            SecretInfo::KeyRequest(info) => {
117                format!("keyRequest:{}:{}:{}", info.room_id(), info.session_id(), info.algorithm())
118            }
119            SecretInfo::SecretRequest(sname) => format!("secretName:{sname}"),
120        }
121    }
122}
123
124impl<T> From<T> for SecretInfo
125where
126    T: Into<SupportedKeyInfo>,
127{
128    fn from(v: T) -> Self {
129        Self::KeyRequest(v.into())
130    }
131}
132
133impl From<SecretName> for SecretInfo {
134    fn from(i: SecretName) -> Self {
135        Self::SecretRequest(i)
136    }
137}
138
139impl GossipRequest {
140    /// Create an outgoing secret request for the given secret.
141    pub(crate) fn from_secret_name(own_user_id: OwnedUserId, secret_name: SecretName) -> Self {
142        Self {
143            request_recipient: own_user_id,
144            request_id: TransactionId::new(),
145            info: secret_name.into(),
146            sent_out: false,
147        }
148    }
149
150    fn request_type(&self) -> &str {
151        match &self.info {
152            SecretInfo::KeyRequest(_) => "m.room_key_request",
153            SecretInfo::SecretRequest(s) => s.as_ref(),
154        }
155    }
156
157    fn to_request(&self, own_device_id: &DeviceId) -> OutgoingRequest {
158        let request = match &self.info {
159            SecretInfo::KeyRequest(r) => {
160                let content = RoomKeyRequestContent::new_request(
161                    r.clone().into(),
162                    own_device_id.to_owned(),
163                    self.request_id.to_owned(),
164                );
165                let content = Raw::new(&content)
166                    .expect("We can always serialize a room key request info")
167                    .cast();
168
169                ToDeviceRequest::with_id_raw(
170                    &self.request_recipient,
171                    DeviceIdOrAllDevices::AllDevices,
172                    content,
173                    ToDeviceEventType::RoomKeyRequest,
174                    self.request_id.clone(),
175                )
176            }
177            SecretInfo::SecretRequest(s) => {
178                let content =
179                    AnyToDeviceEventContent::SecretRequest(SecretRequestEventContent::new(
180                        RequestAction::Request(SecretRequestAction::new(s.clone())),
181                        own_device_id.to_owned(),
182                        self.request_id.clone(),
183                    ));
184
185                ToDeviceRequest::with_id(
186                    &self.request_recipient,
187                    DeviceIdOrAllDevices::AllDevices,
188                    &content,
189                    self.request_id.clone(),
190                )
191            }
192        };
193
194        OutgoingRequest { request_id: request.txn_id.clone(), request: Arc::new(request.into()) }
195    }
196
197    fn to_cancellation(&self, own_device_id: &DeviceId) -> OutgoingRequest {
198        let content = match self.info {
199            SecretInfo::KeyRequest(_) => {
200                AnyToDeviceEventContent::RoomKeyRequest(ToDeviceRoomKeyRequestEventContent::new(
201                    Action::CancelRequest,
202                    None,
203                    own_device_id.to_owned(),
204                    self.request_id.clone(),
205                ))
206            }
207            SecretInfo::SecretRequest(_) => {
208                AnyToDeviceEventContent::SecretRequest(SecretRequestEventContent::new(
209                    RequestAction::RequestCancellation,
210                    own_device_id.to_owned(),
211                    self.request_id.clone(),
212                ))
213            }
214        };
215
216        let request = ToDeviceRequest::with_id(
217            &self.request_recipient,
218            DeviceIdOrAllDevices::AllDevices,
219            &content,
220            TransactionId::new(),
221        );
222
223        OutgoingRequest { request_id: request.txn_id.clone(), request: Arc::new(request.into()) }
224    }
225}
226
227impl PartialEq for GossipRequest {
228    fn eq(&self, other: &Self) -> bool {
229        let is_info_equal = match (&self.info, &other.info) {
230            (SecretInfo::KeyRequest(first), SecretInfo::KeyRequest(second)) => first == second,
231            (SecretInfo::SecretRequest(first), SecretInfo::SecretRequest(second)) => {
232                first == second
233            }
234            (SecretInfo::KeyRequest(_), SecretInfo::SecretRequest(_))
235            | (SecretInfo::SecretRequest(_), SecretInfo::KeyRequest(_)) => false,
236        };
237
238        self.request_id == other.request_id && is_info_equal
239    }
240}
241
242#[derive(Debug)]
243enum RequestEvent {
244    KeyShare(RoomKeyRequestEvent),
245    Secret(SecretRequestEvent),
246}
247
248impl From<SecretRequestEvent> for RequestEvent {
249    fn from(e: SecretRequestEvent) -> Self {
250        Self::Secret(e)
251    }
252}
253
254impl From<RoomKeyRequestEvent> for RequestEvent {
255    fn from(e: RoomKeyRequestEvent) -> Self {
256        Self::KeyShare(e)
257    }
258}
259
260impl RequestEvent {
261    fn to_request_info(&self) -> RequestInfo {
262        RequestInfo::new(
263            self.sender().to_owned(),
264            self.requesting_device_id().into(),
265            self.request_id().to_owned(),
266        )
267    }
268
269    fn sender(&self) -> &UserId {
270        match self {
271            RequestEvent::KeyShare(e) => &e.sender,
272            RequestEvent::Secret(e) => &e.sender,
273        }
274    }
275
276    fn requesting_device_id(&self) -> &DeviceId {
277        match self {
278            RequestEvent::KeyShare(e) => &e.content.requesting_device_id,
279            RequestEvent::Secret(e) => &e.content.requesting_device_id,
280        }
281    }
282
283    fn request_id(&self) -> &TransactionId {
284        match self {
285            RequestEvent::KeyShare(e) => &e.content.request_id,
286            RequestEvent::Secret(e) => &e.content.request_id,
287        }
288    }
289}
290
291#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
292struct RequestInfo {
293    sender: OwnedUserId,
294    requesting_device_id: OwnedDeviceId,
295    request_id: OwnedTransactionId,
296}
297
298impl RequestInfo {
299    fn new(
300        sender: OwnedUserId,
301        requesting_device_id: OwnedDeviceId,
302        request_id: OwnedTransactionId,
303    ) -> Self {
304        Self { sender, requesting_device_id, request_id }
305    }
306}
307
308/// A queue where we store room key requests that we want to serve but the
309/// device that requested the key doesn't share an Olm session with us.
310#[derive(Clone, Debug, Default)]
311struct WaitQueue {
312    inner: Arc<StdRwLock<WaitQueueInner>>,
313}
314
315#[derive(Debug, Default)]
316struct WaitQueueInner {
317    requests_waiting_for_session: BTreeMap<RequestInfo, RequestEvent>,
318    requests_ids_waiting: BTreeMap<(OwnedUserId, OwnedDeviceId), BTreeSet<OwnedTransactionId>>,
319}
320
321impl WaitQueue {
322    fn new() -> Self {
323        Self::default()
324    }
325
326    #[cfg(all(test, feature = "automatic-room-key-forwarding"))]
327    fn is_empty(&self) -> bool {
328        let read_guard = self.inner.read();
329        read_guard.requests_ids_waiting.is_empty()
330            && read_guard.requests_waiting_for_session.is_empty()
331    }
332
333    fn insert(&self, device: &Device, event: RequestEvent) {
334        let request_id = event.request_id().to_owned();
335        let requests_waiting_key = RequestInfo::new(
336            device.user_id().to_owned(),
337            device.device_id().into(),
338            request_id.clone(),
339        );
340        let ids_waiting_key = (device.user_id().to_owned(), device.device_id().into());
341
342        let mut write_guard = self.inner.write();
343        write_guard.requests_waiting_for_session.insert(requests_waiting_key, event);
344        write_guard.requests_ids_waiting.entry(ids_waiting_key).or_default().insert(request_id);
345    }
346
347    fn remove(&self, user_id: &UserId, device_id: &DeviceId) -> Vec<(RequestInfo, RequestEvent)> {
348        let mut write_guard = self.inner.write();
349
350        write_guard
351            .requests_ids_waiting
352            .remove(&(user_id.to_owned(), device_id.into()))
353            .map(|request_ids| {
354                request_ids
355                    .iter()
356                    .filter_map(|id| {
357                        let key =
358                            RequestInfo::new(user_id.to_owned(), device_id.into(), id.to_owned());
359                        write_guard.requests_waiting_for_session.remove_entry(&key)
360                    })
361                    .collect()
362            })
363            .unwrap_or_default()
364    }
365}