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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Types for the `m.room_key_request` events.

use std::collections::BTreeMap;

use ruma::{OwnedDeviceId, OwnedRoomId, OwnedTransactionId, RoomId};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vodozemac::Curve25519PublicKey;

use super::{EventType, ToDeviceEvent};
use crate::types::{deserialize_curve_key, serialize_curve_key, EventEncryptionAlgorithm};

/// The `m.room_key_request` to-device event.
pub type RoomKeyRequestEvent = ToDeviceEvent<RoomKeyRequestContent>;

impl Clone for RoomKeyRequestEvent {
    fn clone(&self) -> Self {
        Self {
            sender: self.sender.clone(),
            content: self.content.clone(),
            other: self.other.clone(),
        }
    }
}

/// The content for a `m.room_key_request` event.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct RoomKeyRequestContent {
    /// The action that this room key request is carrying.
    #[serde(flatten)]
    pub action: Action,
    /// The ID of the device that is requesting the room key.
    pub requesting_device_id: OwnedDeviceId,
    /// A random string uniquely identifying the request for a key. If the key
    /// is requested multiple times, it should be reused. It should also reused
    /// in order to cancel a request.
    pub request_id: OwnedTransactionId,
}

impl RoomKeyRequestContent {
    /// Create a new content for a `m.room_key_request` event with the action
    /// set to request a room key with the given `RequestedKeyInfo`.
    pub fn new_request(
        info: RequestedKeyInfo,
        requesting_device_id: OwnedDeviceId,
        request_id: OwnedTransactionId,
    ) -> Self {
        Self { action: Action::Request(info), requesting_device_id, request_id }
    }
}

impl EventType for RoomKeyRequestContent {
    const EVENT_TYPE: &'static str = "m.room_key_request";
}

/// Enum describing different actions a room key request event can be carrying.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "action", content = "body")]
pub enum Action {
    /// An action describing a cancellation of a previous room key request.
    #[serde(rename = "request_cancellation")]
    Cancellation,
    /// An action describing a room key request.
    #[serde(rename = "request")]
    Request(RequestedKeyInfo),
}

/// Info about the room key that is being requested.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(try_from = "RequestedKeyInfoHelper")]
pub enum RequestedKeyInfo {
    /// The `m.megolm.v1.aes-sha2` variant of the `m.room_key_request` content.
    MegolmV1AesSha2(MegolmV1AesSha2Content),
    /// The `m.megolm.v2.aes-sha2` variant of the `m.room_key_request` content.
    #[cfg(feature = "experimental-algorithms")]
    MegolmV2AesSha2(MegolmV2AesSha2Content),
    /// An unknown and unsupported variant of the `m.room_key_request`
    /// content.
    Unknown(UnknownRoomKeyRequest),
}

impl RequestedKeyInfo {
    /// Get the algorithm of the room key request content.
    pub fn algorithm(&self) -> EventEncryptionAlgorithm {
        match self {
            RequestedKeyInfo::MegolmV1AesSha2(_) => EventEncryptionAlgorithm::MegolmV1AesSha2,
            #[cfg(feature = "experimental-algorithms")]
            RequestedKeyInfo::MegolmV2AesSha2(_) => EventEncryptionAlgorithm::MegolmV2AesSha2,
            RequestedKeyInfo::Unknown(c) => c.algorithm.to_owned(),
        }
    }
}

impl From<SupportedKeyInfo> for RequestedKeyInfo {
    fn from(s: SupportedKeyInfo) -> Self {
        match s {
            SupportedKeyInfo::MegolmV1AesSha2(c) => Self::MegolmV1AesSha2(c),
            #[cfg(feature = "experimental-algorithms")]
            SupportedKeyInfo::MegolmV2AesSha2(c) => Self::MegolmV2AesSha2(c),
        }
    }
}

impl From<MegolmV1AesSha2Content> for RequestedKeyInfo {
    fn from(c: MegolmV1AesSha2Content) -> Self {
        Self::MegolmV1AesSha2(c)
    }
}

#[cfg(feature = "experimental-algorithms")]
impl From<MegolmV2AesSha2Content> for RequestedKeyInfo {
    fn from(c: MegolmV2AesSha2Content) -> Self {
        Self::MegolmV2AesSha2(c)
    }
}

