Debian Codegraph @

third_party/rust/mls-rs/src/group/framing.rs

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5 use core::ops::Deref;
6
7 use crate::{client::MlsError, tree_kem::node::LeafIndex, KeyPackage, KeyPackageRef};
8
9 use super::{Commit, FramedContentAuthData, GroupInfo, MembershipTag, Welcome};
10
11 #[cfg(feature = "by_ref_proposal")]
12 use crate::{group::Proposal, mls_rules::ProposalRef};
13
14 use alloc::vec::Vec;
15 use core::fmt::{self, Debug};
16 use mls_rs_codec::{MlsDecode, MlsEncode, MlsSize};
17 use mls_rs_core::{
18 crypto::{CipherSuite, CipherSuiteProvider},
19 protocol_version::ProtocolVersion,
20 };
21 use zeroize::ZeroizeOnDrop;
22
23 #[cfg(feature = "private_message")]
24 use alloc::boxed::Box;
25
26 #[cfg(feature = "custom_proposal")]
27 use crate::group::proposal::{CustomProposal, ProposalOrRef};
28
29 #[derive(Copy, Clone, Debug, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
30 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
31 #[repr(u8)]
32 pub enum ContentType {
33 #[cfg(feature = "private_message")]
34 Application = 1u8,
35 #[cfg(feature = "by_ref_proposal")]
36 Proposal = 2u8,
37 Commit = 3u8,
38 }
39
40 impl From<&Content> for ContentType {
41 fn from(content: &Content) -> Self {
42 match content {
43 #[cfg(feature = "private_message")]
44 Content::Application(_) => ContentType::Application,
45 #[cfg(feature = "by_ref_proposal")]
46 Content::Proposal(_) => ContentType::Proposal,
47 Content::Commit(_) => ContentType::Commit,
48 }
49 }
50 }
51
52 // #[cfg_attr(
53 // all(feature = "ffi", not(test)),
54 // safer_ffi_gen::ffi_type(clone, opaque)
55 // )]
56 #[derive(Clone, Copy, Debug, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
57 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
58 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59 #[repr(u8)]
60 #[non_exhaustive]
61 /// Description of a [`MlsMessage`] sender
62 pub enum Sender {
63 /// Current group member index.
64 Member(u32) = 1u8,
65 /// An external entity sending a proposal proposal identified by an index
66 /// in the current
67 /// [`ExternalSendersExt`](crate::extension::ExternalSendersExt) stored in
68 /// group context extensions.
69 #[cfg(feature = "by_ref_proposal")]
70 External(u32) = 2u8,
71 /// A new member proposing their own addition to the group.
72 #[cfg(feature = "by_ref_proposal")]
73 NewMemberProposal = 3u8,
74 /// A member sending an external commit.
75 NewMemberCommit = 4u8,
76 }
77
78 impl From<LeafIndex> for Sender {
79 fn from(leaf_index: LeafIndex) -> Self {
80 Sender::Member(*leaf_index)
81 }
82 }
83
84 impl From<u32> for Sender {
85 fn from(leaf_index: u32) -> Self {
86 Sender::Member(leaf_index)
87 }
88 }
89
90 #[derive(Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode, ZeroizeOnDrop)]
91 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
92 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
93 pub struct ApplicationData(
94 #[mls_codec(with = "mls_rs_codec::byte_vec")]
95 #[cfg_attr(feature = "serde", serde(with = "mls_rs_core::vec_serde"))]
96 Vec<u8>,
97 );
98
99 impl Debug for ApplicationData {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 mls_rs_core::debug::pretty_bytes(&self.0)
102 .named("ApplicationData")
103 .fmt(f)
104 }
105 }
106
107 impl From<Vec<u8>> for ApplicationData {
108 fn from(data: Vec<u8>) -> Self {
109 Self(data)
110 }
111 }
112
113 impl Deref for ApplicationData {
114 type Target = [u8];
115
116 fn deref(&self) -> &Self::Target {
117 &self.0
118 }
119 }
120
121 impl ApplicationData {
122 /// Underlying message content.
123 pub fn as_bytes(&self) -> &[u8] {
124 &self.0
125 }
126 }
127
128 #[derive(Clone, Debug, PartialEq, MlsSize, MlsEncode, MlsDecode)]
129 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
130 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
131 #[repr(u8)]
132 pub(crate) enum Content {
133 #[cfg(feature = "private_message")]
134 Application(ApplicationData) = 1u8,
135 #[cfg(feature = "by_ref_proposal")]
136 Proposal(alloc::boxed::Box<Proposal>) = 2u8,
137 Commit(alloc::boxed::Box<Commit>) = 3u8,
138 }
139
140 impl Content {
141 pub fn content_type(&self) -> ContentType {
142 self.into()
143 }
144 }
145
146 #[derive(Clone, Debug, PartialEq)]
147 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
148 pub(crate) struct PublicMessage {
149 pub content: FramedContent,
150 pub auth: FramedContentAuthData,
151 pub membership_tag: Option<MembershipTag>,
152 }
153
154 impl MlsSize for PublicMessage {
155 fn mls_encoded_len(&self) -> usize {
156 self.content.mls_encoded_len()
157 + self.auth.mls_encoded_len()
158 + self
159 .membership_tag
160 .as_ref()
161 .map_or(0, |tag| tag.mls_encoded_len())
162 }
163 }
164
165 impl MlsEncode for PublicMessage {
166 fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), mls_rs_codec::Error> {
167 self.content.mls_encode(writer)?;
168 self.auth.mls_encode(writer)?;
169
170 self.membership_tag
171 .as_ref()
172 .map_or(Ok(()), |tag| tag.mls_encode(writer))
173 }
174 }
175
176 impl MlsDecode for PublicMessage {
177 fn mls_decode(reader: &mut &[u8]) -> Result<Self, mls_rs_codec::Error> {
178 let content = FramedContent::mls_decode(reader)?;
179 let auth = FramedContentAuthData::mls_decode(reader, content.content_type())?;
180
181 let membership_tag = match content.sender {
182 Sender::Member(_) => Some(MembershipTag::mls_decode(reader)?),
183 _ => None,
184 };
185
186 Ok(Self {
187 content,
188 auth,
189 membership_tag,
190 })
191 }
192 }
193
194 #[cfg(feature = "private_message")]
195 #[derive(Clone, Debug, PartialEq)]
196 pub(crate) struct PrivateMessageContent {
197 pub content: Content,
198 pub auth: FramedContentAuthData,
199 }
200
201 #[cfg(feature = "private_message")]
202 impl MlsSize for PrivateMessageContent {
203 fn mls_encoded_len(&self) -> usize {
204 let content_len_without_type = match &self.content {
205 Content::Application(c) => c.mls_encoded_len(),
206 #[cfg(feature = "by_ref_proposal")]
207 Content::Proposal(c) => c.mls_encoded_len(),
208 Content::Commit(c) => c.mls_encoded_len(),
209 };
210
211 content_len_without_type + self.auth.mls_encoded_len()
212 }
213 }
214
215 #[cfg(feature = "private_message")]
216 impl MlsEncode for PrivateMessageContent {
217 fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), mls_rs_codec::Error> {
218 match &self.content {
219 Content::Application(c) => c.mls_encode(writer),
220 #[cfg(feature = "by_ref_proposal")]
221 Content::Proposal(c) => c.mls_encode(writer),
222 Content::Commit(c) => c.mls_encode(writer),
223 }?;
224
225 self.auth.mls_encode(writer)?;
226
227 Ok(())
228 }
229 }
230
231 #[cfg(feature = "private_message")]
232 impl PrivateMessageContent {
233 pub(crate) fn mls_decode(
234 reader: &mut &[u8],
235 content_type: ContentType,
236 ) -> Result<Self, mls_rs_codec::Error> {
237 let content = match content_type {
238 ContentType::Application => Content::Application(ApplicationData::mls_decode(reader)?),
239 #[cfg(feature = "by_ref_proposal")]
240 ContentType::Proposal => Content::Proposal(Box::new(Proposal::mls_decode(reader)?)),
241 ContentType::Commit => {
242 Content::Commit(alloc::boxed::Box::new(Commit::mls_decode(reader)?))
243 }
244 };
245
246 let auth = FramedContentAuthData::mls_decode(reader, content.content_type())?;
247
248 if reader.iter().any(|&i| i != 0u8) {
249 // #[cfg(feature = "std")]
250 // return Err(mls_rs_codec::Error::Custom(
251 // "non-zero padding bytes discovered".to_string(),
252 // ));
253
254 // #[cfg(not(feature = "std"))]
255 return Err(mls_rs_codec::Error::Custom(5));
256 }
257
258 Ok(Self { content, auth })
259 }
260 }
261
262 #[cfg(feature = "private_message")]
263 #[derive(Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
264 pub struct PrivateContentAAD {
265 #[mls_codec(with = "mls_rs_codec::byte_vec")]
266 pub group_id: Vec<u8>,
267 pub epoch: u64,
268 pub content_type: ContentType,
269 #[mls_codec(with = "mls_rs_codec::byte_vec")]
270 pub authenticated_data: Vec<u8>,
271 }
272
273 #[cfg(feature = "private_message")]
274 impl Debug for PrivateContentAAD {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 f.debug_struct("PrivateContentAAD")
277 .field(
278 "group_id",
279 &mls_rs_core::debug::pretty_group_id(&self.group_id),
280 )
281 .field("epoch", &self.epoch)
282 .field("content_type", &self.content_type)
283 .field(
284 "authenticated_data",
285 &mls_rs_core::debug::pretty_bytes(&self.authenticated_data),
286 )
287 .finish()
288 }
289 }
290
291 #[cfg(feature = "private_message")]
292 #[derive(Clone, PartialEq, Eq, MlsSize, MlsEncode, MlsDecode)]
293 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
294 pub struct PrivateMessage {
295 #[mls_codec(with = "mls_rs_codec::byte_vec")]
296 pub group_id: Vec<u8>,
297 pub epoch: u64,
298 pub content_type: ContentType,
299 #[mls_codec(with = "mls_rs_codec::byte_vec")]
300 pub authenticated_data: Vec<u8>,
301 #[mls_codec(with = "mls_rs_codec::byte_vec")]
302 pub encrypted_sender_data: Vec<u8>,
303 #[mls_codec(with = "mls_rs_codec::byte_vec")]
304 pub ciphertext: Vec<u8>,
305 }
306
307 #[cfg(feature = "private_message")]
308 impl Debug for PrivateMessage {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 f.debug_struct("PrivateMessage")
311 .field(
312 "group_id",
313 &mls_rs_core::debug::pretty_group_id(&self.group_id),
314 )
315 .field("epoch", &self.epoch)
316 .field("content_type", &self.content_type)
317 .field(
318 "authenticated_data",
319 &mls_rs_core::debug::pretty_bytes(&self.authenticated_data),
320 )
321 .field(
322 "encrypted_sender_data",
323 &mls_rs_core::debug::pretty_bytes(&self.encrypted_sender_data),
324 )
325 .field(
326 "ciphertext",
327 &mls_rs_core::debug::pretty_bytes(&self.ciphertext),
328 )
329 .finish()
330 }
331 }
332
333 #[cfg(feature = "private_message")]
334 impl From<&PrivateMessage> for PrivateContentAAD {
335 fn from(ciphertext: &PrivateMessage) -> Self {
336 Self {
337 group_id: ciphertext.group_id.clone(),
338 epoch: ciphertext.epoch,
339 content_type: ciphertext.content_type,
340 authenticated_data: ciphertext.authenticated_data.clone(),
341 }
342 }
343 }
344
345 #[derive(Clone, Debug, PartialEq, MlsSize, MlsEncode, MlsDecode)]
346 // #[cfg_attr(
347 // all(feature = "ffi", not(test)),
348 // ::safer_ffi_gen::ffi_type(clone, opaque)
349 // )]
350 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
351 /// A MLS protocol message for sending data over the wire.
352 pub struct MlsMessage {
353 pub(crate) version: ProtocolVersion,
354 pub(crate) payload: MlsMessagePayload,
355 }
356
357 // #[cfg_attr(all(feature = "ffi", not(test)), ::safer_ffi_gen::safer_ffi_gen)]
358 #[allow(dead_code)]
359 impl MlsMessage {
360 pub(crate) fn new(version: ProtocolVersion, payload: MlsMessagePayload) -> MlsMessage {
361 Self { version, payload }
362 }
363
364 #[inline(always)]
365 pub(crate) fn into_plaintext(self) -> Option<PublicMessage> {
366 match self.payload {
367 MlsMessagePayload::Plain(plaintext) => Some(plaintext),
368 _ => None,
369 }
370 }
371
372 #[cfg(feature = "private_message")]
373 #[inline(always)]
374 pub(crate) fn into_ciphertext(self) -> Option<PrivateMessage> {
375 match self.payload {
376 MlsMessagePayload::Cipher(ciphertext) => Some(ciphertext),
377 _ => None,
378 }
379 }
380
381 #[inline(always)]
382 pub(crate) fn into_welcome(self) -> Option<Welcome> {
383 match self.payload {
384 MlsMessagePayload::Welcome(welcome) => Some(welcome),
385 _ => None,
386 }
387 }
388
389 #[inline(always)]
390 pub fn into_group_info(self) -> Option<GroupInfo> {
391 match self.payload {
392 MlsMessagePayload::GroupInfo(info) => Some(info),
393 _ => None,
394 }
395 }
396
397 #[inline(always)]
398 pub fn as_group_info(&self) -> Option<&GroupInfo> {
399 match &self.payload {
400 MlsMessagePayload::GroupInfo(info) => Some(info),
401 _ => None,
402 }
403 }
404
405 #[inline(always)]
406 pub fn into_key_package(self) -> Option<KeyPackage> {
407 match self.payload {
408 MlsMessagePayload::KeyPackage(kp) => Some(kp),
409 _ => None,
410 }
411 }
412
413 pub fn as_key_package(&self) -> Option<&KeyPackage> {
414 match &self.payload {
415 MlsMessagePayload::KeyPackage(kp) => Some(kp),
416 _ => None,
417 }
418 }
419
420 /// The wire format value describing the contents of this message.
421 pub fn wire_format(&self) -> WireFormat {
422 match self.payload {
423 MlsMessagePayload::Plain(_) => WireFormat::PublicMessage,
424 #[cfg(feature = "private_message")]
425 MlsMessagePayload::Cipher(_) => WireFormat::PrivateMessage,
426 MlsMessagePayload::Welcome(_) => WireFormat::Welcome,
427 MlsMessagePayload::GroupInfo(_) => WireFormat::GroupInfo,
428 MlsMessagePayload::KeyPackage(_) => WireFormat::KeyPackage,
429 }
430 }
431
432 /// The epoch that this message belongs to.
433 ///
434 /// Returns `None` if the message is [`WireFormat::KeyPackage`]
435 /// or [`WireFormat::Welcome`]
436 // #[cfg_attr(all(feature = "ffi", not(test)), ::safer_ffi_gen::safer_ffi_gen_ignore)]
437 pub fn epoch(&self) -> Option<u64> {
438 match &self.payload {
439 MlsMessagePayload::Plain(p) => Some(p.content.epoch),
440 #[cfg(feature = "private_message")]
441 MlsMessagePayload::Cipher(c) => Some(c.epoch),
442 MlsMessagePayload::GroupInfo(gi) => Some(gi.group_context.epoch),
443 _ => None,
444 }
445 }
446
447 // #[cfg_attr(all(feature = "ffi", not(test)), ::safer_ffi_gen::safer_ffi_gen_ignore)]
448 pub fn cipher_suite(&self) -> Option<CipherSuite> {
449 match &self.payload {
450 MlsMessagePayload::GroupInfo(i) => Some(i.group_context.cipher_suite),
451 MlsMessagePayload::Welcome(w) => Some(w.cipher_suite),
452 MlsMessagePayload::KeyPackage(k) => Some(k.cipher_suite),
453 _ => None,
454 }
455 }
456
457 pub fn group_id(&self) -> Option<&[u8]> {
458 match &self.payload {
459 MlsMessagePayload::Plain(p) => Some(&p.content.group_id),
460 #[cfg(feature = "private_message")]
461 MlsMessagePayload::Cipher(p) => Some(&p.group_id),
462 MlsMessagePayload::GroupInfo(p) => Some(&p.group_context.group_id),
463 MlsMessagePayload::KeyPackage(_) | MlsMessagePayload::Welcome(_) => None,
464 }
465 }
466
467 /// Deserialize a message from transport.
468 #[inline(never)]
469 pub fn from_bytes(bytes: &[u8]) -> Result<Self, MlsError> {
470 Self::mls_decode(&mut &*bytes).map_err(Into::into)
471 }
472
473 /// Serialize a message for transport.
474 pub fn to_bytes(&self) -> Result<Vec<u8>, MlsError> {
475 self.mls_encode_to_vec().map_err(Into::into)
476 }
477
478 /// If this is a plaintext commit message, return all custom proposals committed by value.
479 /// If this is not a plaintext or not a commit, this returns an empty list.
480 #[cfg(feature = "custom_proposal")]
481 pub fn custom_proposals_by_value(&self) -> Vec<&CustomProposal> {
482 match &self.payload {
483 MlsMessagePayload::Plain(plaintext) => match &plaintext.content.content {
484 Content::Commit(commit) => Self::find_custom_proposals(commit),
485 _ => Vec::new(),
486 },
487 _ => Vec::new(),
488 }
489 }
490
491 /// If this is a welcome message, return key package references of all members who can
492 /// join using this message.
493 pub fn welcome_key_package_references(&self) -> Vec<&KeyPackageRef> {
494 let MlsMessagePayload::Welcome(welcome) = &self.payload else {
495 return Vec::new();
496 };
497
498 welcome.secrets.iter().map(|s| &s.new_member).collect()
499 }
500
501 /// If this is a key package, return its key package reference.
502 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
503 pub async fn key_package_reference<C: CipherSuiteProvider>(
504 &self,
505 cipher_suite: &C,
506 ) -> Result<Option<KeyPackageRef>, MlsError> {
507 let MlsMessagePayload::KeyPackage(kp) = &self.payload else {
508 return Ok(None);
509 };
510
511 kp.to_reference(cipher_suite).await.map(Some)
512 }
513
514 /// If this is a plaintext proposal, return the proposal reference that can be matched e.g. with
515 /// [`NewEpoch::unused_proposals`](super::NewEpoch::unused_proposals).
516 #[cfg(feature = "by_ref_proposal")]
517 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
518 pub async fn into_proposal_reference<C: CipherSuiteProvider>(
519 self,
520 cipher_suite: &C,
521 ) -> Result<Option<Vec<u8>>, MlsError> {
522 let MlsMessagePayload::Plain(public_message) = self.payload else {
523 return Ok(None);
524 };
525
526 ProposalRef::from_content(cipher_suite, &public_message.into())
527 .await
528 .map(|r| Some(r.to_vec()))
529 }
530 }
531
532 #[cfg(feature = "custom_proposal")]
533 impl MlsMessage {
534 fn find_custom_proposals(commit: &Commit) -> Vec<&CustomProposal> {
535 commit
536 .proposals
537 .iter()
538 .filter_map(|p| match p {
539 ProposalOrRef::Proposal(p) => match p.as_ref() {
540 crate::group::Proposal::Custom(p) => Some(p),
541 _ => None,
542 },
543 _ => None,
544 })
545 .collect()
546 }
547 }
548
549 #[allow(clippy::large_enum_variant)]
550 #[derive(Clone, Debug, PartialEq, MlsSize, MlsEncode, MlsDecode)]
551 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
552 #[repr(u16)]
553 pub(crate) enum MlsMessagePayload {
554 Plain(PublicMessage) = 1u16,
555 #[cfg(feature = "private_message")]
556 Cipher(PrivateMessage) = 2u16,
557 Welcome(Welcome) = 3u16,
558 GroupInfo(GroupInfo) = 4u16,
559 KeyPackage(KeyPackage) = 5u16,
560 }
561
562 impl From<PublicMessage> for MlsMessagePayload {
563 fn from(m: PublicMessage) -> Self {
564 Self::Plain(m)
565 }
566 }
567
568 // #[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::ffi_type)]
569 #[derive(
570 Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, MlsSize, MlsEncode, MlsDecode,
571 )]
572 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
573 #[repr(u16)]
574 #[non_exhaustive]
575 /// Content description of an [`MlsMessage`]
576 pub enum WireFormat {
577 PublicMessage = 1u16,
578 PrivateMessage = 2u16,
579 Welcome = 3u16,
580 GroupInfo = 4u16,
581 KeyPackage = 5u16,
582 }
583
584 #[derive(Clone, PartialEq, MlsSize, MlsEncode, MlsDecode)]
585 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
586 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
587 pub(crate) struct FramedContent {
588 #[mls_codec(with = "mls_rs_codec::byte_vec")]
589 #[cfg_attr(feature = "serde", serde(with = "mls_rs_core::vec_serde"))]
590 pub group_id: Vec<u8>,
591 pub epoch: u64,
592 pub sender: Sender,
593 #[mls_codec(with = "mls_rs_codec::byte_vec")]
594 #[cfg_attr(feature = "serde", serde(with = "mls_rs_core::vec_serde"))]
595 pub authenticated_data: Vec<u8>,
596 pub content: Content,
597 }
598
599 impl Debug for FramedContent {
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601 f.debug_struct("FramedContent")
602 .field(
603 "group_id",
604 &mls_rs_core::debug::pretty_group_id(&self.group_id),
605 )
606 .field("epoch", &self.epoch)
607 .field("sender", &self.sender)
608 .field(
609 "authenticated_data",
610 &mls_rs_core::debug::pretty_bytes(&self.authenticated_data),
611 )
612 .field("content", &self.content)
613 .finish()
614 }
615 }
616
617 impl FramedContent {
618 pub fn content_type(&self) -> ContentType {
619 self.content.content_type()
620 }
621 }
622
623 #[cfg(test)]
624 pub(crate) mod test_utils {
625 #[cfg(feature = "private_message")]
626 use crate::group::test_utils::random_bytes;
627
628 use crate::group::{AuthenticatedContent, MessageSignature};
629
630 use super::*;
631
632 use alloc::boxed::Box;
633
634 pub(crate) fn get_test_auth_content() -> AuthenticatedContent {
635 // This is not a valid commit and should not be validated
636 let commit = Commit {
637 proposals: Default::default(),
638 path: None,
639 };
640
641 AuthenticatedContent {
642 wire_format: WireFormat::PublicMessage,
643 content: FramedContent {
644 group_id: Vec::new(),
645 epoch: 0,
646 sender: Sender::Member(1),
647 authenticated_data: Vec::new(),
648 content: Content::Commit(Box::new(commit)),
649 },
650 auth: FramedContentAuthData {
651 signature: MessageSignature::empty(),
652 confirmation_tag: None,
653 },
654 }
655 }
656
657 #[cfg(feature = "private_message")]
658 pub(crate) fn get_test_ciphertext_content() -> PrivateMessageContent {
659 PrivateMessageContent {
660 content: Content::Application(random_bytes(1024).into()),
661 auth: FramedContentAuthData {
662 signature: MessageSignature::from(random_bytes(128)),
663 confirmation_tag: None,
664 },
665 }
666 }
667
668 impl AsRef<[u8]> for ApplicationData {
669 fn as_ref(&self) -> &[u8] {
670 &self.0
671 }
672 }
673 }
674
675 #[cfg(feature = "private_message")]
676 #[cfg(test)]
677 mod tests {
678 use assert_matches::assert_matches;
679
680 use crate::{
681 client::test_utils::{TEST_CIPHER_SUITE, TEST_PROTOCOL_VERSION},
682 crypto::test_utils::test_cipher_suite_provider,
683 group::{
684 framing::test_utils::get_test_ciphertext_content,
685 proposal_ref::test_utils::auth_content_from_proposal, RemoveProposal,
686 },
687 };
688
689 use super::*;
690
691 #[test]
692 fn test_mls_ciphertext_content_mls_encoding() {
693 let ciphertext_content = get_test_ciphertext_content();
694
695 let mut encoded = ciphertext_content.mls_encode_to_vec().unwrap();
696 encoded.extend_from_slice(&[0u8; 128]);
697
698 let decoded =
699 PrivateMessageContent::mls_decode(&mut &*encoded, (&ciphertext_content.content).into())
700 .unwrap();
701
702 assert_eq!(ciphertext_content, decoded);
703 }
704
705 #[test]
706 fn test_mls_ciphertext_content_non_zero_padding_error() {
707 let ciphertext_content = get_test_ciphertext_content();
708
709 let mut encoded = ciphertext_content.mls_encode_to_vec().unwrap();
710 encoded.extend_from_slice(&[1u8; 128]);
711
712 let decoded =
713 PrivateMessageContent::mls_decode(&mut &*encoded, (&ciphertext_content.content).into());
714
715 assert_matches!(decoded, Err(mls_rs_codec::Error::Custom(_)));
716 }
717
718 #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
719 async fn proposal_ref() {
720 let cs = test_cipher_suite_provider(TEST_CIPHER_SUITE);
721
722 let test_auth = auth_content_from_proposal(
723 Proposal::Remove(RemoveProposal {
724 to_remove: LeafIndex(0),
725 }),
726 Sender::External(0),
727 );
728
729 let expected_ref = ProposalRef::from_content(&cs, &test_auth).await.unwrap();
730
731 let test_message = MlsMessage {
732 version: TEST_PROTOCOL_VERSION,
733 payload: MlsMessagePayload::Plain(PublicMessage {
734 content: test_auth.content,
735 auth: test_auth.auth,
736 membership_tag: Some(cs.mac(&[1, 2, 3], &[1, 2, 3]).await.unwrap().into()),
737 }),
738 };
739
740 let computed_ref = test_message
741 .into_proposal_reference(&cs)
742 .await
743 .unwrap()
744 .unwrap();
745
746 assert_eq!(computed_ref, expected_ref.to_vec());
747 }
748 }