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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Types for the *m.key.verification.start* event.

use ruma_identifiers::DeviceId;
use serde::{ser::SerializeStruct, Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{from_value, Value};

use super::{
    HashAlgorithm, KeyAgreementProtocol, MessageAuthenticationCode, ShortAuthenticationString,
    VerificationMethod,
};
use crate::{Event, EventType, InvalidInput, TryFromRaw};

/// Begins an SAS key verification process.
///
/// Typically sent as a to-device event.
#[derive(Clone, Debug, PartialEq)]
pub struct StartEvent {
    /// The event's content.
    pub content: StartEventContent,
}

/// The payload of an *m.key.verification.start* event.
#[derive(Clone, Debug, PartialEq)]
pub enum StartEventContent {
    /// The *m.sas.v1* verification method.
    MSasV1(MSasV1Content),

    /// Additional variants may be added in the future and will not be considered breaking changes
    /// to ruma-events.
    #[doc(hidden)]
    __Nonexhaustive,
}

impl TryFromRaw for StartEvent {
    type Raw = raw::StartEvent;
    type Err = &'static str;

    fn try_from_raw(raw: raw::StartEvent) -> Result<Self, Self::Err> {
        StartEventContent::try_from_raw(raw.content).map(|content| Self { content })
    }
}

impl Serialize for StartEvent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("StartEvent", 2)?;

        state.serialize_field("content", &self.content)?;
        state.serialize_field("type", &self.event_type())?;

        state.end()
    }
}

impl_event!(
    StartEvent,
    StartEventContent,
    EventType::KeyVerificationStart
);

impl TryFromRaw for StartEventContent {
    type Raw = raw::StartEventContent;
    type Err = &'static str;

    fn try_from_raw(raw: raw::StartEventContent) -> Result<Self, Self::Err> {
        match raw {
            raw::StartEventContent::MSasV1(content) => {
                if !content
                    .key_agreement_protocols
                    .contains(&KeyAgreementProtocol::Curve25519)
                {
                    return Err(
                        "`key_agreement_protocols` must contain at least `KeyAgreementProtocol::Curve25519`"
                    );
                }

                if !content.hashes.contains(&HashAlgorithm::Sha256) {
                    return Err("`hashes` must contain at least `HashAlgorithm::Sha256`");
                }

                if !content
                    .message_authentication_codes
                    .contains(&MessageAuthenticationCode::HkdfHmacSha256)
                {
                    return Err(
                        "`message_authentication_codes` must contain at least `MessageAuthenticationCode::HkdfHmacSha256`"
                    );
                }

                if !content
                    .short_authentication_string
                    .contains(&ShortAuthenticationString::Decimal)
                {
                    return Err(
                        "`short_authentication_string` must contain at least `ShortAuthenticationString::Decimal`",
                    );
                }

                Ok(StartEventContent::MSasV1(content))
            }
            raw::StartEventContent::__Nonexhaustive => {
                panic!("__Nonexhaustive enum variant is not intended for use.");
            }
        }
    }
}

impl Serialize for StartEventContent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            StartEventContent::MSasV1(ref content) => content.serialize(serializer),
            _ => panic!("Attempted to serialize __Nonexhaustive variant."),
        }
    }
}

pub(crate) mod raw {
    use super::*;

    /// Begins an SAS key verification process.
    ///
    /// Typically sent as a to-device event.
    #[derive(Clone, Debug, Deserialize, PartialEq)]
    pub struct StartEvent {
        /// The event's content.
        pub content: StartEventContent,
    }

    /// The payload of an *m.key.verification.start* event.
    #[derive(Clone, Debug, PartialEq)]
    pub enum StartEventContent {
        /// The *m.sas.v1* verification method.
        MSasV1(MSasV1Content),

        /// Additional variants may be added in the future and will not be considered breaking changes
        /// to ruma-events.
        #[doc(hidden)]
        __Nonexhaustive,
    }

    impl<'de> Deserialize<'de> for StartEventContent {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            use serde::de::Error as _;

            let value: Value = Deserialize::deserialize(deserializer)?;

            let method_value = match value.get("method") {
                Some(value) => value.clone(),
                None => return Err(D::Error::missing_field("method")),
            };

            let method = match from_value::<VerificationMethod>(method_value) {
                Ok(method) => method,
                Err(error) => return Err(D::Error::custom(error.to_string())),
            };

