matrix_sdk_crypto/store/
types.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
15//! Data types for persistent storage.
16//!
17//! This module defines the data structures used by the crypto store to
18//! represent objects that are persisted in the database.
19
20use std::{
21    collections::{BTreeMap, HashMap, HashSet},
22    time::Duration,
23};
24
25use ruma::{OwnedDeviceId, OwnedRoomId, OwnedUserId};
26use serde::{Deserialize, Serialize};
27use vodozemac::{Curve25519PublicKey, base64_encode};
28use zeroize::{Zeroize, ZeroizeOnDrop};
29
30use super::{DehydrationError, GossipRequest};
31use crate::{
32    Account, Device, DeviceData, GossippedSecret, Session, UserIdentity, UserIdentityData,
33    olm::{
34        InboundGroupSession, OlmMessageHash, OutboundGroupSession, PrivateCrossSigningIdentity,
35        SenderData,
36    },
37    types::{
38        EventEncryptionAlgorithm,
39        events::{
40            room_key_bundle::RoomKeyBundleContent,
41            room_key_withheld::{RoomKeyWithheldContent, RoomKeyWithheldEvent},
42        },
43    },
44};
45
46/// Aggregated changes to be saved in the database.
47///
48/// This is an update version of `Changes` that will replace it as #2624
49/// progresses.
50// If you ever add a field here, make sure to update `Changes::is_empty` too.
51#[derive(Default, Debug)]
52#[allow(missing_docs)]
53pub struct PendingChanges {
54    pub account: Option<Account>,
55}
56
57impl PendingChanges {
58    /// Are there any changes stored or is this an empty `Changes` struct?
59    pub fn is_empty(&self) -> bool {
60        self.account.is_none()
61    }
62}
63
64/// Aggregated changes to be saved in the database.
65// If you ever add a field here, make sure to update `Changes::is_empty` too.
66#[derive(Default, Debug)]
67#[allow(missing_docs)]
68pub struct Changes {
69    pub private_identity: Option<PrivateCrossSigningIdentity>,
70    pub backup_version: Option<String>,
71    pub backup_decryption_key: Option<BackupDecryptionKey>,
72    pub dehydrated_device_pickle_key: Option<DehydratedDeviceKey>,
73    pub sessions: Vec<Session>,
74    pub message_hashes: Vec<OlmMessageHash>,
75    pub inbound_group_sessions: Vec<InboundGroupSession>,
76    pub outbound_group_sessions: Vec<OutboundGroupSession>,
77    pub key_requests: Vec<GossipRequest>,
78    pub identities: IdentityChanges,
79    pub devices: DeviceChanges,
80    /// Stores when a `m.room_key.withheld` is received
81    pub withheld_session_info: BTreeMap<OwnedRoomId, BTreeMap<String, RoomKeyWithheldEntry>>,
82    pub room_settings: HashMap<OwnedRoomId, RoomSettings>,
83    pub secrets: Vec<GossippedSecret>,
84    pub next_batch_token: Option<String>,
85
86    /// Historical room key history bundles that we have received and should
87    /// store.
88    pub received_room_key_bundles: Vec<StoredRoomKeyBundleData>,
89
90    /// The set of rooms for which we have requested all room keys from the
91    /// backup in advance of constructing a room key bundle.
92    pub room_key_backups_fully_downloaded: HashSet<OwnedRoomId>,
93}
94
95/// Information about an [MSC4268] room key bundle.
96///
97/// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
98#[derive(Clone, Debug, Serialize, Deserialize)]
99pub struct StoredRoomKeyBundleData {
100    /// The user that sent us this data.
101    pub sender_user: OwnedUserId,
102
103    /// The [`Curve25519PublicKey`] of the device that sent us this data.
104    pub sender_key: Curve25519PublicKey,
105
106    /// Information about the sender of this data and how much we trust that
107    /// information.
108    pub sender_data: SenderData,
109
110    /// The room key bundle data itself.
111    pub bundle_data: RoomKeyBundleContent,
112}
113
114/// A user for which we are tracking the list of devices.
115#[derive(Clone, Debug, Serialize, Deserialize)]
116pub struct TrackedUser {
117    /// The user ID of the user.
118    pub user_id: OwnedUserId,
119    /// The outdate/dirty flag of the user, remembers if the list of devices for
120    /// the user is considered to be out of date. If the list of devices is
121    /// out of date, a `/keys/query` request should be sent out for this
122    /// user.
123    pub dirty: bool,
124}
125
126impl Changes {
127    /// Are there any changes stored or is this an empty `Changes` struct?
128    pub fn is_empty(&self) -> bool {
129        self.private_identity.is_none()
130            && self.backup_version.is_none()
131            && self.backup_decryption_key.is_none()
132            && self.dehydrated_device_pickle_key.is_none()
133            && self.sessions.is_empty()
134            && self.message_hashes.is_empty()
135            && self.inbound_group_sessions.is_empty()
136            && self.outbound_group_sessions.is_empty()
137            && self.key_requests.is_empty()
138            && self.identities.is_empty()
139            && self.devices.is_empty()
140            && self.withheld_session_info.is_empty()
141            && self.room_settings.is_empty()
142            && self.secrets.is_empty()
143            && self.next_batch_token.is_none()
144            && self.received_room_key_bundles.is_empty()
145    }
146}
147
148/// This struct is used to remember whether an identity has undergone a change
149/// or remains the same as the one we already know about.
150///
151/// When the homeserver informs us of a potential change in a user's identity or
152/// device during a `/sync` response, it triggers a `/keys/query` request from
153/// our side. In response to this query, the server provides a comprehensive
154/// snapshot of all the user's devices and identities.
155///
156/// Our responsibility is to discern whether a device or identity is new,
157/// changed, or unchanged.
158#[derive(Debug, Clone, Default)]
159#[allow(missing_docs)]
160pub struct IdentityChanges {
161    pub new: Vec<UserIdentityData>,
162    pub changed: Vec<UserIdentityData>,
163    pub unchanged: Vec<UserIdentityData>,
164}
165
166impl IdentityChanges {
167    pub(super) fn is_empty(&self) -> bool {
168        self.new.is_empty() && self.changed.is_empty()
169    }
170
171    /// Convert the vectors contained in the [`IdentityChanges`] into
172    /// three maps from user id to user identity (new, updated, unchanged).
173    pub(super) fn into_maps(
174        self,
175    ) -> (
176        BTreeMap<OwnedUserId, UserIdentityData>,
177        BTreeMap<OwnedUserId, UserIdentityData>,
178        BTreeMap<OwnedUserId, UserIdentityData>,
179    ) {
180        let new: BTreeMap<_, _> = self
181            .new
182            .into_iter()
183            .map(|identity| (identity.user_id().to_owned(), identity))
184            .collect();
185
186        let changed: BTreeMap<_, _> = self
187            .changed
188            .into_iter()
189            .map(|identity| (identity.user_id().to_owned(), identity))
190            .collect();
191
192        let unchanged: BTreeMap<_, _> = self
193            .unchanged
194            .into_iter()
195            .map(|identity| (identity.user_id().to_owned(), identity))
196            .collect();
197
198        (new, changed, unchanged)
199    }
200}
201
202#[derive(Debug, Clone, Default)]
203#[allow(missing_docs)]
204pub struct DeviceChanges {
205    pub new: Vec<DeviceData>,
206    pub changed: Vec<DeviceData>,
207    pub deleted: Vec<DeviceData>,
208}
209
210/// Updates about [`Device`]s which got received over the `/keys/query`
211/// endpoint.
212#[derive(Clone, Debug, Default)]
213pub struct DeviceUpdates {
214    /// The list of newly discovered devices.
215    ///
216    /// A device being in this list does not necessarily mean that the device
217    /// was just created, it just means that it's the first time we're
218    /// seeing this device.
219    pub new: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, Device>>,
220    /// The list of changed devices.
221    pub changed: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, Device>>,
222}
223
224/// Updates about [`UserIdentity`]s which got received over the `/keys/query`
225/// endpoint.
226#[derive(Clone, Debug, Default)]
227pub struct IdentityUpdates {
228    /// The list of newly discovered user identities .
229    ///
230    /// A identity being in this list does not necessarily mean that the
231    /// identity was just created, it just means that it's the first time
232    /// we're seeing this identity.
233    pub new: BTreeMap<OwnedUserId, UserIdentity>,
234    /// The list of changed identities.
235    pub changed: BTreeMap<OwnedUserId, UserIdentity>,
236    /// The list of unchanged identities.
237    pub unchanged: BTreeMap<OwnedUserId, UserIdentity>,
238}
239
240/// The private part of a backup key.
241///
242/// The private part of the key is not used on a regular basis. Rather, it is
243/// used only when we need to *recover* the backup.
244///
245/// Typically, this private key is itself encrypted and stored in server-side
246/// secret storage (SSSS), whence it can be retrieved when it is needed for a
247/// recovery operation. Alternatively, the key can be "gossiped" between devices
248/// via "secret sharing".
249#[derive(Clone, Zeroize, ZeroizeOnDrop, Deserialize, Serialize)]
250#[serde(transparent)]
251pub struct BackupDecryptionKey {
252    pub(crate) inner: Box<[u8; BackupDecryptionKey::KEY_SIZE]>,
253}
254
255impl BackupDecryptionKey {
256    /// The number of bytes the decryption key will hold.
257    pub const KEY_SIZE: usize = 32;
258
259    /// Create a new random decryption key.
260    pub fn new() -> Result<Self, rand::Error> {
261        let mut rng = rand::thread_rng();
262
263        let mut key = Box::new([0u8; Self::KEY_SIZE]);
264        rand::Fill::try_fill(key.as_mut_slice(), &mut rng)?;
265
266        Ok(Self { inner: key })
267    }
268
269    /// Export the [`BackupDecryptionKey`] as a base64 encoded string.
270    pub fn to_base64(&self) -> String {
271        base64_encode(self.inner.as_slice())
272    }
273}
274
275#[cfg(not(tarpaulin_include))]
276impl std::fmt::Debug for BackupDecryptionKey {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_tuple("BackupDecryptionKey").field(&"...").finish()
279    }
280}
281
282/// The pickle key used to safely store the dehydrated device pickle.
283///
284/// This input key material will be expanded using HKDF into an AES key, MAC
285/// key, and an initialization vector (IV).
286#[derive(Clone, Zeroize, ZeroizeOnDrop, Deserialize, Serialize)]
287#[serde(transparent)]
288pub struct DehydratedDeviceKey {
289    pub(crate) inner: Box<[u8; DehydratedDeviceKey::KEY_SIZE]>,
290}
291
292impl DehydratedDeviceKey {
293    /// The number of bytes the encryption key will hold.
294    pub const KEY_SIZE: usize = 32;
295
296    /// Generates a new random pickle key.
297    pub fn new() -> Result<Self, rand::Error> {
298        let mut rng = rand::thread_rng();
299
300        let mut key = Box::new([0u8; Self::KEY_SIZE]);
301        rand::Fill::try_fill(key.as_mut_slice(), &mut rng)?;
302
303        Ok(Self { inner: key })
304    }
305
306    /// Creates a new dehydration pickle key from the given slice.
307    ///
308    /// Fail if the slice length is not 32.
309    pub fn from_slice(slice: &[u8]) -> Result<Self, DehydrationError> {
310        if slice.len() == 32 {
311            let mut key = Box::new([0u8; 32]);
312            key.copy_from_slice(slice);
313            Ok(DehydratedDeviceKey { inner: key })
314        } else {
315            Err(DehydrationError::PickleKeyLength(slice.len()))
316        }
317    }
318
319    /// Creates a dehydration pickle key from the given bytes.
320    pub fn from_bytes(raw_key: &[u8; 32]) -> Self {
321        let mut inner = Box::new([0u8; Self::KEY_SIZE]);
322        inner.copy_from_slice(raw_key);
323
324        Self { inner }
325    }
326
327    /// Export the [`DehydratedDeviceKey`] as a base64 encoded string.
328    pub fn to_base64(&self) -> String {
329        base64_encode(self.inner.as_slice())
330    }
331}
332
333impl From<&[u8; 32]> for DehydratedDeviceKey {
334    fn from(value: &[u8; 32]) -> Self {
335        DehydratedDeviceKey { inner: Box::new(*value) }
336    }
337}
338
339impl From<DehydratedDeviceKey> for Vec<u8> {
340    fn from(key: DehydratedDeviceKey) -> Self {
341        key.inner.to_vec()
342    }
343}
344
345#[cfg(not(tarpaulin_include))]
346impl std::fmt::Debug for DehydratedDeviceKey {
347    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
348        f.debug_tuple("DehydratedDeviceKey").field(&"...").finish()
349    }
350}
351
352impl DeviceChanges {
353    /// Merge the given `DeviceChanges` into this instance of `DeviceChanges`.
354    pub fn extend(&mut self, other: DeviceChanges) {
355        self.new.extend(other.new);
356        self.changed.extend(other.changed);
357        self.deleted.extend(other.deleted);
358    }
359
360    /// Are there any changes is this an empty [`DeviceChanges`] struct?
361    pub fn is_empty(&self) -> bool {
362        self.new.is_empty() && self.changed.is_empty() && self.deleted.is_empty()
363    }
364}
365
366/// Struct holding info about how many room keys the store has.
367#[derive(Debug, Clone, Default)]
368pub struct RoomKeyCounts {
369    /// The total number of room keys the store has.
370    pub total: usize,
371    /// The number of backed up room keys the store has.
372    pub backed_up: usize,
373}
374
375/// Stored versions of the backup keys.
376#[derive(Default, Clone, Debug)]
377pub struct BackupKeys {
378    /// The key used to decrypt backed up room keys.
379    pub decryption_key: Option<BackupDecryptionKey>,
380    /// The version that we are using for backups.
381    pub backup_version: Option<String>,
382}
383
384/// A struct containing private cross signing keys that can be backed up or
385/// uploaded to the secret store.
386#[derive(Default, Zeroize, ZeroizeOnDrop)]
387pub struct CrossSigningKeyExport {
388    /// The seed of the master key encoded as unpadded base64.
389    pub master_key: Option<String>,
390    /// The seed of the self signing key encoded as unpadded base64.
391    pub self_signing_key: Option<String>,
392    /// The seed of the user signing key encoded as unpadded base64.
393    pub user_signing_key: Option<String>,
394}
395
396#[cfg(not(tarpaulin_include))]
397impl std::fmt::Debug for CrossSigningKeyExport {
398    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
399        f.debug_struct("CrossSigningKeyExport")
400            .field("master_key", &self.master_key.is_some())
401            .field("self_signing_key", &self.self_signing_key.is_some())
402            .field("user_signing_key", &self.user_signing_key.is_some())
403            .finish_non_exhaustive()
404    }
405}
406
407/// Result type telling us if a `/keys/query` response was expected for a given
408/// user.
409#[derive(Clone, Copy, Debug, PartialEq, Eq)]
410pub(crate) enum UserKeyQueryResult {
411    WasPending,
412    WasNotPending,
413
414    /// A query was pending, but we gave up waiting
415    TimeoutExpired,
416}
417
418/// Room encryption settings which are modified by state events or user options
419#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
420pub struct RoomSettings {
421    /// The encryption algorithm that should be used in the room.
422    pub algorithm: EventEncryptionAlgorithm,
423
424    /// Whether state event encryption is enabled.
425    #[cfg(feature = "experimental-encrypted-state-events")]
426    #[serde(default)]
427    pub encrypt_state_events: bool,
428
429    /// Should untrusted devices receive the room key, or should they be
430    /// excluded from the conversation.
431    pub only_allow_trusted_devices: bool,
432
433    /// The maximum time an encryption session should be used for, before it is
434    /// rotated.
435    pub session_rotation_period: Option<Duration>,
436
437    /// The maximum number of messages an encryption session should be used for,
438    /// before it is rotated.
439    pub session_rotation_period_messages: Option<usize>,
440}
441
442impl Default for RoomSettings {
443    fn default() -> Self {
444        Self {
445            algorithm: EventEncryptionAlgorithm::MegolmV1AesSha2,
446            #[cfg(feature = "experimental-encrypted-state-events")]
447            encrypt_state_events: false,
448            only_allow_trusted_devices: false,
449            session_rotation_period: None,
450            session_rotation_period_messages: None,
451        }
452    }
453}
454
455/// Information on a room key that has been received or imported.
456#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
457pub struct RoomKeyInfo {
458    /// The [messaging algorithm] that this key is used for. Will be one of the
459    /// `m.megolm.*` algorithms.
460    ///
461    /// [messaging algorithm]: https://spec.matrix.org/v1.6/client-server-api/#messaging-algorithms
462    pub algorithm: EventEncryptionAlgorithm,
463
464    /// The room where the key is used.
465    pub room_id: OwnedRoomId,
466
467    /// The Curve25519 key of the device which initiated the session originally.
468    pub sender_key: Curve25519PublicKey,
469
470    /// The ID of the session that the key is for.
471    pub session_id: String,
472}
473
474impl From<&InboundGroupSession> for RoomKeyInfo {
475    fn from(group_session: &InboundGroupSession) -> Self {
476        RoomKeyInfo {
477            algorithm: group_session.algorithm().clone(),
478            room_id: group_session.room_id().to_owned(),
479            sender_key: group_session.sender_key(),
480            session_id: group_session.session_id().to_owned(),
481        }
482    }
483}
484
485/// Information on a room key that has been withheld
486#[derive(Clone, Debug, Deserialize, Serialize)]
487pub struct RoomKeyWithheldInfo {
488    /// The room where the key is used.
489    pub room_id: OwnedRoomId,
490
491    /// The ID of the session that the key is for.
492    pub session_id: String,
493
494    /// The withheld entry from a `m.room_key.withheld` event or [MSC4268] room
495    /// key bundle.
496    ///
497    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
498    pub withheld_event: RoomKeyWithheldEntry,
499}
500
501/// Represents an entry for a withheld room key event, which can be either a
502/// to-device event or a bundle entry.
503#[derive(Clone, Debug, Serialize, Deserialize)]
504pub struct RoomKeyWithheldEntry {
505    /// The user ID responsible for this entry, either from a
506    /// `m.room_key.withheld` to-device event or an [MSC4268] room key bundle.
507    ///
508    /// [MSC4268]: https://github.com/matrix-org/matrix-spec-proposals/pull/4268
509    pub sender: OwnedUserId,
510    /// The content of the entry, which provides details about the reason the
511    /// key was withheld.
512    pub content: RoomKeyWithheldContent,
513}
514
515impl From<RoomKeyWithheldEvent> for RoomKeyWithheldEntry {
516    fn from(value: RoomKeyWithheldEvent) -> Self {
517        Self { sender: value.sender, content: value.content }
518    }
519}
520
521/// Information about a received historic room key bundle.
522///
523/// This struct contains information needed to uniquely identify a room key
524/// bundle. Only a single bundle per sender for a given room is persisted at a
525/// time.
526///
527/// It is used to notify listeners about received room key bundles.
528#[derive(Debug, Clone)]
529pub struct RoomKeyBundleInfo {
530    /// The user ID of the person that sent us the historic room key bundle.
531    pub sender: OwnedUserId,
532
533    /// The [`Curve25519PublicKey`] of the device that sent us this data.
534    pub sender_key: Curve25519PublicKey,
535
536    /// The ID of the room the bundle should be used in.
537    pub room_id: OwnedRoomId,
538}
539
540impl From<&StoredRoomKeyBundleData> for RoomKeyBundleInfo {
541    fn from(value: &StoredRoomKeyBundleData) -> Self {
542        let StoredRoomKeyBundleData { sender_user, sender_data: _, bundle_data, sender_key } =
543            value;
544        let sender_key = *sender_key;
545
546        Self { sender: sender_user.clone(), room_id: bundle_data.room_id.clone(), sender_key }
547    }
548}