matrix_sdk_crypto/types/
device_keys.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2020 Karl Linderhed.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use std::collections::BTreeMap;

use js_option::JsOption;
use ruma::{
    serde::Raw, DeviceKeyAlgorithm, DeviceKeyId, OwnedDeviceId, OwnedDeviceKeyId, OwnedUserId,
};
use serde::{Deserialize, Serialize};
use serde_json::{value::to_raw_value, Value};
use vodozemac::{Curve25519PublicKey, Ed25519PublicKey};

use super::{EventEncryptionAlgorithm, Signatures};

/// Represents a Matrix cryptographic device
///
/// This struct models a Matrix cryptographic device involved in end-to-end
/// encrypted messaging, specifically for to-device communication. It aligns
/// with the [`DeviceKeys` struct][device_keys_spec] in the Matrix
/// Specification, encapsulating essential elements such as the public device
/// identity keys.
///
/// [device_keys_spec]: https://spec.matrix.org/v1.10/client-server-api/#_matrixclientv3keysupload_devicekeys
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(try_from = "DeviceKeyHelper", into = "DeviceKeyHelper")]
pub struct DeviceKeys {
    /// The ID of the user the device belongs to.
    ///
    /// Must match the user ID used when logging in.
    pub user_id: OwnedUserId,

    /// The ID of the device these keys belong to.
    ///
    /// Must match the device ID used when logging in.
    pub device_id: OwnedDeviceId,

    /// The encryption algorithms supported by this device.
    pub algorithms: Vec<EventEncryptionAlgorithm>,

    /// Public identity keys.
    pub keys: BTreeMap<OwnedDeviceKeyId, DeviceKey>,

    /// Signatures for the device key object.
    pub signatures: Signatures,

    /// Whether the device is a dehydrated device or not
    #[serde(default, skip_serializing_if = "JsOption::is_undefined")]
    pub dehydrated: JsOption<bool>,

    /// Additional data added to the device key information by intermediate
    /// servers, and not covered by the signatures.
    #[serde(default, skip_serializing_if = "UnsignedDeviceInfo::is_empty")]
    pub unsigned: UnsignedDeviceInfo,

    #[serde(flatten)]
    other: BTreeMap<String, Value>,
}

impl DeviceKeys {
    /// Creates a new `DeviceKeys` from the given user id, device ID,
    /// algorithms, keys and signatures.
    pub fn new(
        user_id: OwnedUserId,
        device_id: OwnedDeviceId,
        algorithms: Vec<EventEncryptionAlgorithm>,
        keys: BTreeMap<OwnedDeviceKeyId, DeviceKey>,
        signatures: Signatures,
    ) -> Self {
        Self {
            user_id,
            device_id,
            algorithms,
            keys,
            signatures,
            dehydrated: JsOption::Undefined,
            unsigned: Default::default(),
            other: BTreeMap::new(),
        }
    }

    /// Serialize the device keys key into a Raw version.
    pub fn to_raw<T>(&self) -> Raw<T> {
        Raw::from_json(to_raw_value(&self).expect("Couldn't serialize device keys"))
    }

    /// Get the key of the given key algorithm belonging to this device.
    pub fn get_key(&self, algorithm: DeviceKeyAlgorithm) -> Option<&DeviceKey> {
        self.keys.get(&DeviceKeyId::from_parts(algorithm, &self.device_id))
    }

    /// Get the Curve25519 key of the given device.
    pub fn curve25519_key(&self) -> Option<Curve25519PublicKey> {
        self.get_key(DeviceKeyAlgorithm::Curve25519).and_then(|k| {
            if let DeviceKey::Curve25519(k) = k {
                Some(*k)
            } else {
                None
            }
        })
    }

    /// Get the Ed25519 key of the given device.
    pub fn ed25519_key(&self) -> Option<Ed25519PublicKey> {
        self.get_key(DeviceKeyAlgorithm::Ed25519).and_then(|k| {
            if let DeviceKey::Ed25519(k) = k {
                Some(*k)
            } else {
                None
            }
        })
    }
}

/// Additional data added to device key information by intermediate servers.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub struct UnsignedDeviceInfo {
    /// The display name which the user set on the device.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_display_name: Option<String>,

    #[serde(flatten)]
    other: BTreeMap<String, Value>,
}

impl UnsignedDeviceInfo {
    /// Creates an empty `UnsignedDeviceInfo`.
    pub fn new() -> Self {
        Default::default()
    }

    /// Checks whether all fields are empty / `None`.
    pub fn is_empty(&self) -> bool {
        self.device_display_name.is_none()
    }
}

/// An enum over the different key types a device can have.
///
/// Currently devices have a curve25519 and ed25519 keypair. The keys transport
/// format is a base64 encoded string, any unknown key type will be left as such
/// a string.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeviceKey {
    /// The curve25519 device key.
    Curve25519(Curve25519PublicKey),
    /// The ed25519 device key.
    Ed25519(Ed25519PublicKey),
    /// An unknown device key.
    Unknown(String),
}

