Skip to main content

openmls/messages/
group_info.rs

1//! This module contains all types related to group info handling.
2
3use openmls_traits::crypto::OpenMlsCrypto;
4use openmls_traits::types::Ciphersuite;
5use serde::{Deserialize as SerdeDeserialize, Serialize as SerdeSerialize};
6use thiserror::Error;
7use tls_codec::{
8    Deserialize, Serialize as TlsSerializeTrait, TlsDeserialize, TlsDeserializeBytes, TlsSerialize,
9    TlsSize,
10};
11
12use crate::{
13    binary_tree::LeafNodeIndex,
14    ciphersuite::{
15        signable::{Signable, SignedStruct, Verifiable, VerifiedStruct},
16        AeadKey, AeadNonce, Signature,
17    },
18    extensions::{errors::InvalidExtensionError, Extension, Extensions},
19    group::{GroupContext, GroupEpoch, GroupId},
20    messages::ConfirmationTag,
21    prelude::ExtensionTypeNotValidInGroupInfoError,
22};
23
24const SIGNATURE_GROUP_INFO_LABEL: &str = "GroupInfoTBS";
25
26/// A type that represents a group info of which the signature has not been verified.
27/// It implements the [`Verifiable`] trait and can be turned into a group info by calling
28/// `verify(...)` with the signature key of the [`Credential`](crate::credentials::Credential).
29/// When receiving a serialized group info, it can only be deserialized into a
30/// [`VerifiableGroupInfo`], which can then be turned into a group info as described above.
31#[derive(Debug, PartialEq, Clone, TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize)]
32pub struct VerifiableGroupInfo {
33    payload: GroupInfoTBS,
34    signature: Signature,
35}
36
37/// Error related to group info.
38#[derive(Error, Debug, PartialEq, Clone)]
39pub enum GroupInfoError {
40    /// Decryption failed.
41    #[error("Decryption failed.")]
42    DecryptionFailed,
43    /// Malformed.
44    #[error("Malformed.")]
45    Malformed,
46}
47
48impl VerifiableGroupInfo {
49    /// Create a new [`VerifiableGroupInfo`] from its contents.
50    pub fn new(
51        group_context: GroupContext,
52        extensions: Extensions<GroupInfo>,
53        confirmation_tag: ConfirmationTag,
54        signer: LeafNodeIndex,
55        signature: Signature,
56    ) -> Self {
57        let payload = GroupInfoTBS {
58            group_context,
59            extensions,
60            confirmation_tag,
61            signer,
62        };
63        Self { payload, signature }
64    }
65
66    pub(crate) fn try_from_ciphertext(
67        skey: &AeadKey,
68        nonce: &AeadNonce,
69        ciphertext: &[u8],
70        context: &[u8],
71        crypto: &impl OpenMlsCrypto,
72    ) -> Result<Self, GroupInfoError> {
73        let verifiable_group_info_plaintext = skey
74            .aead_open(crypto, ciphertext, context, nonce)
75            .map_err(|_| GroupInfoError::DecryptionFailed)?;
76
77        let mut verifiable_group_info_plaintext_slice = verifiable_group_info_plaintext.as_slice();
78
79        let verifiable_group_info =
80            VerifiableGroupInfo::tls_deserialize(&mut verifiable_group_info_plaintext_slice)
81                .map_err(|_| GroupInfoError::Malformed)?;
82
83        if !verifiable_group_info_plaintext_slice.is_empty() {
84            return Err(GroupInfoError::Malformed);
85        }
86
87        Ok(verifiable_group_info)
88    }
89
90    /// Get (unverified) ciphersuite of the verifiable group info.
91    ///
92    /// Note: This method should only be used when necessary to verify the group info signature.
93    pub fn ciphersuite(&self) -> Ciphersuite {
94        self.payload.group_context.ciphersuite()
95    }
96
97    /// Get (unverified) signer of the verifiable group info.
98    ///
99    /// Note: This method should only be used when necessary to verify the group info signature.
100    pub(crate) fn signer(&self) -> LeafNodeIndex {
101        self.payload.signer
102    }
103
104    /// Get (unverified) extensions of the verifiable group info.
105    ///
106    /// Note: This method should only be used when necessary to verify the group info signature.
107    pub fn extensions(&self) -> &Extensions<GroupInfo> {
108        &self.payload.extensions
109    }
110
111    /// Get (unverified) group ID of the verifiable group info.
112    ///
113    /// Note: This method should only be used when necessary to verify the group
114    /// info signature.
115    pub fn group_id(&self) -> &GroupId {
116        self.payload.group_context.group_id()
117    }
118
119    /// Get (unverified) epoch of the verifiable group info.
120    ///
121    /// Note: This method should only be used when necessary to verify the group
122    /// info signature.
123    pub fn epoch(&self) -> GroupEpoch {
124        self.payload.group_context.epoch()
125    }
126
127    /// Get (unverified) group context of the verifiable group info.
128    pub fn group_context(&self) -> &GroupContext {
129        &self.payload.group_context
130    }
131}
132
133#[cfg(test)]
134impl VerifiableGroupInfo {
135    pub(crate) fn payload_mut(&mut self) -> &mut GroupInfoTBS {
136        &mut self.payload
137    }
138
139    /// Break the signature for testing purposes.
140    pub(crate) fn break_signature(&mut self) {
141        self.signature.modify(b"");
142    }
143}
144
145#[cfg(any(feature = "test-utils", test))]
146impl From<VerifiableGroupInfo> for GroupInfo {
147    fn from(vgi: VerifiableGroupInfo) -> Self {
148        GroupInfo {
149            payload: vgi.payload,
150            signature: vgi.signature,
151            serialized_payload: None,
152        }
153    }
154}
155
156/// GroupInfo
157///
158/// Note: The struct is split into a `GroupInfoTBS` payload and a signature.
159///
160/// ```c
161/// // draft-ietf-mls-protocol-16
162///
163/// struct {
164///     GroupContext group_context;
165///     Extension extensions<V>;
166///     MAC confirmation_tag;
167///     uint32 signer;
168///     /* SignWithLabel(., "GroupInfoTBS", GroupInfoTBS) */
169///     opaque signature<V>;
170/// } GroupInfo;
171/// ```
172#[derive(Debug, PartialEq, Clone, TlsSize, SerdeSerialize, SerdeDeserialize)]
173#[cfg_attr(feature = "test-utils", derive(TlsDeserialize))]
174pub struct GroupInfo {
175    payload: GroupInfoTBS,
176    signature: Signature,
177    #[serde(skip)]
178    #[tls_codec(skip)]
179    serialized_payload: Option<Vec<u8>>,
180}
181
182impl TlsSerializeTrait for GroupInfo {
183    fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> {
184        let mut written = 0;
185        if let Some(ref bytes) = self.serialized_payload {
186            written += writer.write(bytes)?;
187        } else {
188            written += self.payload.tls_serialize(writer)?;
189        }
190        written += self.signature.tls_serialize(writer)?;
191        Ok(written)
192    }
193}
194
195impl GroupInfo {
196    /// Returns the group context.
197    pub fn group_context(&self) -> &GroupContext {
198        &self.payload.group_context
199    }
200
201    /// Returns the [`GroupInfo`] extensions.
202    pub fn extensions(&self) -> &Extensions<GroupInfo> {
203        &self.payload.extensions
204    }
205
206    /// Returns the [`GroupInfo`] signature.
207    pub fn signature(&self) -> &Signature {
208        &self.signature
209    }
210
211    /// Returns the confirmation tag.
212    pub(crate) fn confirmation_tag(&self) -> &ConfirmationTag {
213        &self.payload.confirmation_tag
214    }
215
216    /// Returns the GroupInfo with a type that signals it is unverified.
217    /// A form of downcasting to an equivalent type with a weaker type invariant.
218    pub(crate) fn into_verifiable_group_info(self) -> VerifiableGroupInfo {
219        VerifiableGroupInfo {
220            payload: GroupInfoTBS {
221                group_context: self.payload.group_context,
222                extensions: self.payload.extensions,
223                confirmation_tag: self.payload.confirmation_tag,
224                signer: self.payload.signer,
225            },
226            signature: self.signature,
227        }
228    }
229}
230
231/// GroupInfo (To Be Signed)
232///
233/// ```c
234/// // draft-ietf-mls-protocol-16
235///
236/// struct {
237///     GroupContext group_context;
238///     Extension extensions<V>;
239///     MAC confirmation_tag;
240///     uint32 signer;
241/// } GroupInfoTBS;
242/// ```
243#[derive(
244    Debug,
245    PartialEq,
246    Clone,
247    TlsDeserialize,
248    TlsDeserializeBytes,
249    TlsSerialize,
250    TlsSize,
251    SerdeSerialize,
252    SerdeDeserialize,
253)]
254pub(crate) struct GroupInfoTBS {
255    group_context: GroupContext,
256    extensions: Extensions<GroupInfo>,
257    confirmation_tag: ConfirmationTag,
258    signer: LeafNodeIndex,
259}
260
261impl GroupInfoTBS {
262    /// Create a new to-be-signed group info.
263    pub(crate) fn new(
264        group_context: GroupContext,
265        extensions: Extensions<GroupInfo>,
266        confirmation_tag: ConfirmationTag,
267        signer: LeafNodeIndex,
268    ) -> Result<Self, InvalidExtensionError> {
269        // validate the extensions
270        for extension_type in extensions.iter().map(Extension::extension_type) {
271            if extension_type.is_valid_in_group_info() == Some(false) {
272                return Err(InvalidExtensionError::ExtensionTypeNotValidInGroupInfo(
273                    ExtensionTypeNotValidInGroupInfoError(extension_type),
274                ));
275            }
276        }
277
278        Ok(Self {
279            group_context,
280            extensions,
281            confirmation_tag,
282            signer,
283        })
284    }
285}
286
287#[cfg(test)]
288impl GroupInfoTBS {
289    pub(crate) fn group_context_mut(&mut self) -> &mut GroupContext {
290        &mut self.group_context
291    }
292}
293
294// -------------------------------------------------------------------------------------------------
295
296impl Signable for GroupInfoTBS {
297    type SignedOutput = GroupInfo;
298
299    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
300        self.tls_serialize_detached()
301    }
302
303    fn label(&self) -> &str {
304        SIGNATURE_GROUP_INFO_LABEL
305    }
306}
307
308impl SignedStruct<GroupInfoTBS> for GroupInfo {
309    fn from_payload(
310        payload: GroupInfoTBS,
311        signature: Signature,
312        serialized_payload: Vec<u8>,
313    ) -> Self {
314        Self {
315            payload,
316            signature,
317            serialized_payload: Some(serialized_payload),
318        }
319    }
320}
321
322impl Verifiable for VerifiableGroupInfo {
323    type VerifiedStruct = GroupInfo;
324
325    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
326        self.payload.tls_serialize_detached()
327    }
328
329    fn signature(&self) -> &Signature {
330        &self.signature
331    }
332
333    fn label(&self) -> &str {
334        SIGNATURE_GROUP_INFO_LABEL
335    }
336
337    fn verify(
338        self,
339        crypto: &impl OpenMlsCrypto,
340        pk: &crate::ciphersuite::OpenMlsSignaturePublicKey,
341    ) -> Result<Self::VerifiedStruct, crate::ciphersuite::signable::SignatureError> {
342        self.verify_no_out(crypto, pk)?;
343        Ok(GroupInfo {
344            payload: self.payload,
345            signature: self.signature,
346            serialized_payload: None,
347        })
348    }
349}
350
351impl VerifiedStruct for GroupInfo {}