openmls/group/mls_group/config.rs
1//! Configuration module for [`MlsGroup`] configurations.
2//!
3//! ## Building an MlsGroupCreateConfig
4//! The [`MlsGroupCreateConfigBuilder`] makes it easy to build configurations for the
5//! [`MlsGroup`].
6//!
7//! ```
8//! use openmls::prelude::*;
9//!
10//! let group_config = MlsGroupCreateConfig::builder()
11//! .use_ratchet_tree_extension(true)
12//! .build();
13//! ```
14//!
15//! See [`MlsGroupCreateConfigBuilder`](MlsGroupCreateConfigBuilder#implementations) for
16//! all options that can be configured.
17//!
18//! ### Wire format policies
19//! Only some combination of possible wire formats are valid within OpenMLS.
20//! The [`WIRE_FORMAT_POLICIES`] lists all valid options that can be set.
21//!
22//! ```
23//! use openmls::prelude::*;
24//!
25//! let group_config = MlsGroupCreateConfig::builder()
26//! .wire_format_policy(MIXED_CIPHERTEXT_WIRE_FORMAT_POLICY)
27//! .build();
28//! ```
29
30#[cfg(not(target_arch = "wasm32"))]
31use std::time::SystemTime;
32#[cfg(target_arch = "wasm32")]
33use web_time::SystemTime;
34
35use super::*;
36use crate::{
37 extensions::Extensions,
38 key_packages::Lifetime,
39 tree::sender_ratchet::SenderRatchetConfiguration,
40 treesync::{
41 errors::LeafNodeValidationError,
42 node::leaf_node::{Capabilities, CapabilitiesPolicy},
43 },
44};
45use serde::{Deserialize, Serialize};
46
47/// Configures the automatic deletion of past epoch secrets.
48///
49/// **WARNING**
50///
51/// Policies other than `MaxEpochs(0)` enable the storage of message secrets from past epochs.
52/// It is a trade-off between functionality and forward secrecy and should only be enabled
53/// if the Delivery Service cannot guarantee that application messages will be sent in
54/// the same epoch in which they were generated. The number for `max_epochs` should be
55/// as low as possible.
56///
57/// If the MaxEpochs policy is set to MaxEpochs(usize::MAX), if will be returned
58/// as KeepAll after deserialization due to backwards compatibility constraints.
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub enum PastEpochDeletionPolicy {
61 /// Keep at most `n` past epoch secrets.
62 MaxEpochs(usize),
63 /// Keep all past epoch secrets.
64 ///
65 /// NOTE: The application is responsible for deleting past epoch secrets when
66 /// `KeepAll` is set. Past epoch secrets can be deleted manually using:
67 /// - [`MlsGroup::delete_past_epoch_secrets()`]
68 KeepAll,
69}
70
71impl Default for PastEpochDeletionPolicy {
72 fn default() -> Self {
73 Self::MaxEpochs(0)
74 }
75}
76
77impl Serialize for PastEpochDeletionPolicy {
78 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
79 where
80 S: serde::Serializer,
81 {
82 let usize = match self {
83 Self::MaxEpochs(epochs) => *epochs,
84 Self::KeepAll => usize::MAX,
85 };
86 serializer.serialize_u64(usize as u64)
87 }
88}
89
90impl<'de> Deserialize<'de> for PastEpochDeletionPolicy {
91 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
92 // Previously supported format (changed to plain integer in 8bdba6f)
93 #[derive(Deserialize)]
94 enum Tagged {
95 MaxEpochs(usize),
96 KeepAll,
97 }
98
99 #[derive(Deserialize)]
100 #[serde(untagged)]
101 enum Format {
102 Int(u64),
103 Tagged(Tagged),
104 }
105
106 Ok(match Format::deserialize(deserializer)? {
107 Format::Int(u64::MAX) => Self::KeepAll,
108 Format::Int(n) => {
109 Self::MaxEpochs(usize::try_from(n).map_err(serde::de::Error::custom)?)
110 }
111 Format::Tagged(Tagged::MaxEpochs(n)) => Self::MaxEpochs(n),
112 Format::Tagged(Tagged::KeepAll) => Self::KeepAll,
113 })
114 }
115}
116
117/// The input to [`MlsGroup::delete_past_epoch_secrets()`].
118///
119/// This struct can be used for manual deletion of past epoch secrets by the application.
120///
121/// An [`MlsGroup`] also applies automatic deletion of past epoch secrets by default.
122///
123/// For more information, see [`PastEpochDeletionPolicy`] and [`MlsGroup::set_past_epoch_deletion_policy()`].
124///
125/// These methods can be used by the application to set up time-based deletion schedules:
126/// - [`PastEpochDeletion::before_timestamp()`]
127/// - [`PastEpochDeletion::older_than_duration()`]
128///
129/// **NOTE**: Epoch secrets that were created using `openmls=0.8.1` or earlier will not yet include a timestamp.
130/// After migration, these may not always be deleted by applying a time-based [`PastEpochDeletion`]. Only if a new secret that does include a timestamp is added later, and it matches the time-based condition in the [`PastEpochDeletion`], all earlier past epoch secrets without timestamps will be deleted, as well. However, otherwise, past epoch secrets without timestamps will not be affected by applying time-based [`PastEpochDeletion`]s.
131///
132/// To manually delete all past epoch secrets without timestamps, see:
133/// [`PastEpochDeletion::delete_all_without_timestamps()`]
134pub struct PastEpochDeletion {
135 pub(crate) config: Option<PastEpochDeletionTimeConfig>,
136 pub(crate) max_past_epochs: Option<usize>,
137}
138
139/// A duration or timestamp before which to delete past epoch secrets.
140pub(crate) enum PastEpochDeletionTimeConfig {
141 OlderThanDuration(std::time::Duration),
142 BeforeTimestamp(SystemTime),
143 DeleteAllWithoutTimestamp,
144}
145
146impl PastEpochDeletion {
147 /// Delete all past epoch secrets older than a provided duration.
148 pub fn older_than_duration(duration: std::time::Duration) -> Self {
149 Self {
150 config: Some(PastEpochDeletionTimeConfig::OlderThanDuration(duration)),
151 max_past_epochs: None,
152 }
153 }
154
155 /// Delete all past epoch secrets before a provided timestamp.
156 pub fn before_timestamp(timestamp: SystemTime) -> Self {
157 Self {
158 config: Some(PastEpochDeletionTimeConfig::BeforeTimestamp(timestamp)),
159 max_past_epochs: None,
160 }
161 }
162
163 /// Delete all past epoch secrets without timestamps.
164 ///
165 /// NOTE: This will delete all past epoch secrets having the legacy
166 /// format that does not include a timestamp.
167 pub fn delete_all_without_timestamps() -> Self {
168 Self {
169 config: Some(PastEpochDeletionTimeConfig::DeleteAllWithoutTimestamp),
170 max_past_epochs: None,
171 }
172 }
173
174 /// Delete all past epoch secrets.
175 pub fn delete_all() -> Self {
176 Self {
177 config: None,
178 max_past_epochs: None,
179 }
180 }
181
182 /// Set the number of `max_past_epochs` that should be kept, at most.
183 pub fn max_past_epochs(mut self, max_past_epochs: usize) -> Self {
184 self.max_past_epochs = Some(max_past_epochs);
185 self
186 }
187}
188
189impl PastEpochDeletionPolicy {
190 pub(crate) fn max_epochs(&self) -> Option<usize> {
191 match self {
192 Self::MaxEpochs(epochs) => Some(*epochs),
193 Self::KeepAll => None,
194 }
195 }
196}
197
198/// Configures how many virtual-clients derivation epochs an emulation group
199/// keeps, so that delayed messages from sibling emulator clients can still be
200/// processed.
201///
202/// Registering a new derivation epoch drops the epochs beyond the window. Their
203/// key material is deleted unless a higher-level group or a retained KeyPackage
204/// still references it.
205#[cfg(feature = "virtual-clients-draft")]
206#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
207pub enum VcDerivationEpochRetentionPolicy {
208 /// Keep at most `n` derivation epochs.
209 MaxEpochs(usize),
210 /// Keep every derivation epoch. The application deletes them with
211 /// [`MlsGroup::delete_vc_derivation_epochs()`].
212 KeepAll,
213}
214
215#[cfg(feature = "virtual-clients-draft")]
216impl Default for VcDerivationEpochRetentionPolicy {
217 fn default() -> Self {
218 Self::MaxEpochs(5)
219 }
220}
221
222#[cfg(feature = "virtual-clients-draft")]
223impl VcDerivationEpochRetentionPolicy {
224 pub(crate) fn max_epochs(&self) -> Option<usize> {
225 match self {
226 Self::MaxEpochs(epochs) => Some(*epochs),
227 Self::KeepAll => None,
228 }
229 }
230}
231
232/// Selects the derivation epochs [`MlsGroup::delete_vc_derivation_epochs()`]
233/// deletes: those superseded before a point in time, optionally capped to a
234/// number of surviving epochs. An epoch is superseded when the next one is
235/// registered. The newest epoch is never selected.
236#[cfg(feature = "virtual-clients-draft")]
237pub struct VcDerivationEpochDeletion {
238 pub(crate) time: VcDerivationEpochDeletionTime,
239 pub(crate) max_epochs: Option<usize>,
240}
241
242/// A duration or timestamp before which superseded derivation epochs are
243/// deleted.
244#[cfg(feature = "virtual-clients-draft")]
245pub(crate) enum VcDerivationEpochDeletionTime {
246 OlderThanDuration(std::time::Duration),
247 BeforeTimestamp(SystemTime),
248}
249
250#[cfg(feature = "virtual-clients-draft")]
251impl VcDerivationEpochDeletion {
252 /// Delete all derivation epochs superseded more than `duration` ago.
253 pub fn older_than_duration(duration: std::time::Duration) -> Self {
254 Self {
255 time: VcDerivationEpochDeletionTime::OlderThanDuration(duration),
256 max_epochs: None,
257 }
258 }
259
260 /// Delete all derivation epochs superseded before `timestamp`.
261 pub fn before_timestamp(timestamp: SystemTime) -> Self {
262 Self {
263 time: VcDerivationEpochDeletionTime::BeforeTimestamp(timestamp),
264 max_epochs: None,
265 }
266 }
267
268 /// Additionally cap the number of derivation epochs that survive.
269 pub fn max_epochs(mut self, max_epochs: usize) -> Self {
270 self.max_epochs = Some(max_epochs);
271 self
272 }
273}
274
275/// Returned by [`MlsGroup::delete_vc_derivation_epochs()`]. Selected epochs
276/// whose per-epoch state was already absent appear in neither list.
277#[cfg(feature = "virtual-clients-draft")]
278#[derive(Debug, Default, Clone, PartialEq, Eq)]
279pub struct VcDerivationEpochDeletionResult {
280 /// The derivation epochs whose per-epoch state was deleted.
281 pub deleted: Vec<crate::components::vc_derivation_info::EpochId>,
282 /// The derivation epochs whose per-epoch state was kept because something
283 /// still references it.
284 pub kept: Vec<crate::components::vc_derivation_info::EpochId>,
285}
286
287/// The [`MlsGroupJoinConfig`] contains all configuration parameters that are
288/// relevant to group operation at runtime. It is used to configure the group's
289/// behaviour when joining an existing group. To configure a newly created
290/// group, use [`MlsGroupCreateConfig`].
291#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
292pub struct MlsGroupJoinConfig {
293 /// Defines the wire format policy for outgoing and incoming handshake messages.
294 /// Application are always encrypted regardless.
295 pub(crate) wire_format_policy: WireFormatPolicy,
296 /// Size of padding in bytes
297 pub(crate) padding_size: usize,
298 /// Maximum number of past epochs for which application messages
299 /// can be decrypted. The default is 0.
300 #[serde(alias = "max_past_epochs")]
301 // alias for backwards compatibility after renaming field
302 pub(crate) past_epoch_deletion_policy: PastEpochDeletionPolicy,
303 /// Number of resumption secrets to keep
304 pub(crate) number_of_resumption_psks: usize,
305 /// Flag to indicate the Ratchet Tree Extension should be used
306 pub(crate) use_ratchet_tree_extension: bool,
307 /// Sender ratchet configuration
308 pub(crate) sender_ratchet_configuration: SenderRatchetConfiguration,
309 /// Derivation-epoch retention policy, only consulted on emulation groups.
310 /// See [`VcDerivationEpochRetentionPolicy`].
311 #[cfg(feature = "virtual-clients-draft")]
312 #[serde(default)]
313 pub(crate) vc_derivation_epoch_retention_policy: VcDerivationEpochRetentionPolicy,
314}
315
316impl MlsGroupJoinConfig {
317 /// Returns a builder for [`MlsGroupJoinConfig`].
318 pub fn builder() -> MlsGroupJoinConfigBuilder {
319 MlsGroupJoinConfigBuilder::new()
320 }
321
322 /// Returns the wire format policy set in this [`MlsGroupJoinConfig`].
323 pub fn wire_format_policy(&self) -> WireFormatPolicy {
324 self.wire_format_policy
325 }
326
327 /// Returns the padding size set in this [`MlsGroupJoinConfig`].
328 pub fn padding_size(&self) -> usize {
329 self.padding_size
330 }
331
332 /// Returns the [`SenderRatchetConfiguration`] set in this [`MlsGroupJoinConfig`].
333 pub fn sender_ratchet_configuration(&self) -> &SenderRatchetConfiguration {
334 &self.sender_ratchet_configuration
335 }
336
337 /// Returns the max past epochs configured in this [`MlsGroupJoinConfig`]
338 pub(crate) fn max_past_epochs(&self) -> Option<usize> {
339 self.past_epoch_deletion_policy.max_epochs()
340 }
341
342 pub(crate) fn past_epoch_deletion_policy(&self) -> &PastEpochDeletionPolicy {
343 &self.past_epoch_deletion_policy
344 }
345
346 /// Returns the derivation-epoch retention policy set in this
347 /// [`MlsGroupJoinConfig`].
348 #[cfg(feature = "virtual-clients-draft")]
349 pub fn vc_derivation_epoch_retention_policy(&self) -> &VcDerivationEpochRetentionPolicy {
350 &self.vc_derivation_epoch_retention_policy
351 }
352}
353
354/// Specifies configuration for the creation of an [`MlsGroup`]. Refer to the
355/// [User Manual](https://book.openmls.tech/user_manual/group_config.html) for
356/// more information about the different configuration values.
357#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
358pub struct MlsGroupCreateConfig {
359 /// Capabilities advertised in the creator's leaf node. `None` means the
360 /// caller expressed no preference, in which case they are derived from the
361 /// leaf itself — see [`resolve_capabilities`].
362 pub(crate) capabilities: Option<Capabilities>,
363 /// Lifetime of the own leaf node
364 pub(crate) lifetime: Lifetime,
365 /// Ciphersuite and protocol version
366 pub(crate) ciphersuite: Ciphersuite,
367 /// Configuration parameters relevant to group operation at runtime
368 pub(crate) join_config: MlsGroupJoinConfig,
369 /// List of initial group context extensions
370 pub(crate) group_context_extensions: Extensions<GroupContext>,
371 /// List of initial leaf node extensions
372 pub(crate) leaf_node_extensions: Extensions<LeafNode>,
373 /// How the creator's leaf node capabilities are treated when they don't
374 /// cover what the leaf needs. `None` lets [`resolve_capabilities`] pick
375 /// based on whether `capabilities` was set.
376 pub(crate) capabilities_policy: Option<CapabilitiesPolicy>,
377 /// Flag marking the created group as an emulation group of a virtual
378 /// client. Only consulted at group creation, the group keeps the flag
379 /// itself afterwards.
380 #[cfg(feature = "virtual-clients-draft")]
381 pub(crate) emulation_group: bool,
382}
383
384impl Default for MlsGroupCreateConfig {
385 fn default() -> Self {
386 Self {
387 capabilities: None,
388 lifetime: Lifetime::default(),
389 ciphersuite: Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519,
390 join_config: MlsGroupJoinConfig::default(),
391 group_context_extensions: Extensions::default(),
392 leaf_node_extensions: Extensions::default(),
393 capabilities_policy: None,
394 #[cfg(feature = "virtual-clients-draft")]
395 emulation_group: false,
396 }
397 }
398}
399
400/// Builder struct for an [`MlsGroupJoinConfig`].
401#[derive(Default)]
402pub struct MlsGroupJoinConfigBuilder {
403 join_config: MlsGroupJoinConfig,
404}
405
406impl MlsGroupJoinConfigBuilder {
407 /// Creates a new builder with default values.
408 fn new() -> Self {
409 Self {
410 join_config: MlsGroupJoinConfig::default(),
411 }
412 }
413
414 /// Sets the `wire_format` property of the [`MlsGroupJoinConfig`].
415 pub fn wire_format_policy(mut self, wire_format_policy: WireFormatPolicy) -> Self {
416 self.join_config.wire_format_policy = wire_format_policy;
417 self
418 }
419
420 /// Sets the `padding_size` property of the [`MlsGroupJoinConfig`].
421 pub fn padding_size(mut self, padding_size: usize) -> Self {
422 self.join_config.padding_size = padding_size;
423 self
424 }
425
426 /// Sets the `max_past_epochs` property of the [`MlsGroupJoinConfig`].
427 ///
428 /// This method overrides the policy set by [`Self::set_past_epoch_deletion_policy()`],
429 /// and is equivalent to setting the past epoch deletion policy to
430 /// `PastEpochDeletionPolicy::MaxEpochs(max_past_epochs)`.
431 ///
432 /// **WARNING**
433 ///
434 /// This feature enables the storage of message secrets from past epochs.
435 /// It is a trade-off between functionality and forward secrecy and should only be enabled
436 /// if the Delivery Service cannot guarantee that application messages will be sent in
437 /// the same epoch in which they were generated. The number for `max_epochs` should be
438 /// as low as possible.
439 pub fn max_past_epochs(mut self, max_past_epochs: usize) -> Self {
440 self.join_config.past_epoch_deletion_policy =
441 PastEpochDeletionPolicy::MaxEpochs(max_past_epochs);
442 self
443 }
444
445 /// Set the policy for deleting past epoch secrets.
446 ///
447 /// By default, storage of past epoch secrets is disabled.
448 ///
449 /// This method overrides the configuration set by [`Self::max_past_epochs()`].
450 ///
451 /// **WARNING**
452 ///
453 /// This feature enables the storage of message secrets from past epochs.
454 /// It is a trade-off between functionality and forward secrecy and should only be enabled
455 /// if the Delivery Service cannot guarantee that application messages will be sent in
456 /// the same epoch in which they were generated. The number for `max_epochs` should be
457 /// as low as possible.
458 pub fn set_past_epoch_deletion_policy(mut self, policy: PastEpochDeletionPolicy) -> Self {
459 self.join_config.past_epoch_deletion_policy = policy;
460 self
461 }
462
463 /// Sets the derivation-epoch retention policy. See
464 /// [`VcDerivationEpochRetentionPolicy`].
465 #[cfg(feature = "virtual-clients-draft")]
466 pub fn set_vc_derivation_epoch_retention_policy(
467 mut self,
468 policy: VcDerivationEpochRetentionPolicy,
469 ) -> Self {
470 self.join_config.vc_derivation_epoch_retention_policy = policy;
471 self
472 }
473
474 /// Sets the `number_of_resumption_psks` property of the [`MlsGroupJoinConfig`].
475 pub fn number_of_resumption_psks(mut self, number_of_resumption_psks: usize) -> Self {
476 self.join_config.number_of_resumption_psks = number_of_resumption_psks;
477 self
478 }
479
480 /// Sets the `use_ratchet_tree_extension` property of the [`MlsGroupJoinConfig`].
481 pub fn use_ratchet_tree_extension(mut self, use_ratchet_tree_extension: bool) -> Self {
482 self.join_config.use_ratchet_tree_extension = use_ratchet_tree_extension;
483 self
484 }
485
486 /// Sets the `sender_ratchet_configuration` property of the [`MlsGroupJoinConfig`].
487 pub fn sender_ratchet_configuration(
488 mut self,
489 sender_ratchet_configuration: SenderRatchetConfiguration,
490 ) -> Self {
491 self.join_config.sender_ratchet_configuration = sender_ratchet_configuration;
492 self
493 }
494
495 /// Finalizes the builder and returns an [`MlsGroupJoinConfig`].
496 pub fn build(self) -> MlsGroupJoinConfig {
497 self.join_config
498 }
499}
500
501impl MlsGroupCreateConfig {
502 /// Returns a builder for [`MlsGroupCreateConfig`]
503 pub fn builder() -> MlsGroupCreateConfigBuilder {
504 MlsGroupCreateConfigBuilder::new()
505 }
506
507 /// Returns the [`MlsGroupCreateConfig`] wire format policy.
508 pub fn wire_format_policy(&self) -> WireFormatPolicy {
509 self.join_config.wire_format_policy
510 }
511
512 /// Returns the [`MlsGroupCreateConfig`] padding size.
513 pub fn padding_size(&self) -> usize {
514 self.join_config.padding_size
515 }
516
517 /// Returns the [`MlsGroupCreateConfig`] max past epochs.
518 pub fn max_past_epochs(&self) -> Option<usize> {
519 self.join_config.max_past_epochs()
520 }
521
522 /// Returns the [`MlsGroupCreateConfig`] number of resumption psks.
523 pub fn number_of_resumption_psks(&self) -> usize {
524 self.join_config.number_of_resumption_psks
525 }
526
527 /// Returns the [`MlsGroupCreateConfig`] boolean flag that indicates whether ratchet_tree_extension should be used.
528 pub fn use_ratchet_tree_extension(&self) -> bool {
529 self.join_config.use_ratchet_tree_extension
530 }
531
532 /// Returns the [`MlsGroupCreateConfig`] sender ratchet configuration.
533 pub fn sender_ratchet_configuration(&self) -> &SenderRatchetConfiguration {
534 &self.join_config.sender_ratchet_configuration
535 }
536
537 /// Returns the [`Extensions`] set as the initial group context.
538 /// This does not contain the initial group context extensions
539 /// added from builder calls to `external_senders` or `required_capabilities`.
540 pub fn group_context_extensions(&self) -> &Extensions<GroupContext> {
541 &self.group_context_extensions
542 }
543
544 /// Returns the [`MlsGroupCreateConfig`] lifetime configuration.
545 pub fn lifetime(&self) -> &Lifetime {
546 &self.lifetime
547 }
548
549 /// Returns the [`Ciphersuite`].
550 pub fn ciphersuite(&self) -> Ciphersuite {
551 self.ciphersuite
552 }
553
554 /// Returns whether groups created with this config are emulation groups of
555 /// a virtual client. See [`MlsGroupCreateConfigBuilder::emulation_group`].
556 #[cfg(feature = "virtual-clients-draft")]
557 pub fn emulation_group(&self) -> bool {
558 self.emulation_group
559 }
560
561 #[cfg(any(feature = "test-utils", test))]
562 pub fn test_default(ciphersuite: Ciphersuite) -> Self {
563 Self::builder()
564 .wire_format_policy(WireFormatPolicy::new(
565 OutgoingWireFormatPolicy::AlwaysPlaintext,
566 IncomingWireFormatPolicy::Mixed,
567 ))
568 .ciphersuite(ciphersuite)
569 .build()
570 }
571
572 /// Returns the [`MlsGroupJoinConfig`] of groups created with this create config.
573 pub fn join_config(&self) -> &MlsGroupJoinConfig {
574 &self.join_config
575 }
576}
577
578/// Builder for an [`MlsGroupCreateConfig`].
579#[derive(Default, Debug)]
580pub struct MlsGroupCreateConfigBuilder {
581 config: MlsGroupCreateConfig,
582}
583
584impl MlsGroupCreateConfigBuilder {
585 /// Creates a new builder with default values.
586 fn new() -> Self {
587 MlsGroupCreateConfigBuilder {
588 config: MlsGroupCreateConfig::default(),
589 }
590 }
591
592 /// Sets the `wire_format` property of the MlsGroupCreateConfig.
593 pub fn wire_format_policy(mut self, wire_format_policy: WireFormatPolicy) -> Self {
594 self.config.join_config.wire_format_policy = wire_format_policy;
595 self
596 }
597
598 /// Sets the `padding_size` property of the MlsGroupCreateConfig.
599 pub fn padding_size(mut self, padding_size: usize) -> Self {
600 self.config.join_config.padding_size = padding_size;
601 self
602 }
603
604 /// Sets the `max_past_epochs` property of the MlsGroupCreateConfig.
605 /// This allows application messages from previous epochs to be decrypted.
606 ///
607 /// This method overrides the policy set by [`Self::set_past_epoch_deletion_policy()`],
608 /// and is equivalent to setting the past epoch deletion policy to
609 /// `PastEpochDeletionPolicy::MaxEpochs(max_past_epochs)`.
610 ///
611 /// **WARNING**
612 ///
613 /// This feature enables the storage of message secrets from past epochs.
614 /// It is a trade-off between functionality and forward secrecy and should only be enabled
615 /// if the Delivery Service cannot guarantee that application messages will be sent in
616 /// the same epoch in which they were generated. The number for `max_epochs` should be
617 /// as low as possible.
618 pub fn max_past_epochs(mut self, max_past_epochs: usize) -> Self {
619 self.config.join_config.past_epoch_deletion_policy =
620 PastEpochDeletionPolicy::MaxEpochs(max_past_epochs);
621 self
622 }
623
624 /// Set the policy for deleting past epoch secrets.
625 ///
626 /// By default, storage of past epoch secrets is disabled.
627 ///
628 /// This method overrides the configuration set by [`Self::max_past_epochs()`].
629 ///
630 /// **WARNING**
631 ///
632 /// This feature enables the storage of message secrets from past epochs.
633 /// It is a trade-off between functionality and forward secrecy and should only be enabled
634 /// if the Delivery Service cannot guarantee that application messages will be sent in
635 /// the same epoch in which they were generated. The number for `max_epochs` should be
636 /// as low as possible.
637 pub fn set_past_epoch_deletion_policy(mut self, policy: PastEpochDeletionPolicy) -> Self {
638 self.config.join_config.past_epoch_deletion_policy = policy;
639 self
640 }
641
642 /// Sets the derivation-epoch retention policy. See
643 /// [`VcDerivationEpochRetentionPolicy`].
644 #[cfg(feature = "virtual-clients-draft")]
645 pub fn set_vc_derivation_epoch_retention_policy(
646 mut self,
647 policy: VcDerivationEpochRetentionPolicy,
648 ) -> Self {
649 self.config.join_config.vc_derivation_epoch_retention_policy = policy;
650 self
651 }
652
653 /// Sets the `number_of_resumption_psks` property of the MlsGroupCreateConfig.
654 pub fn number_of_resumption_psks(mut self, number_of_resumption_psks: usize) -> Self {
655 self.config.join_config.number_of_resumption_psks = number_of_resumption_psks;
656 self
657 }
658
659 /// Sets the `use_ratchet_tree_extension` property of the MlsGroupCreateConfig.
660 pub fn use_ratchet_tree_extension(mut self, use_ratchet_tree_extension: bool) -> Self {
661 self.config.join_config.use_ratchet_tree_extension = use_ratchet_tree_extension;
662 self
663 }
664
665 /// Sets the `capabilities` of the group creator's leaf node.
666 ///
667 /// Setting them explicitly means they are taken at face value: if they
668 /// don't cover the group's ciphersuite, the creator's credential type or
669 /// the configured leaf node extensions, group creation fails rather than
670 /// silently advertising something else. Leave them unset to have them
671 /// derived from the leaf, or pair this with
672 /// [`MlsGroupCreateConfigBuilder::capabilities_policy`] to have the
673 /// missing pieces added.
674 pub fn capabilities(mut self, capabilities: Capabilities) -> Self {
675 self.config.capabilities = Some(capabilities);
676 self
677 }
678
679 /// Marks the group as an emulation group of a virtual client.
680 ///
681 /// This is the application's declaration that the group's members are the
682 /// emulator clients of one virtual client. It is local state, nothing about
683 /// it travels on the wire, and every member of an emulation group has to
684 /// set it. Members that join by Welcome set it on the
685 /// [`StagedWelcome`](crate::group::StagedWelcome) instead, and members that
686 /// join by external commit on the
687 /// [`ExternalCommitBuilder`](crate::group::ExternalCommitBuilder).
688 ///
689 /// An emulation group derives the virtual client's secrets from its
690 /// derivation epochs. The initial epoch is a derivation epoch, and so is
691 /// the output epoch of every commit that changes membership or that carries
692 /// a `new_derivation_epoch` action in its virtual-clients Safe AAD item
693 /// (see [`CommitBuilder::derivation_epoch`]). OpenMLS derives and
694 /// persists the derivation-epoch state itself at group creation, at a
695 /// Welcome join, and when such a commit is merged.
696 ///
697 /// Use [`MlsGroup::newest_vc_derivation_epoch`] to look up the derivation
698 /// epoch that virtual-client operations resolve to. It may be older than
699 /// the group's current epoch.
700 ///
701 /// Groups without this flag never write virtual-clients state.
702 ///
703 /// [`CommitBuilder::derivation_epoch`]: crate::group::CommitBuilder::derivation_epoch
704 /// [`MlsGroup::newest_vc_derivation_epoch`]: crate::group::MlsGroup::newest_vc_derivation_epoch
705 #[cfg(feature = "virtual-clients-draft")]
706 pub fn emulation_group(mut self, emulation_group: bool) -> Self {
707 self.config.emulation_group = emulation_group;
708 self
709 }
710
711 /// Sets the `sender_ratchet_configuration` property of the MlsGroupCreateConfig.
712 /// See [`SenderRatchetConfiguration`] for more information.
713 pub fn sender_ratchet_configuration(
714 mut self,
715 sender_ratchet_configuration: SenderRatchetConfiguration,
716 ) -> Self {
717 self.config.join_config.sender_ratchet_configuration = sender_ratchet_configuration;
718 self
719 }
720
721 /// Sets the `lifetime` property of the MlsGroupCreateConfig.
722 pub fn lifetime(mut self, lifetime: Lifetime) -> Self {
723 self.config.lifetime = lifetime;
724 self
725 }
726
727 /// Sets the `ciphersuite` property of the MlsGroupCreateConfig.
728 pub fn ciphersuite(mut self, ciphersuite: Ciphersuite) -> Self {
729 self.config.ciphersuite = ciphersuite;
730 self
731 }
732
733 /// Sets initial group context extensions.
734 pub fn with_group_context_extensions(mut self, extensions: Extensions<GroupContext>) -> Self {
735 self.config.group_context_extensions = extensions;
736 self
737 }
738
739 /// Sets extensions of the group creator's [`LeafNode`].
740 ///
741 /// The extensions are checked against the creator's capabilities when the
742 /// leaf is built, not here.
743 pub fn with_leaf_node_extensions(
744 mut self,
745 extensions: Extensions<LeafNode>,
746 ) -> Result<Self, LeafNodeValidationError> {
747 self.config.leaf_node_extensions = extensions;
748 Ok(self)
749 }
750
751 /// Sets the [`CapabilitiesPolicy`] applied to the creator's leaf node capabilities.
752 ///
753 /// If left unset, uses [`CapabilitiesPolicy::Reject`] if capabilities are
754 /// manually set via [`Self::capabilities`], and [`CapabilitiesPolicy::Widen`] if they aren't.
755 pub fn capabilities_policy(mut self, policy: CapabilitiesPolicy) -> Self {
756 self.config.capabilities_policy = Some(policy);
757 self
758 }
759
760 /// Finalizes the builder and returns an [`MlsGroupCreateConfig`].
761 pub fn build(self) -> MlsGroupCreateConfig {
762 self.config
763 }
764}
765
766/// Defines what wire format is acceptable for incoming handshake messages.
767/// Note that application messages must always be encrypted.
768#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
769pub enum IncomingWireFormatPolicy {
770 /// Handshake messages must always be PrivateMessage
771 AlwaysCiphertext,
772 /// Handshake messages must always be PublicMessage
773 AlwaysPlaintext,
774 /// Handshake messages can either be PrivateMessage or PublicMessage
775 Mixed,
776}
777
778impl IncomingWireFormatPolicy {
779 pub(crate) fn is_compatible_with(&self, wire_format: WireFormat) -> bool {
780 match self {
781 IncomingWireFormatPolicy::AlwaysCiphertext => wire_format == WireFormat::PrivateMessage,
782 IncomingWireFormatPolicy::AlwaysPlaintext => wire_format == WireFormat::PublicMessage,
783 IncomingWireFormatPolicy::Mixed => {
784 wire_format == WireFormat::PrivateMessage
785 || wire_format == WireFormat::PublicMessage
786 }
787 }
788 }
789}
790
791/// Defines what wire format should be used for outgoing handshake messages.
792/// Note that application messages must always be encrypted.
793#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
794pub enum OutgoingWireFormatPolicy {
795 /// Handshake messages must always be PrivateMessage
796 AlwaysCiphertext,
797 /// Handshake messages must always be PublicMessage
798 AlwaysPlaintext,
799}
800
801/// Defines what wire format is desired for outgoing handshake messages.
802/// Note that application messages must always be encrypted.
803#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
804pub struct WireFormatPolicy {
805 outgoing: OutgoingWireFormatPolicy,
806 incoming: IncomingWireFormatPolicy,
807}
808
809impl WireFormatPolicy {
810 /// Creates a new wire format policy from an [`OutgoingWireFormatPolicy`]
811 /// and an [`IncomingWireFormatPolicy`].
812 #[cfg(any(feature = "test-utils", test))]
813 pub(crate) fn new(
814 outgoing: OutgoingWireFormatPolicy,
815 incoming: IncomingWireFormatPolicy,
816 ) -> Self {
817 Self { outgoing, incoming }
818 }
819
820 /// Returns a reference to the wire format policy's outgoing wire format policy.
821 pub fn outgoing(&self) -> OutgoingWireFormatPolicy {
822 self.outgoing
823 }
824
825 /// Returns a reference to the wire format policy's incoming wire format policy.
826 pub fn incoming(&self) -> IncomingWireFormatPolicy {
827 self.incoming
828 }
829}
830
831impl Default for WireFormatPolicy {
832 fn default() -> Self {
833 PURE_CIPHERTEXT_WIRE_FORMAT_POLICY
834 }
835}
836
837impl From<OutgoingWireFormatPolicy> for WireFormat {
838 fn from(outgoing: OutgoingWireFormatPolicy) -> Self {
839 match outgoing {
840 OutgoingWireFormatPolicy::AlwaysCiphertext => WireFormat::PrivateMessage,
841 OutgoingWireFormatPolicy::AlwaysPlaintext => WireFormat::PublicMessage,
842 }
843 }
844}
845
846/// All valid wire format policy combinations.
847/// - [`PURE_PLAINTEXT_WIRE_FORMAT_POLICY`]
848/// - [`PURE_CIPHERTEXT_WIRE_FORMAT_POLICY`]
849/// - [`MIXED_PLAINTEXT_WIRE_FORMAT_POLICY`]
850/// - [`MIXED_CIPHERTEXT_WIRE_FORMAT_POLICY`]
851pub const WIRE_FORMAT_POLICIES: [WireFormatPolicy; 4] = [
852 PURE_PLAINTEXT_WIRE_FORMAT_POLICY,
853 PURE_CIPHERTEXT_WIRE_FORMAT_POLICY,
854 MIXED_PLAINTEXT_WIRE_FORMAT_POLICY,
855 MIXED_CIPHERTEXT_WIRE_FORMAT_POLICY,
856];
857
858/// Incoming and outgoing wire formats are always plaintext.
859pub const PURE_PLAINTEXT_WIRE_FORMAT_POLICY: WireFormatPolicy = WireFormatPolicy {
860 outgoing: OutgoingWireFormatPolicy::AlwaysPlaintext,
861 incoming: IncomingWireFormatPolicy::AlwaysPlaintext,
862};
863
864/// Incoming and outgoing wire formats are always ciphertext.
865pub const PURE_CIPHERTEXT_WIRE_FORMAT_POLICY: WireFormatPolicy = WireFormatPolicy {
866 outgoing: OutgoingWireFormatPolicy::AlwaysCiphertext,
867 incoming: IncomingWireFormatPolicy::AlwaysCiphertext,
868};
869
870/// Incoming wire formats can be mixed while outgoing wire formats are always
871/// plaintext.
872pub const MIXED_PLAINTEXT_WIRE_FORMAT_POLICY: WireFormatPolicy = WireFormatPolicy {
873 outgoing: OutgoingWireFormatPolicy::AlwaysPlaintext,
874 incoming: IncomingWireFormatPolicy::Mixed,
875};
876
877/// Incoming wire formats can be mixed while outgoing wire formats are always
878/// ciphertext.
879pub const MIXED_CIPHERTEXT_WIRE_FORMAT_POLICY: WireFormatPolicy = WireFormatPolicy {
880 outgoing: OutgoingWireFormatPolicy::AlwaysCiphertext,
881 incoming: IncomingWireFormatPolicy::Mixed,
882};
883
884#[cfg(test)]
885mod tests {
886 use super::PastEpochDeletionPolicy;
887
888 #[test]
889 fn past_epoch_deletion_policy_roundtrip() {
890 for policy in [
891 PastEpochDeletionPolicy::MaxEpochs(0),
892 PastEpochDeletionPolicy::MaxEpochs(42),
893 PastEpochDeletionPolicy::KeepAll,
894 ] {
895 let json = serde_json::to_string(&policy).unwrap();
896 let deserialized: PastEpochDeletionPolicy = serde_json::from_str(&json).unwrap();
897 assert_eq!(deserialized, policy);
898 }
899
900 // MaxEpochs(usize::MAX) is indistinguishable from KeepAll after serialization.
901 let json = serde_json::to_string(&PastEpochDeletionPolicy::MaxEpochs(usize::MAX)).unwrap();
902 let deserialized: PastEpochDeletionPolicy = serde_json::from_str(&json).unwrap();
903 assert_eq!(deserialized, PastEpochDeletionPolicy::KeepAll);
904 }
905
906 #[test]
907 fn past_epoch_deletion_policy_deserializes_plain_integer() {
908 let deserialized: PastEpochDeletionPolicy = serde_json::from_str("42").unwrap();
909 assert_eq!(deserialized, PastEpochDeletionPolicy::MaxEpochs(42));
910
911 let deserialized: PastEpochDeletionPolicy =
912 serde_json::from_str(&u64::MAX.to_string()).unwrap();
913 assert_eq!(deserialized, PastEpochDeletionPolicy::KeepAll);
914 }
915
916 #[test]
917 fn past_epoch_deletion_policy_deserializes_legacy_tagged_format() {
918 // Externally tagged enum format used before 8bdba6f.
919 let deserialized: PastEpochDeletionPolicy =
920 serde_json::from_str(r#"{"MaxEpochs":42}"#).unwrap();
921 assert_eq!(deserialized, PastEpochDeletionPolicy::MaxEpochs(42));
922
923 let deserialized: PastEpochDeletionPolicy = serde_json::from_str(r#""KeepAll""#).unwrap();
924 assert_eq!(deserialized, PastEpochDeletionPolicy::KeepAll);
925 }
926}