1use std::{
28 collections::HashSet,
29 convert::Infallible,
30 fmt::Debug,
31 io::{Read, Write},
32 marker::PhantomData,
33};
34
35use serde::{Deserialize, Serialize};
36
37#[cfg(feature = "extensions-draft")]
39mod app_data_dict_extension;
40mod application_id_extension;
41mod codec;
42mod extension_in;
43mod external_pub_extension;
44mod external_sender_extension;
45mod last_resort;
46mod ratchet_tree_extension;
47mod required_capabilities;
48use errors::*;
49
50pub mod errors;
52
53#[cfg(feature = "extensions-draft")]
55pub use app_data_dict_extension::{AppDataDictionary, AppDataDictionaryExtension};
56pub use application_id_extension::ApplicationIdExtension;
57pub use external_pub_extension::ExternalPubExtension;
58pub use external_sender_extension::{
59 ExternalSender, ExternalSendersExtension, SenderExtensionIndex,
60};
61pub use last_resort::LastResortExtension;
62pub use ratchet_tree_extension::RatchetTreeExtension;
63pub use required_capabilities::RequiredCapabilitiesExtension;
64
65use tls_codec::{
66 Deserialize as TlsDeserializeTrait, DeserializeBytes, Error, Serialize as TlsSerializeTrait,
67 Size, TlsDeserialize, TlsSerialize, TlsSize,
68};
69
70use crate::{
71 extensions::extension_in::ExtensionIn, group::GroupContext, key_packages::KeyPackage,
72 messages::group_info::GroupInfo, treesync::LeafNode,
73};
74
75#[cfg(test)]
76mod tests;
77
78#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
94#[cfg_attr(
95 feature = "0-8-1-storage-format",
96 derive(serde::Serialize, serde::Deserialize)
97)]
98#[cfg_attr(
99 not(feature = "0-8-1-storage-format"),
100 derive(
101 openmls_serialization_helpers::Serialize,
102 openmls_serialization_helpers::Deserialize,
103 )
104)]
105pub enum ExtensionType {
106 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 0)]
107 ApplicationId,
110
111 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 1)]
112 RatchetTree,
115
116 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 2)]
117 RequiredCapabilities,
120
121 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 3)]
122 ExternalPub,
125
126 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 4)]
127 ExternalSenders,
130
131 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 5)]
132 LastResort,
135
136 #[cfg(feature = "extensions-draft")]
137 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 8)]
138 AppDataDictionary,
140
141 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 7)]
142 Grease(u16),
144
145 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 6)]
146 Unknown(u16),
148}
149
150impl ExtensionType {
151 pub(crate) fn is_default(self) -> bool {
153 match self {
154 ExtensionType::ApplicationId
155 | ExtensionType::RatchetTree
156 | ExtensionType::RequiredCapabilities
157 | ExtensionType::ExternalPub
158 | ExtensionType::ExternalSenders => true,
159 ExtensionType::LastResort | ExtensionType::Grease(_) | ExtensionType::Unknown(_) => {
160 false
161 }
162 #[cfg(feature = "extensions-draft")]
163 ExtensionType::AppDataDictionary => false,
164 }
165 }
166
167 pub(crate) fn is_valid_in_leaf_node(self) -> bool {
171 match self {
172 ExtensionType::LastResort
173 | ExtensionType::RatchetTree
174 | ExtensionType::RequiredCapabilities
175 | ExtensionType::ExternalPub
176 | ExtensionType::ExternalSenders => false,
177 ExtensionType::Grease(_) | ExtensionType::Unknown(_) | ExtensionType::ApplicationId => {
182 true
183 }
184 #[cfg(feature = "extensions-draft")]
185 ExtensionType::AppDataDictionary => true,
186 }
187 }
188 pub(crate) fn is_valid_in_group_info(self) -> Option<bool> {
189 match self {
190 ExtensionType::LastResort
191 | ExtensionType::RequiredCapabilities
192 | ExtensionType::ExternalSenders
193 | ExtensionType::ApplicationId => Some(false),
194 ExtensionType::RatchetTree | ExtensionType::ExternalPub => Some(true),
195 ExtensionType::Grease(_) | ExtensionType::Unknown(_) => None,
199 #[cfg(feature = "extensions-draft")]
200 ExtensionType::AppDataDictionary => Some(true),
201 }
202 }
203
204 pub(crate) fn is_valid_in_key_package(self) -> bool {
205 match self {
206 ExtensionType::RatchetTree
207 | ExtensionType::RequiredCapabilities
208 | ExtensionType::ExternalPub
209 | ExtensionType::ExternalSenders
210 | ExtensionType::ApplicationId => false,
211 ExtensionType::Grease(_) | ExtensionType::Unknown(_) | ExtensionType::LastResort => {
216 true
217 }
218 #[cfg(feature = "extensions-draft")]
219 ExtensionType::AppDataDictionary => true,
220 }
221 }
222
223 pub(crate) fn is_valid_in_group_context(self) -> bool {
224 match self {
225 ExtensionType::RequiredCapabilities
226 | ExtensionType::ExternalSenders
227 | ExtensionType::Unknown(_) => true,
228 ExtensionType::Grease(_) => true,
234 #[cfg(feature = "extensions-draft")]
235 ExtensionType::AppDataDictionary => true,
236 _ => false,
237 }
238 }
239
240 pub fn is_grease(&self) -> bool {
245 matches!(self, ExtensionType::Grease(v) if crate::grease::is_grease_value(*v))
246 }
247}
248
249impl Size for ExtensionType {
250 fn tls_serialized_len(&self) -> usize {
251 2
252 }
253}
254
255impl TlsDeserializeTrait for ExtensionType {
256 fn tls_deserialize<R: Read>(bytes: &mut R) -> Result<Self, Error>
257 where
258 Self: Sized,
259 {
260 let mut extension_type = [0u8; 2];
261 bytes.read_exact(&mut extension_type)?;
262
263 Ok(ExtensionType::from(u16::from_be_bytes(extension_type)))
264 }
265}
266
267impl DeserializeBytes for ExtensionType {
268 fn tls_deserialize_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error>
269 where
270 Self: Sized,
271 {
272 let mut bytes_ref = bytes;
273 let extension_type = ExtensionType::tls_deserialize(&mut bytes_ref)?;
274 Ok((extension_type, bytes_ref))
275 }
276}
277
278impl TlsSerializeTrait for ExtensionType {
279 fn tls_serialize<W: Write>(&self, writer: &mut W) -> Result<usize, Error> {
280 let value = u16::from(*self);
281 if ExtensionType::from(value) != *self {
284 return Err(Error::EncodingError(format!(
285 "{self:?} is encoded as {value:#06x}, which decodes as a different extension type"
286 )));
287 }
288 writer.write_all(&value.to_be_bytes())?;
289
290 Ok(2)
291 }
292}
293
294impl From<u16> for ExtensionType {
295 fn from(a: u16) -> Self {
296 match a {
297 1 => ExtensionType::ApplicationId,
298 2 => ExtensionType::RatchetTree,
299 3 => ExtensionType::RequiredCapabilities,
300 4 => ExtensionType::ExternalPub,
301 5 => ExtensionType::ExternalSenders,
302 #[cfg(feature = "extensions-draft")]
303 6 => ExtensionType::AppDataDictionary,
304 10 => ExtensionType::LastResort,
305 unknown if crate::grease::is_grease_value(unknown) => ExtensionType::Grease(unknown),
306 unknown => ExtensionType::Unknown(unknown),
307 }
308 }
309}
310
311impl From<ExtensionType> for u16 {
312 fn from(value: ExtensionType) -> Self {
313 match value {
314 ExtensionType::ApplicationId => 1,
315 ExtensionType::RatchetTree => 2,
316 ExtensionType::RequiredCapabilities => 3,
317 ExtensionType::ExternalPub => 4,
318 ExtensionType::ExternalSenders => 5,
319 #[cfg(feature = "extensions-draft")]
320 ExtensionType::AppDataDictionary => 6,
321 ExtensionType::LastResort => 10,
322 ExtensionType::Grease(value) => value,
323 ExtensionType::Unknown(unknown) => unknown,
324 }
325 }
326}
327
328#[derive(Debug, Clone, PartialEq, Eq)]
343#[cfg_attr(
344 feature = "0-8-1-storage-format",
345 derive(serde::Serialize, serde::Deserialize)
346)]
347#[cfg_attr(
348 not(feature = "0-8-1-storage-format"),
349 derive(
350 openmls_serialization_helpers::Serialize,
351 openmls_serialization_helpers::Deserialize,
352 )
353)]
354pub enum Extension {
355 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 0)]
356 ApplicationId(ApplicationIdExtension),
358
359 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 1)]
360 RatchetTree(RatchetTreeExtension),
362
363 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 2)]
364 RequiredCapabilities(RequiredCapabilitiesExtension),
366
367 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 3)]
368 ExternalPub(ExternalPubExtension),
370
371 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 4)]
372 ExternalSenders(ExternalSendersExtension),
374
375 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 7)]
376 #[cfg(feature = "extensions-draft")]
378 AppDataDictionary(AppDataDictionaryExtension),
379
380 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 5)]
381 LastResort(LastResortExtension),
383
384 #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 6)]
385 Unknown(u16, UnknownExtension),
387}
388
389#[derive(
391 PartialEq, Eq, Clone, Debug, Serialize, Deserialize, TlsSize, TlsSerialize, TlsDeserialize,
392)]
393pub struct UnknownExtension(pub Vec<u8>);
394
395#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
401pub struct Extensions<T> {
402 unique: Vec<Extension>,
403 #[serde(skip)]
404 _object: core::marker::PhantomData<T>,
405}
406
407#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, TlsSize, TlsSerialize, TlsDeserialize)]
408pub struct AnyObject;
410
411impl<T> Default for Extensions<T> {
412 fn default() -> Self {
413 Self {
414 unique: vec![],
415 _object: PhantomData,
416 }
417 }
418}
419
420impl<T> Size for Extensions<T> {
421 fn tls_serialized_len(&self) -> usize {
422 Vec::tls_serialized_len(&self.unique)
423 }
424}
425
426impl<T> TlsSerializeTrait for Extensions<T> {
427 fn tls_serialize<W: Write>(&self, writer: &mut W) -> Result<usize, Error> {
428 self.unique.tls_serialize(writer)
429 }
430}
431
432impl<T: ExtensionValidator<Error: ToString>> TlsDeserializeTrait for Extensions<T>
433where
434 InvalidExtensionError: From<T::Error>,
435{
436 fn tls_deserialize<R: Read>(bytes: &mut R) -> Result<Self, Error>
437 where
438 Self: Sized,
439 {
440 let candidate: Vec<ExtensionIn<T>> = Vec::tls_deserialize(bytes)?;
441 Extensions::<T>::try_from(candidate)
442 .map_err(|_| Error::DecodingError("Found duplicate extensions".into()))
443 }
444}
445
446impl<T: ExtensionValidator<Error: ToString>> DeserializeBytes for Extensions<T>
447where
448 InvalidExtensionError: From<T::Error>,
449{
450 fn tls_deserialize_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error>
451 where
452 Self: Sized,
453 {
454 let mut bytes_ref = bytes;
455 let extensions = Extensions::<T>::tls_deserialize(&mut bytes_ref)?;
456 Ok((extensions, bytes_ref))
457 }
458}
459
460impl<T: ExtensionValidator> Extensions<T> {
461 pub fn empty() -> Self {
463 Self {
464 unique: vec![],
465 _object: PhantomData,
466 }
467 }
468
469 pub fn iter(&self) -> impl Iterator<Item = &Extension> {
471 self.unique.iter()
472 }
473
474 pub fn remove(&mut self, extension_type: ExtensionType) -> Option<Extension> {
479 if let Some(pos) = self
480 .unique
481 .iter()
482 .position(|ext| ext.extension_type() == extension_type)
483 {
484 Some(self.unique.remove(pos))
485 } else {
486 None
487 }
488 }
489
490 pub fn contains(&self, extension_type: ExtensionType) -> bool {
493 self.unique
494 .iter()
495 .any(|ext| ext.extension_type() == extension_type)
496 }
497}
498
499impl<T> Extensions<T>
500where
501 T: ExtensionValidator,
502 InvalidExtensionError: From<T::Error>,
503{
504 pub fn single(extension: Extension) -> Result<Self, InvalidExtensionError> {
506 T::validate_extension_type(extension.extension_type())?;
507 Ok(Self {
508 unique: vec![extension],
509 _object: PhantomData,
510 })
511 }
512
513 pub fn from_vec(extensions: Vec<Extension>) -> Result<Self, InvalidExtensionError> {
518 extensions.try_into()
519 }
520
521 pub fn validate<'a>(
523 extensions: impl Iterator<Item = &'a Extension>,
524 ) -> Result<(), InvalidExtensionError> {
525 for ext in extensions {
526 T::validate_extension_type(ext.extension_type())?;
527 }
528 Ok(())
529 }
530
531 pub fn add(&mut self, extension: Extension) -> Result<(), InvalidExtensionError> {
536 T::validate_extension_type(extension.extension_type())?;
537 if self.contains(extension.extension_type()) {
538 return Err(InvalidExtensionError::Duplicate);
539 }
540
541 self.unique.push(extension);
542
543 Ok(())
544 }
545
546 pub fn add_or_replace(
550 &mut self,
551 extension: Extension,
552 ) -> Result<Option<Extension>, InvalidExtensionError> {
553 T::validate_extension_type(extension.extension_type())?;
554 let replaced = self.remove(extension.extension_type());
555 self.unique.push(extension);
556 Ok(replaced)
557 }
558}
559
560impl Extensions<AnyObject> {
561 #[cfg(feature = "unchecked-conversions")]
567 pub fn into_unchecked<T>(self) -> Extensions<T> {
568 Extensions {
569 unique: self.unique,
570 _object: PhantomData,
571 }
572 }
573}
574
575mod private {
576 pub trait Sealed {}
578}
579
580pub trait ExtensionValidator: private::Sealed {
582 type Error;
584
585 fn validate_extension_type(ext: ExtensionType) -> Result<(), Self::Error>;
587}
588
589impl private::Sealed for AnyObject {}
590
591impl ExtensionValidator for AnyObject {
592 type Error = Infallible;
593
594 fn validate_extension_type(_ext: ExtensionType) -> Result<(), Infallible> {
595 Ok(())
596 }
597}
598
599impl<T: ExtensionValidator> TryFrom<Vec<Extension>> for Extensions<T>
600where
601 InvalidExtensionError: From<T::Error>,
602{
603 type Error = InvalidExtensionError;
604
605 fn try_from(candidate: Vec<Extension>) -> Result<Self, Self::Error> {
606 let mut seen = HashSet::with_capacity(candidate.len());
607 for extension in candidate.iter() {
608 T::validate_extension_type(extension.extension_type())?;
609
610 if !seen.insert(extension.extension_type()) {
611 return Err(InvalidExtensionError::Duplicate);
612 }
613 }
614
615 Ok(Self {
616 unique: candidate,
617 _object: PhantomData,
618 })
619 }
620}
621
622impl private::Sealed for GroupInfo {}
623
624impl ExtensionValidator for GroupInfo {
626 type Error = ExtensionTypeNotValidInGroupInfoError;
627
628 fn validate_extension_type(
629 extension_type: ExtensionType,
630 ) -> Result<(), ExtensionTypeNotValidInGroupInfoError> {
631 if extension_type.is_valid_in_group_info() == Some(true)
632 || extension_type.is_valid_in_group_info().is_none()
633 {
634 Ok(())
635 } else {
636 Err(ExtensionTypeNotValidInGroupInfoError(extension_type))
637 }
638 }
639}
640
641impl private::Sealed for GroupContext {}
642
643impl ExtensionValidator for GroupContext {
645 type Error = ExtensionTypeNotValidInGroupContextError;
646
647 fn validate_extension_type(
648 extension_type: ExtensionType,
649 ) -> Result<(), ExtensionTypeNotValidInGroupContextError> {
650 if extension_type.is_valid_in_group_context() {
651 Ok(())
652 } else {
653 Err(ExtensionTypeNotValidInGroupContextError(extension_type))
654 }
655 }
656}
657
658impl private::Sealed for KeyPackage {}
659
660impl ExtensionValidator for KeyPackage {
662 type Error = ExtensionTypeNotValidInKeyPackageError;
663
664 fn validate_extension_type(
665 extension_type: ExtensionType,
666 ) -> Result<(), ExtensionTypeNotValidInKeyPackageError> {
667 if extension_type.is_valid_in_key_package() {
668 Ok(())
669 } else {
670 Err(ExtensionTypeNotValidInKeyPackageError(extension_type))
671 }
672 }
673}
674
675impl private::Sealed for LeafNode {}
676
677impl ExtensionValidator for LeafNode {
679 type Error = ExtensionTypeNotValidInLeafNodeError;
680
681 fn validate_extension_type(
682 extension_type: ExtensionType,
683 ) -> Result<(), ExtensionTypeNotValidInLeafNodeError> {
684 if extension_type.is_valid_in_leaf_node() {
685 Ok(())
686 } else {
687 Err(ExtensionTypeNotValidInLeafNodeError(extension_type))
688 }
689 }
690}
691
692impl<T> Extensions<T> {
693 fn find_by_type(&self, extension_type: ExtensionType) -> Option<&Extension> {
694 self.unique
695 .iter()
696 .find(|ext| ext.extension_type() == extension_type)
697 }
698
699 pub fn application_id(&self) -> Option<&ApplicationIdExtension> {
701 self.find_by_type(ExtensionType::ApplicationId)
702 .and_then(|e| match e {
703 Extension::ApplicationId(e) => Some(e),
704 _ => None,
705 })
706 }
707
708 pub fn ratchet_tree(&self) -> Option<&RatchetTreeExtension> {
710 self.find_by_type(ExtensionType::RatchetTree)
711 .and_then(|e| match e {
712 Extension::RatchetTree(e) => Some(e),
713 _ => None,
714 })
715 }
716
717 pub fn required_capabilities(&self) -> Option<&RequiredCapabilitiesExtension> {
720 self.find_by_type(ExtensionType::RequiredCapabilities)
721 .and_then(|e| match e {
722 Extension::RequiredCapabilities(e) => Some(e),
723 _ => None,
724 })
725 }
726
727 pub fn external_pub(&self) -> Option<&ExternalPubExtension> {
729 self.find_by_type(ExtensionType::ExternalPub)
730 .and_then(|e| match e {
731 Extension::ExternalPub(e) => Some(e),
732 _ => None,
733 })
734 }
735
736 pub fn external_senders(&self) -> Option<&ExternalSendersExtension> {
738 self.find_by_type(ExtensionType::ExternalSenders)
739 .and_then(|e| match e {
740 Extension::ExternalSenders(e) => Some(e),
741 _ => None,
742 })
743 }
744
745 #[cfg(feature = "extensions-draft")]
746 pub fn app_data_dictionary(&self) -> Option<&AppDataDictionaryExtension> {
748 self.find_by_type(ExtensionType::AppDataDictionary)
749 .and_then(|e| match e {
750 Extension::AppDataDictionary(e) => Some(e),
751 _ => None,
752 })
753 }
754
755 pub fn unknown(&self, extension_type_id: u16) -> Option<&UnknownExtension> {
757 let extension_type: ExtensionType = extension_type_id.into();
758
759 match extension_type {
760 ExtensionType::Grease(_) | ExtensionType::Unknown(_) => {
761 self.find_by_type(extension_type).and_then(|e| match e {
762 Extension::Unknown(_, e) => Some(e),
763 _ => None,
764 })
765 }
766 _ => None,
767 }
768 }
769}
770
771impl Extension {
772 pub fn as_application_id_extension(&self) -> Result<&ApplicationIdExtension, ExtensionError> {
776 match self {
777 Self::ApplicationId(e) => Ok(e),
778 _ => Err(ExtensionError::InvalidExtensionType(
779 "This is not an ApplicationIdExtension".into(),
780 )),
781 }
782 }
783 #[cfg(feature = "extensions-draft")]
784 pub fn as_app_data_dictionary_extension(
788 &self,
789 ) -> Result<&AppDataDictionaryExtension, ExtensionError> {
790 match self {
791 Self::AppDataDictionary(e) => Ok(e),
792 _ => Err(ExtensionError::InvalidExtensionType(
793 "This is not an AppDataDictionaryExtension".into(),
794 )),
795 }
796 }
797
798 pub fn as_ratchet_tree_extension(&self) -> Result<&RatchetTreeExtension, ExtensionError> {
802 match self {
803 Self::RatchetTree(rte) => Ok(rte),
804 _ => Err(ExtensionError::InvalidExtensionType(
805 "This is not a RatchetTreeExtension".into(),
806 )),
807 }
808 }
809
810 pub fn as_required_capabilities_extension(
814 &self,
815 ) -> Result<&RequiredCapabilitiesExtension, ExtensionError> {
816 match self {
817 Self::RequiredCapabilities(e) => Ok(e),
818 _ => Err(ExtensionError::InvalidExtensionType(
819 "This is not a RequiredCapabilitiesExtension".into(),
820 )),
821 }
822 }
823
824 pub fn as_external_pub_extension(&self) -> Result<&ExternalPubExtension, ExtensionError> {
828 match self {
829 Self::ExternalPub(e) => Ok(e),
830 _ => Err(ExtensionError::InvalidExtensionType(
831 "This is not an ExternalPubExtension".into(),
832 )),
833 }
834 }
835
836 pub fn as_external_senders_extension(
840 &self,
841 ) -> Result<&ExternalSendersExtension, ExtensionError> {
842 match self {
843 Self::ExternalSenders(e) => Ok(e),
844 _ => Err(ExtensionError::InvalidExtensionType(
845 "This is not an ExternalSendersExtension".into(),
846 )),
847 }
848 }
849
850 #[inline]
852 pub const fn extension_type(&self) -> ExtensionType {
853 match self {
854 Extension::ApplicationId(_) => ExtensionType::ApplicationId,
855 Extension::RatchetTree(_) => ExtensionType::RatchetTree,
856 Extension::RequiredCapabilities(_) => ExtensionType::RequiredCapabilities,
857 Extension::ExternalPub(_) => ExtensionType::ExternalPub,
858 Extension::ExternalSenders(_) => ExtensionType::ExternalSenders,
859 #[cfg(feature = "extensions-draft")]
860 Extension::AppDataDictionary(_) => ExtensionType::AppDataDictionary,
861 Extension::LastResort(_) => ExtensionType::LastResort,
862 Extension::Unknown(kind, _) if crate::grease::is_grease_value(*kind) => {
867 ExtensionType::Grease(*kind)
868 }
869 Extension::Unknown(kind, _) => ExtensionType::Unknown(*kind),
870 }
871 }
872}
873
874macro_rules! impl_from_extensions_validator {
875 ($validator:ty, $error:ty) => {
876 impl From<Extensions<$validator>> for Extensions<AnyObject> {
877 fn from(value: Extensions<$validator>) -> Self {
878 Extensions {
879 unique: value.unique,
880 _object: PhantomData,
881 }
882 }
883 }
884
885 impl TryFrom<Extensions<AnyObject>> for Extensions<$validator> {
886 type Error = $error;
887
888 fn try_from(value: Extensions<AnyObject>) -> Result<Self, $error> {
889 value
890 .unique
891 .iter()
892 .map(Extension::extension_type)
893 .try_for_each(<$validator as ExtensionValidator>::validate_extension_type)?;
894
895 Ok(Extensions {
896 unique: value.unique,
897 _object: PhantomData,
898 })
899 }
900 }
901 };
902}
903
904impl_from_extensions_validator!(GroupContext, ExtensionTypeNotValidInGroupContextError);
905impl_from_extensions_validator!(LeafNode, ExtensionTypeNotValidInLeafNodeError);
906impl_from_extensions_validator!(KeyPackage, ExtensionTypeNotValidInKeyPackageError);
907
908#[cfg(any(feature = "test-utils", test))]
909impl Extensions<AnyObject> {
910 pub(crate) fn coerce<T: ExtensionValidator>(self) -> Extensions<T> {
912 Extensions {
913 unique: self.unique,
914 _object: PhantomData,
915 }
916 }
917}
918#[cfg(test)]
919mod test {
920 use itertools::Itertools;
921 use tls_codec::{Deserialize, Serialize, VLBytes};
922
923 use crate::{ciphersuite::HpkePublicKey, extensions::*};
924
925 #[test]
926 fn add() {
927 let mut extensions: Extensions<AnyObject> = Extensions::default();
928 extensions
929 .add(Extension::RequiredCapabilities(
930 RequiredCapabilitiesExtension::default(),
931 ))
932 .unwrap();
933 assert!(extensions
934 .add(Extension::RequiredCapabilities(
935 RequiredCapabilitiesExtension::default()
936 ))
937 .is_err());
938 }
939
940 #[test]
941 fn grease_extension_type_mapping() {
942 let grease = Extension::Unknown(0x5A5A, UnknownExtension(vec![1, 2, 3]));
947 assert_eq!(grease.extension_type(), ExtensionType::Grease(0x5A5A));
948 assert!(grease.extension_type().is_grease());
949
950 let unknown = Extension::Unknown(0xABCD, UnknownExtension(vec![]));
952 assert_eq!(unknown.extension_type(), ExtensionType::Unknown(0xABCD));
953 }
954
955 #[test]
956 fn grease_extension_must_be_declared_in_capabilities() {
957 let advertised = crate::treesync::node::leaf_node::Capabilities::new(
964 None,
965 None,
966 Some(&[ExtensionType::Grease(0x5A5A)]),
967 None,
968 None,
969 );
970 assert!(advertised.contains_extension_type(&ExtensionType::Grease(0x5A5A)));
971 assert!(!advertised.contains_extension_type(&ExtensionType::Grease(0xAAAA)));
973
974 let empty =
976 crate::treesync::node::leaf_node::Capabilities::new(None, None, None, None, None);
977 assert!(!empty.contains_extension_type(&ExtensionType::Grease(0x5A5A)));
978 assert!(!empty.contains_extension_type(&ExtensionType::Unknown(0xABCD)));
979 }
980
981 #[test]
982 fn add_try_from() {
983 let ext_x = Extension::ApplicationId(ApplicationIdExtension::new(b"Test"));
986 let ext_y = Extension::RequiredCapabilities(RequiredCapabilitiesExtension::default());
987
988 let tests = [
989 (vec![], true),
990 (vec![ext_x.clone()], true),
991 (vec![ext_x.clone(), ext_x.clone()], false),
992 (vec![ext_x.clone(), ext_x.clone(), ext_x.clone()], false),
993 (vec![ext_y.clone()], true),
994 (vec![ext_y.clone(), ext_y.clone()], false),
995 (vec![ext_y.clone(), ext_y.clone(), ext_y.clone()], false),
996 (vec![ext_x.clone(), ext_y.clone()], true),
997 (vec![ext_y.clone(), ext_x.clone()], true),
998 (vec![ext_x.clone(), ext_x.clone(), ext_y.clone()], false),
999 (vec![ext_y.clone(), ext_y.clone(), ext_x.clone()], false),
1000 (vec![ext_x.clone(), ext_y.clone(), ext_y.clone()], false),
1001 (vec![ext_y.clone(), ext_x.clone(), ext_x.clone()], false),
1002 (vec![ext_x.clone(), ext_y.clone(), ext_x.clone()], false),
1003 (vec![ext_y.clone(), ext_x, ext_y], false),
1004 ];
1005
1006 for (test, should_work) in tests.into_iter() {
1007 {
1009 let mut extensions: Extensions<AnyObject> = Extensions::default();
1010
1011 let mut works = true;
1012 for ext in test.iter() {
1013 match extensions.add(ext.clone()) {
1014 Ok(_) => {}
1015 Err(InvalidExtensionError::Duplicate) => {
1016 works = false;
1017 }
1018 _ => panic!("This should have never happened."),
1019 }
1020 }
1021
1022 println!("{:?}, {:?}", test.clone(), should_work);
1023 assert_eq!(works, should_work);
1024 }
1025
1026 if should_work {
1028 assert!(Extensions::<AnyObject>::try_from(test).is_ok());
1029 } else {
1030 assert!(Extensions::<AnyObject>::try_from(test).is_err());
1031 }
1032 }
1033 }
1034
1035 #[test]
1036 fn ensure_ordering() {
1037 let ext_x = Extension::ApplicationId(ApplicationIdExtension::new(b"Test"));
1041 let ext_y = Extension::ExternalPub(ExternalPubExtension::new(HpkePublicKey::new(vec![])));
1042 let ext_z = Extension::RequiredCapabilities(RequiredCapabilitiesExtension::default());
1043
1044 for candidate in [ext_x, ext_y, ext_z]
1045 .into_iter()
1046 .permutations(3)
1047 .collect::<Vec<_>>()
1048 {
1049 let candidate: Extensions<AnyObject> = Extensions::try_from(candidate).unwrap();
1050 let bytes = candidate.tls_serialize_detached().unwrap();
1051 let got = Extensions::tls_deserialize(&mut bytes.as_slice()).unwrap();
1052 assert_eq!(candidate, got);
1053 }
1054 }
1055
1056 #[test]
1057 fn that_unknown_extensions_are_de_serialized_correctly() {
1058 let extension_types = [0x0000u16, 0x0A0A, 0x7A7A, 0xF100, 0xFFFF];
1059 let extension_datas = [vec![], vec![0], vec![1, 2, 3]];
1060
1061 for extension_type in extension_types.into_iter() {
1062 for extension_data in extension_datas.iter() {
1063 let test = {
1065 let mut buf = extension_type.to_be_bytes().to_vec();
1066 buf.append(
1067 &mut VLBytes::new(extension_data.clone())
1068 .tls_serialize_detached()
1069 .unwrap(),
1070 );
1071 buf
1072 };
1073
1074 let got = Extension::tls_deserialize_exact(&test).unwrap();
1076
1077 match got {
1078 Extension::Unknown(got_extension_type, ref got_extension_data) => {
1079 assert_eq!(extension_type, got_extension_type);
1080 assert_eq!(extension_data, &got_extension_data.0);
1081 }
1082 other => panic!("Expected `Extension::Unknown`, got {other:?}"),
1083 }
1084
1085 let got_serialized = got.tls_serialize_detached().unwrap();
1087 assert_eq!(test, got_serialized);
1088 }
1089 }
1090 }
1091}