/// Info about the room key that is being requested.
///
/// This is similar to [`RequestedKeyInfo`] but it contains only supported
/// algorithms.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(try_from = "RequestedKeyInfo", into = "RequestedKeyInfo")]
pub enum SupportedKeyInfo {
    /// The `m.megolm.v1.aes-sha2` variant of the `m.room_key_request` content.
    MegolmV1AesSha2(MegolmV1AesSha2Content),
    /// The `m.megolm.v2.aes-sha2` variant of the `m.room_key_request` content.
    #[cfg(feature = "experimental-algorithms")]
    MegolmV2AesSha2(MegolmV2AesSha2Content),
}

impl SupportedKeyInfo {
    /// Get the algorithm of the room key request content.
    pub fn algorithm(&self) -> EventEncryptionAlgorithm {
        match self {
            Self::MegolmV1AesSha2(_) => EventEncryptionAlgorithm::MegolmV1AesSha2,
            #[cfg(feature = "experimental-algorithms")]
            Self::MegolmV2AesSha2(_) => EventEncryptionAlgorithm::MegolmV2AesSha2,
        }
    }

    /// Get the room ID where the room key is used.
    pub fn room_id(&self) -> &RoomId {
        match self {
            Self::MegolmV1AesSha2(c) => &c.room_id,
            #[cfg(feature = "experimental-algorithms")]
            Self::MegolmV2AesSha2(c) => &c.room_id,
        }
    }

    /// Get the unique ID of the room key.
    pub fn session_id(&self) -> &str {
        match self {
            Self::MegolmV1AesSha2(c) => &c.session_id,
            #[cfg(feature = "experimental-algorithms")]
            Self::MegolmV2AesSha2(c) => &c.session_id,
        }
    }
}

impl TryFrom<RequestedKeyInfo> for SupportedKeyInfo {
    type Error = &'static str;

    fn try_from(value: RequestedKeyInfo) -> Result<Self, Self::Error> {
        match value {
            RequestedKeyInfo::MegolmV1AesSha2(c) => Ok(Self::MegolmV1AesSha2(c)),
            #[cfg(feature = "experimental-algorithms")]
            RequestedKeyInfo::MegolmV2AesSha2(c) => Ok(Self::MegolmV2AesSha2(c)),
            RequestedKeyInfo::Unknown(_) => Err("Unsupported algorithm for a room key request"),
        }
    }
}

impl From<MegolmV1AesSha2Content> for SupportedKeyInfo {
    fn from(c: MegolmV1AesSha2Content) -> Self {
        Self::MegolmV1AesSha2(c)
    }
}

#[cfg(feature = "experimental-algorithms")]
impl From<MegolmV2AesSha2Content> for SupportedKeyInfo {
    fn from(c: MegolmV2AesSha2Content) -> Self {
        Self::MegolmV2AesSha2(c)
    }
}

/// The content for a `m.megolm.v2.aes-sha2` `m.room_key_request` event.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct MegolmV1AesSha2Content {
    /// The room where the key is used.
    pub room_id: OwnedRoomId,

    /// The Curve25519 key of the device which initiated the session originally.
    #[serde(deserialize_with = "deserialize_curve_key", serialize_with = "serialize_curve_key")]
    pub sender_key: Curve25519PublicKey,

    /// The ID of the session that the key is for.
    pub session_id: String,
}

/// The content for a `m.megolm.v1.aes-sha2` `m.room_key_request` event.
#[cfg(feature = "experimental-algorithms")]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct MegolmV2AesSha2Content {
    /// The room where the key is used.
    pub room_id: OwnedRoomId,

    /// The ID of the session that the key is for.
    pub session_id: String,
}

/// An unknown and unsupported `m.room_key_request` algorithm.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct UnknownRoomKeyRequest {
    /// The algorithm of the unknown room key request.
    pub algorithm: EventEncryptionAlgorithm,

    /// The other data of the unknown room key request.
    #[serde(flatten)]
    other: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct RequestedKeyInfoHelper {
    pub algorithm: EventEncryptionAlgorithm,
    #[serde(flatten)]
    other: Value,
}

