1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//! # Proposals
//!
//! This module defines all the different types of Proposals.

use crate::{
    ciphersuite::{hash_ref::ProposalRef, signable::Verifiable},
    credentials::CredentialWithKey,
    framing::SenderContext,
    group::errors::ValidationError,
    key_packages::*,
    treesync::node::leaf_node::{LeafNodeIn, TreePosition, VerifiableLeafNode},
    versions::ProtocolVersion,
};

use openmls_traits::{crypto::OpenMlsCrypto, types::Ciphersuite};
use serde::{Deserialize, Serialize};
use tls_codec::{TlsDeserialize, TlsDeserializeBytes, TlsSerialize, TlsSize};

use super::{
    proposals::{
        AddProposal, AppAckProposal, ExternalInitProposal, GroupContextExtensionProposal,
        PreSharedKeyProposal, Proposal, ProposalOrRef, ProposalType, ReInitProposal,
        RemoveProposal, UpdateProposal,
    },
    CustomProposal,
};

/// Proposal.
///
/// This `enum` contains the different proposals in its variants.
///
/// ```c
/// // draft-ietf-mls-protocol-17
/// struct {
///     ProposalType msg_type;
///     select (Proposal.msg_type) {
///         case add:                      Add;
///         case update:                   Update;
///         case remove:                   Remove;
///         case psk:                      PreSharedKey;
///         case reinit:                   ReInit;
///         case external_init:            ExternalInit;
///         case group_context_extensions: GroupContextExtensions;
///     };
/// } Proposal;
/// ```
#[allow(clippy::large_enum_variant)]
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
#[repr(u16)]
pub enum ProposalIn {
    Add(AddProposalIn),
    Update(UpdateProposalIn),
    Remove(RemoveProposal),
    PreSharedKey(PreSharedKeyProposal),
    ReInit(ReInitProposal),
    ExternalInit(ExternalInitProposal),
    GroupContextExtensions(GroupContextExtensionProposal),
    // # Extensions
    // TODO(#916): `AppAck` is not in draft-ietf-mls-protocol-17 but
    //             was moved to `draft-ietf-mls-extensions-00`.
    AppAck(AppAckProposal),
    Custom(CustomProposal),
}

impl ProposalIn {
    /// Returns the proposal type.
    pub fn proposal_type(&self) -> ProposalType {
        match self {
            ProposalIn::Add(_) => ProposalType::Add,
            ProposalIn::Update(_) => ProposalType::Update,
            ProposalIn::Remove(_) => ProposalType::Remove,
            ProposalIn::PreSharedKey(_) => ProposalType::PreSharedKey,
            ProposalIn::ReInit(_) => ProposalType::Reinit,
            ProposalIn::ExternalInit(_) => ProposalType::ExternalInit,
            ProposalIn::GroupContextExtensions(_) => ProposalType::GroupContextExtensions,
            ProposalIn::AppAck(_) => ProposalType::AppAck,
            ProposalIn::Custom(custom_proposal) => {
                ProposalType::Custom(custom_proposal.proposal_type())
            }
        }
    }

    /// Indicates whether a Commit containing this [ProposalIn] requires a path.
    pub fn is_path_required(&self) -> bool {
        self.proposal_type().is_path_required()
    }

    /// Returns a [`Proposal`] after successful validation.
    pub(crate) fn validate(
        self,
        crypto: &impl OpenMlsCrypto,
        ciphersuite: Ciphersuite,
        sender_context: Option<SenderContext>,
        protocol_version: ProtocolVersion,
    ) -> Result<Proposal, ValidationError> {
        Ok(match self {
            ProposalIn::Add(add) => {
                Proposal::Add(add.validate(crypto, protocol_version, ciphersuite)?)
            }
            ProposalIn::Update(update) => {
                let sender_context =
                    sender_context.ok_or(ValidationError::CommitterIncludedOwnUpdate)?;
                Proposal::Update(update.validate(crypto, ciphersuite, sender_context)?)
            }
            ProposalIn::Remove(remove) => Proposal::Remove(remove),
            ProposalIn::PreSharedKey(psk) => Proposal::PreSharedKey(psk),
            ProposalIn::ReInit(reinit) => Proposal::ReInit(reinit),
            ProposalIn::ExternalInit(external_init) => Proposal::ExternalInit(external_init),
            ProposalIn::GroupContextExtensions(group_context_extension) => {
                Proposal::GroupContextExtensions(group_context_extension)
            }
            ProposalIn::AppAck(app_ack) => Proposal::AppAck(app_ack),
            ProposalIn::Custom(custom) => Proposal::Custom(custom),
        })
    }
}