            match method {
                VerificationMethod::MSasV1 => {
                    let content = match from_value::<MSasV1Content>(value) {
                        Ok(content) => content,
                        Err(error) => return Err(D::Error::custom(error.to_string())),
                    };

                    Ok(StartEventContent::MSasV1(content))
                }
                VerificationMethod::__Nonexhaustive => Err(D::Error::custom(
                    "Attempted to deserialize __Nonexhaustive variant.",
                )),
            }
        }
    }
}

/// The payload of an *m.key.verification.start* event using the *m.sas.v1* method.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct MSasV1Content {
    /// The device ID which is initiating the process.
    pub(crate) from_device: DeviceId,

    /// An opaque identifier for the verification process.
    ///
    /// Must be unique with respect to the devices involved. Must be the same as the
    /// `transaction_id` given in the *m.key.verification.request* if this process is originating
    /// from a request.
    pub(crate) transaction_id: String,

    /// The key agreement protocols the sending device understands.
    ///
    /// Must include at least `curve25519`.
    pub(crate) key_agreement_protocols: Vec<KeyAgreementProtocol>,

    /// The hash methods the sending device understands.
    ///
    /// Must include at least `sha256`.
    pub(crate) hashes: Vec<HashAlgorithm>,

    /// The message authentication codes that the sending device understands.
    ///
    /// Must include at least `hkdf-hmac-sha256`.
    pub(crate) message_authentication_codes: Vec<MessageAuthenticationCode>,

    /// The SAS methods the sending device (and the sending device's user) understands.
    ///
    /// Must include at least `decimal`. Optionally can include `emoji`.
    pub(crate) short_authentication_string: Vec<ShortAuthenticationString>,
}

/// Options for creating an `MSasV1Content` with `MSasV1Content::new`.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct MSasV1ContentOptions {
    /// The device ID which is initiating the process.
    pub from_device: DeviceId,

    /// An opaque identifier for the verification process.
    ///
    /// Must be unique with respect to the devices involved. Must be the same as the
    /// `transaction_id` given in the *m.key.verification.request* if this process is originating
    /// from a request.
    pub transaction_id: String,

    /// The key agreement protocols the sending device understands.
    ///
    /// Must include at least `curve25519`.
    pub key_agreement_protocols: Vec<KeyAgreementProtocol>,

    /// The hash methods the sending device understands.
    ///
    /// Must include at least `sha256`.
    pub hashes: Vec<HashAlgorithm>,

    /// The message authentication codes that the sending device understands.
    ///
    /// Must include at least `hkdf-hmac-sha256`.
    pub message_authentication_codes: Vec<MessageAuthenticationCode>,

    /// The SAS methods the sending device (and the sending device's user) understands.
    ///
    /// Must include at least `decimal`. Optionally can include `emoji`.
    pub short_authentication_string: Vec<ShortAuthenticationString>,
}

impl MSasV1Content {
    /// Create a new `MSasV1Content` with the given values.
    ///
    /// # Errors
    ///
    /// `InvalidInput` will be returned in the following cases:
    ///
    /// * `key_agreement_protocols` does not include `KeyAgreementProtocol::Curve25519`.
    /// * `hashes` does not include `HashAlgorithm::Sha256`.
    /// * `message_authentication_codes` does not include
    /// `MessageAuthenticationCode::HkdfHmacSha256`.
    /// * `short_authentication_string` does not include `ShortAuthenticationString::Decimal`.
    pub fn new(options: MSasV1ContentOptions) -> Result<Self, InvalidInput> {
        if !options
            .key_agreement_protocols
            .contains(&KeyAgreementProtocol::Curve25519)
        {
            return Err(InvalidInput("`key_agreement_protocols` must contain at least `KeyAgreementProtocol::Curve25519`".to_string()));
        }

        if !options.hashes.contains(&HashAlgorithm::Sha256) {
            return Err(InvalidInput(
                "`hashes` must contain at least `HashAlgorithm::Sha256`".to_string(),
            ));
        }

        if !options
            .message_authentication_codes
            .contains(&MessageAuthenticationCode::HkdfHmacSha256)
        {
            return Err(InvalidInput("`message_authentication_codes` must contain at least `MessageAuthenticationCode::HkdfHmacSha256`".to_string()));
        }

        if !options
            .short_authentication_string
            .contains(&ShortAuthenticationString::Decimal)
        {
            return Err(InvalidInput("`short_authentication_string` must contain at least `ShortAuthenticationString::Decimal`".to_string()));
        }

        Ok(Self {
            from_device: options.from_device,
            transaction_id: options.transaction_id,
            key_agreement_protocols: options.key_agreement_protocols,
            hashes: options.hashes,
            message_authentication_codes: options.message_authentication_codes,
            short_authentication_string: options.short_authentication_string,
        })
    }
}