impl Serialize for RequestedKeyInfo {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let other = match self {
            Self::MegolmV1AesSha2(r) => {
                serde_json::to_value(r).map_err(serde::ser::Error::custom)?
            }
            #[cfg(feature = "experimental-algorithms")]
            Self::MegolmV2AesSha2(r) => {
                serde_json::to_value(r).map_err(serde::ser::Error::custom)?
            }
            Self::Unknown(r) => {
                serde_json::to_value(r.other.clone()).map_err(serde::ser::Error::custom)?
            }
        };

        let helper = RequestedKeyInfoHelper { algorithm: self.algorithm(), other };

        helper.serialize(serializer)
    }
}

impl TryFrom<RequestedKeyInfoHelper> for RequestedKeyInfo {
    type Error = serde_json::Error;

    fn try_from(value: RequestedKeyInfoHelper) -> Result<Self, Self::Error> {
        Ok(match value.algorithm {
            EventEncryptionAlgorithm::MegolmV1AesSha2 => {
                Self::MegolmV1AesSha2(serde_json::from_value(value.other)?)
            }
            #[cfg(feature = "experimental-algorithms")]
            EventEncryptionAlgorithm::MegolmV2AesSha2 => {
                Self::MegolmV2AesSha2(serde_json::from_value(value.other)?)
            }
            _ => Self::Unknown(UnknownRoomKeyRequest {
                algorithm: value.algorithm,
                other: serde_json::from_value(value.other)?,
            }),
        })
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use serde_json::{json, Value};

    use super::{Action, RequestedKeyInfo, RoomKeyRequestEvent};

    pub fn json() -> Value {
        json!({
            "sender": "@alice:example.org",
            "content": {
                "action": "request",
                "body": {
                    "algorithm": "m.megolm.v1.aes-sha2",
                    "room_id": "!Cuyf34gef24t:localhost",
                    "sender_key": "RF3s+E7RkTQTGF2d8Deol0FkQvgII2aJDf3/Jp5mxVU",
                    "session_id": "X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ"
                },
                "request_id": "1495474790150.19",
                "requesting_device_id": "RJYKSTBOIE"
            },
            "type": "m.room_key_request"
        })
    }

    pub fn json_cancellation() -> Value {
        json!({
            "sender": "@alice:example.org",
            "content": {
                "action": "request_cancellation",
                "request_id": "1495474790150.19",
                "requesting_device_id": "RJYKSTBOIE"
            },
            "type": "m.room_key_request"
        })
    }

    #[cfg(feature = "experimental-algorithms")]
    pub fn json_megolm_v2() -> Value {
        json!({
            "sender": "@alice:example.org",
            "content": {
                "action": "request",
                "body": {
                    "algorithm": "m.megolm.v2.aes-sha2",
                    "room_id": "!Cuyf34gef24t:localhost",
                    "session_id": "X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ"
                },
                "request_id": "1495474790150.19",
                "requesting_device_id": "RJYKSTBOIE"
            },
            "type": "m.room_key_request"
        })
    }

    #[test]
    fn deserialization() -> Result<(), serde_json::Error> {
        let json = json();
        let event: RoomKeyRequestEvent = serde_json::from_value(json.clone())?;

        assert_matches!(
            event.content.action,
            Action::Request(RequestedKeyInfo::MegolmV1AesSha2(_))
        );
        let serialized = serde_json::to_value(event)?;
        assert_eq!(json, serialized);

        let json = json_cancellation();
        let event: RoomKeyRequestEvent = serde_json::from_value(json.clone())?;

        assert_matches!(event.content.action, Action::Cancellation);
        let serialized = serde_json::to_value(event)?;
        assert_eq!(json, serialized);

        Ok(())
    }

    #[test]
    #[cfg(feature = "experimental-algorithms")]
    fn deserialization_megolm_v2() -> Result<(), serde_json::Error> {
        let json = json_megolm_v2();
        let event: RoomKeyRequestEvent = serde_json::from_value(json.clone())?;

        assert_matches!(
            event.content.action,
            Action::Request(RequestedKeyInfo::MegolmV2AesSha2(_))
        );

        let serialized = serde_json::to_value(event)?;
        assert_eq!(json, serialized);

        Ok(())
    }
}