impl DeviceKey {
    /// Convert the `DeviceKey` into a base64 encoded string.
    pub fn to_base64(&self) -> String {
        match self {
            DeviceKey::Curve25519(k) => k.to_base64(),
            DeviceKey::Ed25519(k) => k.to_base64(),
            DeviceKey::Unknown(k) => k.to_owned(),
        }
    }
}

impl From<Curve25519PublicKey> for DeviceKey {
    fn from(val: Curve25519PublicKey) -> Self {
        DeviceKey::Curve25519(val)
    }
}

impl From<Ed25519PublicKey> for DeviceKey {
    fn from(val: Ed25519PublicKey) -> Self {
        DeviceKey::Ed25519(val)
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct DeviceKeyHelper {
    pub user_id: OwnedUserId,
    pub device_id: OwnedDeviceId,
    pub algorithms: Vec<EventEncryptionAlgorithm>,
    pub keys: BTreeMap<OwnedDeviceKeyId, String>,
    #[serde(default, skip_serializing_if = "JsOption::is_undefined")]
    pub dehydrated: JsOption<bool>,
    pub signatures: Signatures,
    #[serde(default, skip_serializing_if = "UnsignedDeviceInfo::is_empty")]
    pub unsigned: UnsignedDeviceInfo,
    #[serde(flatten)]
    other: BTreeMap<String, Value>,
}

impl TryFrom<DeviceKeyHelper> for DeviceKeys {
    type Error = vodozemac::KeyError;

    fn try_from(value: DeviceKeyHelper) -> Result<Self, Self::Error> {
        let keys: Result<BTreeMap<OwnedDeviceKeyId, DeviceKey>, vodozemac::KeyError> = value
            .keys
            .into_iter()
            .map(|(k, v)| {
                let key = match k.algorithm() {
                    DeviceKeyAlgorithm::Ed25519 => {
                        DeviceKey::Ed25519(Ed25519PublicKey::from_base64(&v)?)
                    }
                    DeviceKeyAlgorithm::Curve25519 => {
                        DeviceKey::Curve25519(Curve25519PublicKey::from_base64(&v)?)
                    }
                    _ => DeviceKey::Unknown(v),
                };

                Ok((k, key))
            })
            .collect();

        Ok(Self {
            user_id: value.user_id,
            device_id: value.device_id,
            algorithms: value.algorithms,
            keys: keys?,
            dehydrated: value.dehydrated,
            signatures: value.signatures,
            unsigned: value.unsigned,
            other: value.other,
        })
    }
}

impl From<DeviceKeys> for DeviceKeyHelper {
    fn from(value: DeviceKeys) -> Self {
        let keys: BTreeMap<OwnedDeviceKeyId, String> =
            value.keys.into_iter().map(|(k, v)| (k, v.to_base64())).collect();

        Self {
            user_id: value.user_id,
            device_id: value.device_id,
            algorithms: value.algorithms,
            keys,
            dehydrated: value.dehydrated,
            signatures: value.signatures,
            unsigned: value.unsigned,
            other: value.other,
        }
    }
}

#[cfg(test)]
mod tests {
    use ruma::{device_id, user_id};
    use serde_json::json;

    use super::DeviceKeys;

    #[test]
    fn serialization() {
        let json = json!({
          "algorithms": vec![
              "m.olm.v1.curve25519-aes-sha2",
              "m.megolm.v1.aes-sha2"
          ],
          "device_id": "BNYQQWUMXO",
          "user_id": "@example:localhost",
          "keys": {
              "curve25519:BNYQQWUMXO": "xfgbLIC5WAl1OIkpOzoxpCe8FsRDT6nch7NQsOb15nc",
              "ed25519:BNYQQWUMXO": "2/5LWJMow5zhJqakV88SIc7q/1pa8fmkfgAzx72w9G4"
          },
          "signatures": {
              "@example:localhost": {
                  "ed25519:BNYQQWUMXO": "kTwMrbsLJJM/uFGOj/oqlCaRuw7i9p/6eGrTlXjo8UJMCFAetoyWzoMcF35vSe4S6FTx8RJmqX6rM7ep53MHDQ"
              }
          },
          "unsigned": {
              "device_display_name": "Alice's mobile phone",
              "other_data": "other_value"
          },

          "other_data": "other_value"
        });

        let device_keys: DeviceKeys =
            serde_json::from_value(json.clone()).expect("Can't deserialize device keys");

        assert_eq!(device_keys.user_id, user_id!("@example:localhost"));
        assert_eq!(&device_keys.device_id, device_id!("BNYQQWUMXO"));

        let serialized = serde_json::to_value(device_keys).expect("Can't reserialize device keys");

        assert_eq!(json, serialized);
    }
}