impl Serialize for MSasV1Content {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("MSasV1Content", 2)?;

        state.serialize_field("from_device", &self.from_device)?;
        state.serialize_field("transaction_id", &self.transaction_id)?;
        state.serialize_field("method", "m.sas.v1")?;
        state.serialize_field("key_agreement_protocols", &self.key_agreement_protocols)?;
        state.serialize_field("hashes", &self.hashes)?;
        state.serialize_field(
            "message_authentication_codes",
            &self.message_authentication_codes,
        )?;
        state.serialize_field(
            "short_authentication_string",
            &self.short_authentication_string,
        )?;

        state.end()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::to_string;

    use super::{
        HashAlgorithm, KeyAgreementProtocol, MSasV1Content, MSasV1ContentOptions,
        MessageAuthenticationCode, ShortAuthenticationString, StartEvent, StartEventContent,
    };
    use crate::EventResult;

    #[test]
    fn invalid_m_sas_v1_content_missing_required_key_agreement_protocols() {
        let error = MSasV1Content::new(MSasV1ContentOptions {
            from_device: "123".to_string(),
            transaction_id: "456".to_string(),
            hashes: vec![HashAlgorithm::Sha256],
            key_agreement_protocols: vec![],
            message_authentication_codes: vec![MessageAuthenticationCode::HkdfHmacSha256],
            short_authentication_string: vec![ShortAuthenticationString::Decimal],
        })
        .err()
        .unwrap();

        assert!(error.to_string().contains("key_agreement_protocols"));
    }

    #[test]
    fn invalid_m_sas_v1_content_missing_required_hashes() {
        let error = MSasV1Content::new(MSasV1ContentOptions {
            from_device: "123".to_string(),
            transaction_id: "456".to_string(),
            hashes: vec![],
            key_agreement_protocols: vec![KeyAgreementProtocol::Curve25519],
            message_authentication_codes: vec![MessageAuthenticationCode::HkdfHmacSha256],
            short_authentication_string: vec![ShortAuthenticationString::Decimal],
        })
        .err()
        .unwrap();

        assert!(error.to_string().contains("hashes"));
    }

    #[test]
    fn invalid_m_sas_v1_content_missing_required_message_authentication_codes() {
        let error = MSasV1Content::new(MSasV1ContentOptions {
            from_device: "123".to_string(),
            transaction_id: "456".to_string(),
            hashes: vec![HashAlgorithm::Sha256],
            key_agreement_protocols: vec![KeyAgreementProtocol::Curve25519],
            message_authentication_codes: vec![],
            short_authentication_string: vec![ShortAuthenticationString::Decimal],
        })
        .err()
        .unwrap();

        assert!(error.to_string().contains("message_authentication_codes"));
    }

    #[test]
    fn invalid_m_sas_v1_content_missing_required_short_authentication_string() {
        let error = MSasV1Content::new(MSasV1ContentOptions {
            from_device: "123".to_string(),
            transaction_id: "456".to_string(),
            hashes: vec![HashAlgorithm::Sha256],
            key_agreement_protocols: vec![KeyAgreementProtocol::Curve25519],
            message_authentication_codes: vec![MessageAuthenticationCode::HkdfHmacSha256],
            short_authentication_string: vec![],
        })
        .err()
        .unwrap();

        assert!(error.to_string().contains("short_authentication_string"));
    }