/// Add Proposal.
///
/// An Add proposal requests that a client with a specified [`KeyPackage`] be added to the group.
///
/// ```c
/// // draft-ietf-mls-protocol-17
/// struct {
///     KeyPackage key_package;
/// } Add;
/// ```
#[derive(
    Debug,
    PartialEq,
    Clone,
    Serialize,
    Deserialize,
    TlsSerialize,
    TlsDeserialize,
    TlsDeserializeBytes,
    TlsSize,
)]
pub struct AddProposalIn {
    key_package: KeyPackageIn,
}

impl AddProposalIn {
    pub(crate) fn unverified_credential(&self) -> CredentialWithKey {
        self.key_package.unverified_credential()
    }

    /// Returns a [`AddProposal`] after successful validation.
    pub(crate) fn validate(
        self,
        crypto: &impl OpenMlsCrypto,
        protocol_version: ProtocolVersion,
        ciphersuite: Ciphersuite,
    ) -> Result<AddProposal, ValidationError> {
        let key_package = self.key_package.validate(crypto, protocol_version)?;
        // Verify that the ciphersuite is valid
        if key_package.ciphersuite() != ciphersuite {
            return Err(ValidationError::InvalidAddProposalCiphersuite);
        }
        Ok(AddProposal { key_package })
    }
}

/// Update Proposal.
///
/// An Update proposal is a similar mechanism to [`AddProposalIn`] with the distinction that it
/// replaces the sender's leaf node instead of adding a new leaf to the tree.
///
/// ```c
/// // draft-ietf-mls-protocol-17
/// struct {
///     LeafNode leaf_node;
/// } Update;
/// ```
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    Serialize,
    Deserialize,
    TlsDeserialize,
    TlsDeserializeBytes,
    TlsSerialize,
    TlsSize,
)]
pub struct UpdateProposalIn {
    leaf_node: LeafNodeIn,
}

impl UpdateProposalIn {
    /// Returns a [`UpdateProposal`] after successful validation.
    pub(crate) fn validate(
        self,
        crypto: &impl OpenMlsCrypto,
        ciphersuite: Ciphersuite,
        sender_context: SenderContext,
    ) -> Result<UpdateProposal, ValidationError> {
        let leaf_node = match self.leaf_node.into_verifiable_leaf_node() {
            VerifiableLeafNode::Update(mut leaf_node) => {
                let tree_position = match sender_context {
                    SenderContext::Member((group_id, leaf_index)) => {
                        TreePosition::new(group_id, leaf_index)
                    }
                    _ => return Err(ValidationError::InvalidSenderType),
                };
                leaf_node.add_tree_position(tree_position);
                let pk = &leaf_node
                    .signature_key()
                    .clone()
                    .into_signature_public_key_enriched(ciphersuite.signature_algorithm());

                leaf_node
                    .verify(crypto, pk)
                    .map_err(|_| ValidationError::InvalidLeafNodeSignature)?
            }
            _ => return Err(ValidationError::InvalidLeafNodeSourceType),
        };

        Ok(UpdateProposal { leaf_node })
    }
}

// Crate-only types

/// Type of Proposal, either by value or by reference.
#[derive(
    Debug,
    PartialEq,
    Clone,
    Serialize,
    Deserialize,
    TlsSerialize,
    TlsDeserialize,
    TlsDeserializeBytes,
    TlsSize,
)]
#[repr(u8)]
#[allow(missing_docs)]
#[allow(clippy::large_enum_variant)]
pub(crate) enum ProposalOrRefIn {
    #[tls_codec(discriminant = 1)]
    Proposal(ProposalIn),
    Reference(ProposalRef),
}

