ruma_events/room/
encrypted.rs

1//! Types for the [`m.room.encrypted`] event.
2//!
3//! [`m.room.encrypted`]: https://spec.matrix.org/latest/client-server-api/#mroomencrypted
4
5use std::{borrow::Cow, collections::BTreeMap};
6
7use js_int::UInt;
8use ruma_common::{serde::JsonObject, OwnedDeviceId, OwnedEventId};
9use ruma_macros::EventContent;
10use serde::{Deserialize, Serialize};
11
12use super::message;
13use crate::relation::{Annotation, CustomRelation, InReplyTo, Reference, RelationType, Thread};
14
15mod relation_serde;
16#[cfg(feature = "unstable-msc3414")]
17pub mod unstable_state;
18
19/// The content of an `m.room.encrypted` event.
20#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
21#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
22#[ruma_event(type = "m.room.encrypted", kind = MessageLike)]
23pub struct RoomEncryptedEventContent {
24    /// Algorithm-specific fields.
25    #[serde(flatten)]
26    pub scheme: EncryptedEventScheme,
27
28    /// Information about related events.
29    #[serde(rename = "m.relates_to", skip_serializing_if = "Option::is_none")]
30    pub relates_to: Option<Relation>,
31}
32
33impl RoomEncryptedEventContent {
34    /// Creates a new `RoomEncryptedEventContent` with the given scheme and relation.
35    pub fn new(scheme: EncryptedEventScheme, relates_to: Option<Relation>) -> Self {
36        Self { scheme, relates_to }
37    }
38}
39
40impl From<EncryptedEventScheme> for RoomEncryptedEventContent {
41    fn from(scheme: EncryptedEventScheme) -> Self {
42        Self { scheme, relates_to: None }
43    }
44}
45
46/// The to-device content of an `m.room.encrypted` event.
47#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
48#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
49#[ruma_event(type = "m.room.encrypted", kind = ToDevice)]
50pub struct ToDeviceRoomEncryptedEventContent {
51    /// Algorithm-specific fields.
52    #[serde(flatten)]
53    pub scheme: EncryptedEventScheme,
54}
55
56impl ToDeviceRoomEncryptedEventContent {
57    /// Creates a new `ToDeviceRoomEncryptedEventContent` with the given scheme.
58    pub fn new(scheme: EncryptedEventScheme) -> Self {
59        Self { scheme }
60    }
61}
62
63impl From<EncryptedEventScheme> for ToDeviceRoomEncryptedEventContent {
64    fn from(scheme: EncryptedEventScheme) -> Self {
65        Self { scheme }
66    }
67}
68
69/// The encryption scheme for `RoomEncryptedEventContent`.
70#[derive(Clone, Debug, Deserialize, Serialize)]
71#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
72#[serde(tag = "algorithm")]
73pub enum EncryptedEventScheme {
74    /// An event encrypted with `m.olm.v1.curve25519-aes-sha2`.
75    #[serde(rename = "m.olm.v1.curve25519-aes-sha2")]
76    OlmV1Curve25519AesSha2(OlmV1Curve25519AesSha2Content),
77
78    /// An event encrypted with `m.megolm.v1.aes-sha2`.
79    #[serde(rename = "m.megolm.v1.aes-sha2")]
80    MegolmV1AesSha2(MegolmV1AesSha2Content),
81}
82
83/// Relationship information about an encrypted event.
84///
85/// Outside of the encrypted payload to support server aggregation.
86#[derive(Clone, Debug)]
87#[allow(clippy::manual_non_exhaustive)]
88#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
89pub enum Relation {
90    /// An `m.in_reply_to` relation indicating that the event is a reply to another event.
91    Reply {
92        /// Information about another message being replied to.
93        in_reply_to: InReplyTo,
94    },
95
96    /// An event that replaces another event.
97    Replacement(Replacement),
98
99    /// A reference to another event.
100    Reference(Reference),
101
102    /// An annotation to an event.
103    Annotation(Annotation),
104
105    /// An event that belongs to a thread.
106    Thread(Thread),
107
108    #[doc(hidden)]
109    _Custom(CustomRelation),
110}
111
112impl Relation {
113    /// The type of this `Relation`.
114    ///
115    /// Returns an `Option` because the `Reply` relation does not have a`rel_type` field.
116    pub fn rel_type(&self) -> Option<RelationType> {
117        match self {
118            Relation::Reply { .. } => None,
119            Relation::Replacement(_) => Some(RelationType::Replacement),
120            Relation::Reference(_) => Some(RelationType::Reference),
121            Relation::Annotation(_) => Some(RelationType::Annotation),
122            Relation::Thread(_) => Some(RelationType::Thread),
123            Relation::_Custom(c) => c.rel_type(),
124        }
125    }
126
127    /// The associated data.
128    ///
129    /// The returned JSON object holds the contents of `m.relates_to`, including `rel_type` and
130    /// `event_id` if present, but not things like `m.new_content` for `m.replace` relations that
131    /// live next to `m.relates_to`.
132    ///
133    /// Prefer to use the public variants of `Relation` where possible; this method is meant to
134    /// be used for custom relations only.
135    pub fn data(&self) -> Cow<'_, JsonObject> {
136        if let Relation::_Custom(CustomRelation(data)) = self {
137            Cow::Borrowed(data)
138        } else {
139            Cow::Owned(self.serialize_data())
140        }
141    }
142}
143
144impl<C> From<message::Relation<C>> for Relation {
145    fn from(rel: message::Relation<C>) -> Self {
146        match rel {
147            message::Relation::Reply { in_reply_to } => Self::Reply { in_reply_to },
148            message::Relation::Replacement(re) => {
149                Self::Replacement(Replacement { event_id: re.event_id })
150            }
151            message::Relation::Thread(t) => Self::Thread(Thread {
152                event_id: t.event_id,
153                in_reply_to: t.in_reply_to,
154                is_falling_back: t.is_falling_back,
155            }),
156            message::Relation::_Custom(c) => Self::_Custom(c),
157        }
158    }
159}
160
161/// The event this relation belongs to [replaces another event].
162///
163/// In contrast to [`relation::Replacement`](crate::relation::Replacement), this
164/// struct doesn't store the new content, since that is part of the encrypted content of an
165/// `m.room.encrypted` events.
166///
167/// [replaces another event]: https://spec.matrix.org/latest/client-server-api/#event-replacements
168#[derive(Clone, Debug, Deserialize, Serialize)]
169#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
170#[serde(tag = "rel_type", rename = "m.replace")]
171pub struct Replacement {
172    /// The ID of the event being replaced.
173    pub event_id: OwnedEventId,
174}
175
176impl Replacement {
177    /// Creates a new `Replacement` with the given event ID.
178    pub fn new(event_id: OwnedEventId) -> Self {
179        Self { event_id }
180    }
181}
182
183/// The content of an `m.room.encrypted` event using the `m.olm.v1.curve25519-aes-sha2` algorithm.
184#[derive(Clone, Debug, Serialize, Deserialize)]
185#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
186pub struct OlmV1Curve25519AesSha2Content {
187    /// A map from the recipient Curve25519 identity key to ciphertext information.
188    pub ciphertext: BTreeMap<String, CiphertextInfo>,
189
190    /// The Curve25519 key of the sender.
191    pub sender_key: String,
192}
193
194impl OlmV1Curve25519AesSha2Content {
195    /// Creates a new `OlmV1Curve25519AesSha2Content` with the given ciphertext and sender key.
196    pub fn new(ciphertext: BTreeMap<String, CiphertextInfo>, sender_key: String) -> Self {
197        Self { ciphertext, sender_key }
198    }
199}
200
201/// Ciphertext information holding the ciphertext and message type.
202///
203/// Used for messages encrypted with the `m.olm.v1.curve25519-aes-sha2` algorithm.
204#[derive(Clone, Debug, Deserialize, Serialize)]
205#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
206pub struct CiphertextInfo {
207    /// The encrypted payload.
208    pub body: String,
209
210    /// The Olm message type.
211    #[serde(rename = "type")]
212    pub message_type: UInt,
213}
214
215impl CiphertextInfo {
216    /// Creates a new `CiphertextInfo` with the given body and type.
217    pub fn new(body: String, message_type: UInt) -> Self {
218        Self { body, message_type }
219    }
220}
221
222/// The content of an `m.room.encrypted` event using the `m.megolm.v1.aes-sha2` algorithm.
223///
224/// To create an instance of this type, first create a `MegolmV1AesSha2ContentInit` and convert it
225/// via `MegolmV1AesSha2Content::from` / `.into()`.
226#[derive(Clone, Debug, Serialize, Deserialize)]
227#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
228pub struct MegolmV1AesSha2Content {
229    /// The encrypted content of the event.
230    pub ciphertext: String,
231
232    /// The Curve25519 key of the sender.
233    #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub sender_key: Option<String>,
236
237    /// The ID of the sending device.
238    #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub device_id: Option<OwnedDeviceId>,
241
242    /// The ID of the session used to encrypt the message.
243    pub session_id: String,
244}
245
246/// Mandatory initial set of fields of `MegolmV1AesSha2Content`.
247///
248/// This struct will not be updated even if additional fields are added to `MegolmV1AesSha2Content`
249/// in a new (non-breaking) release of the Matrix specification.
250#[derive(Debug)]
251#[allow(clippy::exhaustive_structs)]
252pub struct MegolmV1AesSha2ContentInit {
253    /// The encrypted content of the event.
254    pub ciphertext: String,
255
256    /// The Curve25519 key of the sender.
257    pub sender_key: String,
258
259    /// The ID of the sending device.
260    pub device_id: OwnedDeviceId,
261
262    /// The ID of the session used to encrypt the message.
263    pub session_id: String,
264}
265
266impl From<MegolmV1AesSha2ContentInit> for MegolmV1AesSha2Content {
267    /// Creates a new `MegolmV1AesSha2Content` from the given init struct.
268    fn from(init: MegolmV1AesSha2ContentInit) -> Self {
269        let MegolmV1AesSha2ContentInit { ciphertext, sender_key, device_id, session_id } = init;
270        #[allow(deprecated)]
271        Self { ciphertext, sender_key: Some(sender_key), device_id: Some(device_id), session_id }
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use assert_matches2::assert_matches;
278    use js_int::uint;
279    use ruma_common::{device_id, owned_event_id, serde::Raw};
280    use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
281
282    use super::{
283        EncryptedEventScheme, InReplyTo, MegolmV1AesSha2ContentInit, Relation,
284        RoomEncryptedEventContent,
285    };
286
287    #[test]
288    fn serialization() {
289        let key_verification_start_content = RoomEncryptedEventContent {
290            scheme: EncryptedEventScheme::MegolmV1AesSha2(
291                MegolmV1AesSha2ContentInit {
292                    ciphertext: "ciphertext".into(),
293                    sender_key: "sender_key".into(),
294                    device_id: "device_id".into(),
295                    session_id: "session_id".into(),
296                }
297                .into(),
298            ),
299            relates_to: Some(Relation::Reply {
300                in_reply_to: InReplyTo { event_id: owned_event_id!("$h29iv0s8:example.com") },
301            }),
302        };
303
304        let json_data = json!({
305            "algorithm": "m.megolm.v1.aes-sha2",
306            "ciphertext": "ciphertext",
307            "sender_key": "sender_key",
308            "device_id": "device_id",
309            "session_id": "session_id",
310            "m.relates_to": {
311                "m.in_reply_to": {
312                    "event_id": "$h29iv0s8:example.com"
313                }
314            },
315        });
316
317        assert_eq!(to_json_value(&key_verification_start_content).unwrap(), json_data);
318    }
319
320    #[test]
321    #[allow(deprecated)]
322    fn deserialization() {
323        let json_data = json!({
324            "algorithm": "m.megolm.v1.aes-sha2",
325            "ciphertext": "ciphertext",
326            "sender_key": "sender_key",
327            "device_id": "device_id",
328            "session_id": "session_id",
329            "m.relates_to": {
330                "m.in_reply_to": {
331                    "event_id": "$h29iv0s8:example.com"
332                }
333            },
334        });
335
336        let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
337
338        assert_matches!(content.scheme, EncryptedEventScheme::MegolmV1AesSha2(scheme));
339        assert_eq!(scheme.ciphertext, "ciphertext");
340        assert_eq!(scheme.sender_key.as_deref(), Some("sender_key"));
341        assert_eq!(scheme.device_id.as_deref(), Some(device_id!("device_id")));
342        assert_eq!(scheme.session_id, "session_id");
343
344        assert_matches!(content.relates_to, Some(Relation::Reply { in_reply_to }));
345        assert_eq!(in_reply_to.event_id, "$h29iv0s8:example.com");
346    }
347
348    #[test]
349    fn deserialization_olm() {
350        let json_data = json!({
351            "sender_key": "test_key",
352            "ciphertext": {
353                "test_curve_key": {
354                    "body": "encrypted_body",
355                    "type": 1
356                }
357            },
358            "algorithm": "m.olm.v1.curve25519-aes-sha2"
359        });
360        let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
361
362        assert_matches!(content.scheme, EncryptedEventScheme::OlmV1Curve25519AesSha2(c));
363        assert_eq!(c.sender_key, "test_key");
364        assert_eq!(c.ciphertext.len(), 1);
365        assert_eq!(c.ciphertext["test_curve_key"].body, "encrypted_body");
366        assert_eq!(c.ciphertext["test_curve_key"].message_type, uint!(1));
367
368        assert_matches!(content.relates_to, None);
369    }
370
371    #[test]
372    fn deserialization_failure() {
373        from_json_value::<Raw<RoomEncryptedEventContent>>(
374            json!({ "algorithm": "m.megolm.v1.aes-sha2" }),
375        )
376        .unwrap()
377        .deserialize()
378        .unwrap_err();
379    }
380}