Skip to main content

openmls/extensions/
mod.rs

1//! # Extensions
2//!
3//! In MLS, extensions appear in the following places:
4//!
5//! - In [`KeyPackages`](`crate::key_packages`) and [`LeafNode`](`crate::treesync::node::leaf_node::LeafNode`),
6//!   to describe client capabilities
7//!   and aspects of their participation in the group.
8//!
9//! - In `GroupInfo`, to inform new members of the group's parameters and to
10//!   provide any additional information required to join the group.
11//!
12//! - In the `GroupContext` object, to ensure that all members of the group have
13//!   a consistent view of the parameters in use.
14//!
15//! Note that `GroupInfo` and `GroupContext` are not exposed via OpenMLS' public
16//! API.
17//!
18//! OpenMLS supports the following extensions:
19//!
20//! - [`ApplicationIdExtension`] (KeyPackage extension)
21//! - [`RatchetTreeExtension`] (GroupInfo extension)
22//! - [`RequiredCapabilitiesExtension`] (GroupContext extension)
23//! - [`ExternalPubExtension`] (GroupInfo extension)
24//! - [`ExternalSendersExtension`] (GroupContext extension)
25//! - [`LastResortExtension`] (KeyPackage extension)
26
27use 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// Private
38#[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
50// Public
51pub mod errors;
52
53// Public re-exports
54#[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/// MLS Extension Types
79///
80/// Copied from draft-ietf-mls-protocol-16:
81///
82/// | Value            | Name                     | Message(s) | Recommended | Reference |
83/// |:-----------------|:-------------------------|:-----------|:------------|:----------|
84/// | 0x0000           | RESERVED                 | N/A        | N/A         | RFC XXXX  |
85/// | 0x0001           | application_id           | LN         | Y           | RFC XXXX  |
86/// | 0x0002           | ratchet_tree             | GI         | Y           | RFC XXXX  |
87/// | 0x0003           | required_capabilities    | GC         | Y           | RFC XXXX  |
88/// | 0x0004           | external_pub             | GI         | Y           | RFC XXXX  |
89/// | 0x0005           | external_senders         | GC         | Y           | RFC XXXX  |
90/// | 0xff00  - 0xffff | Reserved for Private Use | N/A        | N/A         | RFC XXXX  |
91///
92/// Note: OpenMLS does not provide a `Reserved` variant in [ExtensionType].
93#[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    /// The application id extension allows applications to add an explicit,
108    /// application-defined identifier to a KeyPackage.
109    ApplicationId,
110
111    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 1)]
112    /// The ratchet tree extensions provides the whole public state of the
113    /// ratchet tree.
114    RatchetTree,
115
116    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 2)]
117    /// The required capabilities extension defines the configuration of a group
118    /// that imposes certain requirements on clients in the group.
119    RequiredCapabilities,
120
121    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 3)]
122    /// To join a group via an External Commit, a new member needs a GroupInfo
123    /// with an ExternalPub extension present in its extensions field.
124    ExternalPub,
125
126    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 4)]
127    /// Group context extension that contains the credentials and signature keys
128    /// of senders that are permitted to send external proposals to the group.
129    ExternalSenders,
130
131    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 5)]
132    /// KeyPackage extension that marks a KeyPackage for use in a last resort
133    /// scenario.
134    LastResort,
135
136    #[cfg(feature = "extensions-draft")]
137    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 8)]
138    /// AppDataDictionary extension
139    AppDataDictionary,
140
141    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 7)]
142    /// A GREASE extension type for ensuring extensibility.
143    Grease(u16),
144
145    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 6)]
146    /// A currently unknown extension type.
147    Unknown(u16),
148}
149
150impl ExtensionType {
151    /// Returns true for all extension types that are considered "default" by the spec.
152    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    /// Returns whether an extension type is valid when used in leaf nodes.
168    /// Returns [`true`] for unknown extensions.
169    //  https://validation.openmls.tech/#valn1601
170    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            // GREASE may appear as an extension type in `leaf_node.extensions`
178            // and must be tolerated there. It is still subject to the normal rule
179            // that it must be declared in `capabilities` (checked separately),
180            // so this only permits the type, it does not exempt it from that check.
181            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            // GREASE is treated like an unknown extension type (tolerated): a
196            // GREASE-valued extension used to be reported as `Unknown` here, and
197            // must not become stricter now that it maps to `Grease`.
198            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            // GREASE may appear as an extension type in `key_package.extensions`
212            // and must be tolerated there. It is still subject to the normal rule
213            // that it be declared in `capabilities` (checked separately), so this
214            // only permits the type, it does not exempt it from that check.
215            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            // GREASE is treated like an unknown extension type: structurally
229            // allowed to appear here, but (like any unknown extension in the
230            // GroupContext) still subject to the per-member support check, which
231            // enforces the consensus rule that every member support it. GREASE
232            // does not bypass that check.
233            ExtensionType::Grease(_) => true,
234            #[cfg(feature = "extensions-draft")]
235            ExtensionType::AppDataDictionary => true,
236            _ => false,
237        }
238    }
239
240    /// Returns true if this is a GREASE extension type.
241    ///
242    /// GREASE values are used to ensure implementations properly handle unknown
243    /// extension types. See [RFC 9420 Section 13.5](https://www.rfc-editor.org/rfc/rfc9420.html#section-13.5).
244    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        // `Unknown` and `Grease` accept any value. Refuse to encode one that
282        // would decode as a different extension type.
283        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/// # Extension
329///
330/// An extension is one of the [`Extension`] enum values.
331/// The enum provides a set of common functionality for all extensions.
332///
333/// See the individual extensions for more details on each extension.
334///
335/// ```c
336/// // draft-ietf-mls-protocol-16
337/// struct {
338///     ExtensionType extension_type;
339///     opaque extension_data<V>;
340/// } Extension;
341/// ```
342#[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    /// An [`ApplicationIdExtension`]
357    ApplicationId(ApplicationIdExtension),
358
359    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 1)]
360    /// A [`RatchetTreeExtension`]
361    RatchetTree(RatchetTreeExtension),
362
363    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 2)]
364    /// A [`RequiredCapabilitiesExtension`]
365    RequiredCapabilities(RequiredCapabilitiesExtension),
366
367    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 3)]
368    /// An [`ExternalPubExtension`]
369    ExternalPub(ExternalPubExtension),
370
371    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 4)]
372    /// An [`ExternalSendersExtension`]
373    ExternalSenders(ExternalSendersExtension),
374
375    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 7)]
376    /// An [`AppDataDictionaryExtension`]
377    #[cfg(feature = "extensions-draft")]
378    AppDataDictionary(AppDataDictionaryExtension),
379
380    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 5)]
381    /// A [`LastResortExtension`]
382    LastResort(LastResortExtension),
383
384    #[cfg_attr(not(feature = "0-8-1-storage-format"), storage_tag = 6)]
385    /// A currently unknown extension.
386    Unknown(u16, UnknownExtension),
387}
388
389/// A unknown/unparsed extension represented by raw bytes.
390#[derive(
391    PartialEq, Eq, Clone, Debug, Serialize, Deserialize, TlsSize, TlsSerialize, TlsDeserialize,
392)]
393pub struct UnknownExtension(pub Vec<u8>);
394
395/// A Extension for Object of type T
396///
397/// Deserializing `Extensions` with serde does not run the checks of
398/// [`Extensions::from_vec`]. Only deserialize data that was serialized by this
399/// application.
400#[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)]
408/// Any object
409pub 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    /// Create an empty extension list.
462    pub fn empty() -> Self {
463        Self {
464            unique: vec![],
465            _object: PhantomData,
466        }
467    }
468
469    /// Returns an iterator over the extension list.
470    pub fn iter(&self) -> impl Iterator<Item = &Extension> {
471        self.unique.iter()
472    }
473
474    /// Remove an extension from the extension list.
475    ///
476    /// Returns the removed extension or `None` when there is no extension with
477    /// the given extension type.
478    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    /// Returns `true` iff the extension list contains an extension with the
491    /// given extension type.
492    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    /// Create an extension list with a single extension.
505    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    /// Create an extension list with multiple extensions.
514    ///
515    /// This function will fail when the list of extensions contains duplicate
516    /// extension types.
517    pub fn from_vec(extensions: Vec<Extension>) -> Result<Self, InvalidExtensionError> {
518        extensions.try_into()
519    }
520
521    /// Validate if the extensions are valid for this context
522    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    /// Add an extension to the extension list.
532    ///
533    /// Returns an error when there already is an extension with the same
534    /// extension type.
535    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    /// Add an extension to the extension list (or replace an existing one.)
547    ///
548    /// Returns the replaced extension (if any).
549    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    /// Assume that the extensions contain the given extension type.
562    ///
563    /// # Safety
564    ///
565    /// The caller must guarantee that the extensions are of the correct type.
566    #[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    /// Used to seal other traits
577    pub trait Sealed {}
578}
579
580/// Can be implemented by a type to validate extensions.
581pub trait ExtensionValidator: private::Sealed {
582    /// The error returned by the validator
583    type Error;
584
585    /// Check if the extension is valid.
586    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
624// https://validation.openmls.tech/#valn1602
625impl 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
643// https://validation.openmls.tech/#valn1603
644impl 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
660// https://validation.openmls.tech/#valn1604
661impl 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
677// https://validation.openmls.tech/#valn1601
678impl 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    /// Get a reference to the [`ApplicationIdExtension`] if there is any.
700    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    /// Get a reference to the [`RatchetTreeExtension`] if there is any.
709    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    /// Get a reference to the [`RequiredCapabilitiesExtension`] if there is
718    /// any.
719    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    /// Get a reference to the [`ExternalPubExtension`] if there is any.
728    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    /// Get a reference to the [`ExternalSendersExtension`] if there is any.
737    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    /// Get a reference to the [`AppDataDictionaryExtension`] if there is any.
747    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    /// Get a reference to the [`UnknownExtension`] with the given type id, if there is any.
756    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    /// Get a reference to this extension as [`ApplicationIdExtension`].
773    /// Returns an [`ExtensionError::InvalidExtensionType`] if called on an
774    /// [`Extension`] that's not an [`ApplicationIdExtension`].
775    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    /// Get a reference to this extension as [`AppDataDictionaryExtension`].
785    /// Returns an [`ExtensionError::InvalidExtensionType`] if called on an
786    /// [`Extension`] that's not an [`AppDataDictionaryExtension`].
787    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    /// Get a reference to this extension as [`RatchetTreeExtension`].
799    /// Returns an [`ExtensionError::InvalidExtensionType`] if called on
800    /// an [`Extension`] that's not a [`RatchetTreeExtension`].
801    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    /// Get a reference to this extension as [`RequiredCapabilitiesExtension`].
811    /// Returns an [`ExtensionError::InvalidExtensionType`] error if called on
812    /// an [`Extension`] that's not a [`RequiredCapabilitiesExtension`].
813    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    /// Get a reference to this extension as [`ExternalPubExtension`].
825    /// Returns an [`ExtensionError::InvalidExtensionType`] error if called on
826    /// an [`Extension`] that's not a [`ExternalPubExtension`].
827    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    /// Get a reference to this extension as [`ExternalSendersExtension`].
837    /// Returns an [`ExtensionError::InvalidExtensionType`] error if called on
838    /// an [`Extension`] that's not a [`ExternalSendersExtension`].
839    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    /// Returns the [`ExtensionType`]
851    #[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            // Map GREASE-valued extension types to `Grease`, consistent with
863            // `ExtensionType::from(u16)`. Without this an extension carrying a
864            // GREASE value would be reported as `Unknown`, so GREASE-aware
865            // validation (which ignores `Grease(_)`) would not recognize it.
866            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    /// Coerces the extensions to an Extensions with the given validator. Unsafe.
911    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        // A GREASE-valued extension must report a `Grease` extension type
943        // (consistent with `ExtensionType::from(u16)`), not `Unknown`. Otherwise
944        // GREASE-aware validation would fail to recognize it and reject peers
945        // (e.g. MLS++) that decorate leaf/key-package extensions with GREASE.
946        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        // A non-GREASE unknown value stays `Unknown`.
951        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        // GREASE does NOT bypass the capability check: a GREASE extension type is
958        // "contained" only if it is advertised in the capabilities (RFC 9420:
959        // extensions in leaf_node.extensions/key_package.extensions MUST be in
960        // capabilities). The fix that makes this work is that a GREASE-valued
961        // extension now reports a `Grease(_)` type that matches the `Grease(_)`
962        // parsed into the capabilities list.
963        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        // A GREASE value that is not advertised is not contained.
972        assert!(!advertised.contains_extension_type(&ExtensionType::Grease(0xAAAA)));
973
974        // Empty capabilities contain no (non-default) extension, GREASE included.
975        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        // Create some extensions with different extension types and test that
984        // duplicates are rejected. The extension content does not matter in this test.
985        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            // Test `add`.
1008            {
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            // Test `try_from`.
1027            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        // Create some extensions with different extension types and test
1038        // that all permutations keep their order after being (de)serialized.
1039        // The extension content does not matter in this test.
1040        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                // Construct an unknown extension manually.
1064                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                // Test deserialization.
1075                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                // Test serialization.
1086                let got_serialized = got.tls_serialize_detached().unwrap();
1087                assert_eq!(test, got_serialized);
1088            }
1089        }
1090    }
1091}