impl ProposalOrRefIn {
    /// Returns a [`ProposalOrRef`] after successful validation.
    pub(crate) fn validate(
        self,
        crypto: &impl OpenMlsCrypto,
        ciphersuite: Ciphersuite,
        protocol_version: ProtocolVersion,
    ) -> Result<ProposalOrRef, ValidationError> {
        Ok(match self {
            ProposalOrRefIn::Proposal(proposal_in) => ProposalOrRef::Proposal(
                proposal_in.validate(crypto, ciphersuite, None, protocol_version)?,
            ),
            ProposalOrRefIn::Reference(reference) => ProposalOrRef::Reference(reference),
        })
    }
}

// The following `From` implementation breaks abstraction layers and MUST
// NOT be made available outside of tests or "test-utils".
#[cfg(any(feature = "test-utils", test))]
impl From<AddProposalIn> for crate::messages::proposals::AddProposal {
    fn from(value: AddProposalIn) -> Self {
        Self {
            key_package: value.key_package.into(),
        }
    }
}

impl From<crate::messages::proposals::AddProposal> for AddProposalIn {
    fn from(value: crate::messages::proposals::AddProposal) -> Self {
        Self {
            key_package: value.key_package.into(),
        }
    }
}

// The following `From` implementation( breaks abstraction layers and MUST
// NOT be made available outside of tests or "test-utils".
#[cfg(any(feature = "test-utils", test))]
impl From<UpdateProposalIn> for crate::messages::proposals::UpdateProposal {
    fn from(value: UpdateProposalIn) -> Self {
        Self {
            leaf_node: value.leaf_node.into(),
        }
    }
}

impl From<crate::messages::proposals::UpdateProposal> for UpdateProposalIn {
    fn from(value: crate::messages::proposals::UpdateProposal) -> Self {
        Self {
            leaf_node: value.leaf_node.into(),
        }
    }
}

#[cfg(any(feature = "test-utils", test))]
impl From<ProposalIn> for crate::messages::proposals::Proposal {
    fn from(proposal: ProposalIn) -> Self {
        match proposal {
            ProposalIn::Add(add) => Self::Add(add.into()),
            ProposalIn::Update(update) => Self::Update(update.into()),
            ProposalIn::Remove(remove) => Self::Remove(remove),
            ProposalIn::PreSharedKey(psk) => Self::PreSharedKey(psk),
            ProposalIn::ReInit(reinit) => Self::ReInit(reinit),
            ProposalIn::ExternalInit(external_init) => Self::ExternalInit(external_init),
            ProposalIn::GroupContextExtensions(group_context_extension) => {
                Self::GroupContextExtensions(group_context_extension)
            }
            ProposalIn::AppAck(app_ack) => Self::AppAck(app_ack),
            ProposalIn::Custom(other) => Self::Custom(other),
        }
    }
}

impl From<crate::messages::proposals::Proposal> for ProposalIn {
    fn from(proposal: crate::messages::proposals::Proposal) -> Self {
        match proposal {
            Proposal::Add(add) => Self::Add(add.into()),
            Proposal::Update(update) => Self::Update(update.into()),
            Proposal::Remove(remove) => Self::Remove(remove),
            Proposal::PreSharedKey(psk) => Self::PreSharedKey(psk),
            Proposal::ReInit(reinit) => Self::ReInit(reinit),
            Proposal::ExternalInit(external_init) => Self::ExternalInit(external_init),
            Proposal::GroupContextExtensions(group_context_extension) => {
                Self::GroupContextExtensions(group_context_extension)
            }
            Proposal::AppAck(app_ack) => Self::AppAck(app_ack),
            Proposal::Custom(other) => Self::Custom(other),
        }
    }
}

#[cfg(any(feature = "test-utils", test))]
impl From<ProposalOrRefIn> for crate::messages::proposals::ProposalOrRef {
    fn from(proposal: ProposalOrRefIn) -> Self {
        match proposal {
            ProposalOrRefIn::Proposal(proposal) => Self::Proposal(proposal.into()),
            ProposalOrRefIn::Reference(reference) => Self::Reference(reference),
        }
    }
}

impl From<crate::messages::proposals::ProposalOrRef> for ProposalOrRefIn {
    fn from(proposal: crate::messages::proposals::ProposalOrRef) -> Self {
        match proposal {
            crate::messages::proposals::ProposalOrRef::Proposal(proposal) => {
                Self::Proposal(proposal.into())
            }
            crate::messages::proposals::ProposalOrRef::Reference(reference) => {
                Self::Reference(reference)
            }
        }
    }
}