    #[test]
    fn serialization() {
        let key_verification_start_content = StartEventContent::MSasV1(
            MSasV1Content::new(MSasV1ContentOptions {
                from_device: "123".to_string(),
                transaction_id: "456".to_string(),
                hashes: vec![HashAlgorithm::Sha256],
                key_agreement_protocols: vec![KeyAgreementProtocol::Curve25519],
                message_authentication_codes: vec![MessageAuthenticationCode::HkdfHmacSha256],
                short_authentication_string: vec![ShortAuthenticationString::Decimal],
            })
            .unwrap(),
        );

        let key_verification_start = StartEvent {
            content: key_verification_start_content,
        };

        assert_eq!(
            to_string(&key_verification_start).unwrap(),
            r#"{"content":{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]},"type":"m.key.verification.start"}"#
        );
    }

    #[test]
    fn deserialization() {
        let key_verification_start_content = StartEventContent::MSasV1(
            MSasV1Content::new(MSasV1ContentOptions {
                from_device: "123".to_string(),
                transaction_id: "456".to_string(),
                hashes: vec![HashAlgorithm::Sha256],
                key_agreement_protocols: vec![KeyAgreementProtocol::Curve25519],
                message_authentication_codes: vec![MessageAuthenticationCode::HkdfHmacSha256],
                short_authentication_string: vec![ShortAuthenticationString::Decimal],
            })
            .unwrap(),
        );

        // Deserialize the content struct separately to verify `TryFromRaw` is implemented for it.
        assert_eq!(
            serde_json::from_str::<EventResult<StartEventContent>>(
                r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","hashes":["sha256"],"key_agreement_protocols":["curve25519"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]}"#
            )
                .unwrap()
                .into_result()
                .unwrap(),
            key_verification_start_content
        );

        let key_verification_start = StartEvent {
            content: key_verification_start_content,
        };

        assert_eq!(
            serde_json::from_str::<EventResult<StartEvent>>(
                r#"{"content":{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]},"type":"m.key.verification.start"}"#
            )
                .unwrap()
                .into_result()
                .unwrap(),
            key_verification_start
        )
    }

    #[test]
    fn deserialization_failure() {
        // Ensure that invalid JSON  creates a `serde_json::Error` and not `InvalidEvent`
        assert!(serde_json::from_str::<EventResult<StartEventContent>>("{").is_err());
    }

    #[test]
    fn deserialization_structure_mismatch() {
        // Missing several required fields.
        let error =
            serde_json::from_str::<EventResult<StartEventContent>>(r#"{"from_device":"123"}"#)
                .unwrap()
                .into_result()
                .unwrap_err();

        assert!(error.message().contains("missing field"));
        assert!(error.is_deserialization());
    }

    #[test]
    fn deserialization_validation_missing_required_key_agreement_protocols() {
        let error =
            serde_json::from_str::<EventResult<StartEventContent>>(
                r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":[],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]}"#
            )
                .unwrap()
                .into_result()
                .unwrap_err();

        assert!(error.message().contains("key_agreement_protocols"));
        assert!(error.is_validation());
    }

    #[test]
    fn deserialization_validation_missing_required_hashes() {
        let error =
            serde_json::from_str::<EventResult<StartEventContent>>(
                r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":[],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]}"#
            )
                .unwrap()
                .into_result()
                .unwrap_err();

        assert!(error.message().contains("hashes"));
        assert!(error.is_validation());
    }

    #[test]
    fn deserialization_validation_missing_required_message_authentication_codes() {
        let error =
            serde_json::from_str::<EventResult<StartEventContent>>(
                r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":[],"short_authentication_string":["decimal"]}"#
            )
                .unwrap()
                .into_result()
                .unwrap_err();

        assert!(error.message().contains("message_authentication_codes"));
        assert!(error.is_validation());
    }

    #[test]
    fn deserialization_validation_missing_required_short_authentication_string() {
        let error =
            serde_json::from_str::<EventResult<StartEventContent>>(
                r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":[]}"#
            )
                .unwrap()
                .into_result()
                .unwrap_err();

        assert!(error.message().contains("short_authentication_string"));
        assert!(error.is_validation());
    }

    #[test]
    fn deserialization_of_event_validates_content() {
        // This JSON is missing the required value of "curve25519" for "key_agreement_protocols".
        let error =
            serde_json::from_str::<EventResult<StartEvent>>(
                r#"{"content":{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":[],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]},"type":"m.key.verification.start"}"#
            )
                .unwrap()
                .into_result()
                .unwrap_err();

        assert!(error.message().contains("key_agreement_protocols"));
        assert!(error.is_validation());
    }
}