Skip to main content

capsule_core/crypto/authority/openmls_authority/
resilience.rs

1//! **MLS resilience**: reconciliation over the server-authoritative commit chain, the
2//! lost-commit retry primitive, and the group re-keying ceremony.
3//!
4//! SSoT: [MLS Resilience](https://docs/design/mls-resilience/).
5//!
6//! OpenMLS resolves ordinary concurrency (one commit wins, the other re-proposes — via the
7//! `stage`/`merge`/`discard` primitives). This module owns the recovery contracts the base protocol
8//! does *not* resolve on its own: a **lost commit**, **state divergence**, and a **whole-group
9//! re-key** after a suspected compromise.
10//!
11//! **Recovery posture** (from the doc):
12//! - *Server chain is authoritative.* Any local inconsistency is reconciled by replaying the
13//!   server's chain; the server can order commits but holds no group secrets.
14//! - *Re-bootstrap is always available.* A device whose MLS state is unrecoverable is removed and
15//!   re-added — losing local MLS state never loses access to the data.
16//! - *Quarantine, not silent acceptance.* Divergence is surfaced (an explicit
17//!   [`ReconcileOutcome`]), never silently merged.
18//!
19//! **In-process transport.** This module makes no server changes: the server's authoritative
20//! chain is supplied to [`reconcile_with_server`](OpenMlsAuthority::reconcile_with_server) as a
21//! [`ServerChainView`] — the classification (behind / ahead / forked) that the real delivery
22//! service would compute by comparing commit hashes against its persisted chain.
23
24use openmls::group::CommitMessageBundle;
25use openmls::prelude::tls_codec::Deserialize as _;
26use openmls::prelude::{LeafNodeParameters, MlsMessageIn, MlsMessageOut};
27use serde::{Deserialize, Serialize};
28use uuid::Uuid;
29
30use super::super::AlbumAuthority;
31use super::{OpenMlsAuthority, OpenMlsAuthorityError, Result, WriteTierIngest};
32use crate::ambient::IdSource;
33use crate::crypto::hash::{self, Hash32};
34use crate::crypto::keys::HybridSigningKey;
35
36/// The content hash of an MLS commit message — its identity on the server-authoritative chain.
37/// Suite-fixed SHA-256 over the commit's wire bytes; two applications of the same commit share a
38/// hash (the idempotency identity).
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub struct CommitHash(pub Hash32);
41
42/// The single "bring-me-current" reconciliation outcome (mls-resilience.md § Contract Skeleton).
43/// Reconciliation is one entry point, not a per-failure-mode call; this enum reports which path was
44/// taken, including the two that escalate to user action or re-bootstrap.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub enum ReconcileOutcome {
47    /// Local state already matches the server head.
48    UpToDate,
49    /// Local was behind; the missing commits were replayed from the server's chain, in order.
50    Reconciled {
51        /// The commits applied, oldest first.
52        applied_commits: Vec<CommitHash>,
53    },
54    /// Local diverged from the server in a way that is not a simple replay — surfaced to the user
55    /// (quarantine), never silently merged.
56    Diverged {
57        /// This member's local MLS epoch.
58        local_epoch: u64,
59        /// The server's head MLS epoch.
60        server_epoch: u64,
61    },
62    /// Local state is unrecoverable (a provable fork, or a commit that will not apply) — the member
63    /// must discard its group state and re-bootstrap (be re-added by another device).
64    Unrecoverable,
65}
66
67/// The server's authoritative commit chain **as seen relative to this member** — the classification
68/// the real delivery service computes by comparing the member's head against its persisted chain.
69/// This is the mock boundary: this module makes no server changes, so the caller supplies the
70/// comparison result rather than this module querying a live server.
71pub enum ServerChainView {
72    /// The member's head equals the server head.
73    UpToDate,
74    /// The server is ahead: `missed_commits` are the wire bytes of the commits the member is
75    /// missing, oldest first, for replay.
76    Behind {
77        /// The server's head MLS epoch.
78        server_epoch: u64,
79        /// The missing commits' wire bytes, oldest first.
80        missed_commits: Vec<Vec<u8>>,
81    },
82    /// The member holds a commit whose hash is **absent** from the server's chain (it is ahead).
83    /// `provable_fork` is `true` when the server has advanced past the local commit's parent with a
84    /// *different* commit (re-submission can never land) — the discriminator between an honestly
85    /// lost commit (retry) and a fork (re-bootstrap).
86    LocalAhead {
87        /// The server's head MLS epoch.
88        server_epoch: u64,
89        /// Whether the absence is a provable fork (vs. an honestly-lost commit still retryable).
90        provable_fork: bool,
91    },
92}
93
94/// Why a group re-key was triggered (mls-resilience.md § Group re-keying ceremony).
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
96pub enum RekeyReason {
97    /// An album admin manually initiated a full re-key.
98    AdminInitiated,
99    /// Automatic response to a suspected compromise (every leaf rotates; fresh AMK + write-tier).
100    SuspectedCompromise,
101    /// Optional scheduled rotation for a long-lived album (deployment policy).
102    ScheduledRotation,
103}
104
105/// The resume state of an in-flight re-keying ceremony (two phases: the re-key commit, then the
106/// fresh-epoch broadcast). Persisted, so a crash between the phases resumes on restart — the
107/// `intent_id` is the idempotency key it shares with the [upgrade](super::upgrade) ceremony.
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub(super) struct RekeyState {
110    /// The ceremony's idempotency key.
111    pub intent_id: Uuid,
112    /// Why the re-key was triggered.
113    pub reason: RekeyReason,
114}
115
116/// The artifacts a completed re-key produces, for delivery over the (out-of-scope) transport.
117pub struct RekeyOutcome {
118    /// The ceremony's idempotency key.
119    pub intent_id: Uuid,
120    /// Why the re-key was triggered.
121    pub reason: RekeyReason,
122    /// The re-key commit (phase 1), for delivery to the other members.
123    pub commit: MlsMessageOut,
124    /// The fresh epoch's [`AlbumKeyDistribution`](super::AlbumKeyDistribution) (all members) and
125    /// [`WriteTierDistribution`](super::WriteTierDistribution) (writers) — phase 2.
126    pub key_delivery: Vec<MlsMessageOut>,
127}
128
129/// The lost-commit detection + backoff schedule (mls-resilience.md § Lost commit): a device that
130/// doesn't see its committed epoch on the chain within the detection timeout re-submits, backing
131/// off on each attempt, and after the budget is exhausted surfaces the change to the user (never
132/// silently abandoned). Re-submission is idempotent — OpenMLS rejects a duplicate, so a retry that
133/// *did* land is harmless.
134///
135/// Pure timing bookkeeping (no real sleeping) so it is deterministic under test.
136#[derive(Clone, Debug)]
137pub struct LostCommitTracker {
138    attempts: u32,
139    schedule: Vec<jiff::SignedDuration>,
140}
141
142impl Default for LostCommitTracker {
143    fn default() -> Self {
144        Self::new()
145    }
146}
147
148impl LostCommitTracker {
149    /// A tracker with the defaults (owned here, not in the doc): detection timeout 30 s,
150    /// backoff 30 s → 2 min → 10 min, 3 attempts.
151    pub fn new() -> Self {
152        Self {
153            attempts: 0,
154            schedule: vec![
155                jiff::SignedDuration::from_secs(30),
156                jiff::SignedDuration::from_secs(2 * 60),
157                jiff::SignedDuration::from_secs(10 * 60),
158            ],
159        }
160    }
161
162    /// The detection timeout: a committed epoch not reflected on the chain within this is treated
163    /// as lost.
164    pub fn detection_timeout(&self) -> jiff::SignedDuration {
165        jiff::SignedDuration::from_secs(30)
166    }
167
168    /// The maximum number of re-submission attempts before the change is surfaced to the user.
169    pub fn max_attempts(&self) -> u32 {
170        u32::try_from(self.schedule.len()).unwrap_or(u32::MAX)
171    }
172
173    /// Record a re-submission attempt; returns the backoff to wait before the next attempt, or
174    /// `None` if the budget is now exhausted (the change must be surfaced to the user).
175    pub fn record_attempt(&mut self) -> Option<jiff::SignedDuration> {
176        let backoff = self.schedule.get(self.attempts as usize).copied();
177        self.attempts = self.attempts.saturating_add(1);
178        backoff
179    }
180
181    /// Whether the retry budget is exhausted.
182    pub fn is_exhausted(&self) -> bool {
183        self.attempts >= self.max_attempts()
184    }
185
186    /// How many attempts have been recorded.
187    pub fn attempts(&self) -> u32 {
188        self.attempts
189    }
190}
191
192impl OpenMlsAuthority {
193    // ── Reconciliation ───────────────────────────────────────────────────────
194
195    /// Bring this member current against the server-authoritative chain, reporting what happened as
196    /// a [`ReconcileOutcome`]. The single reconciliation entry point (not a per-failure-mode call):
197    ///
198    /// - [`UpToDate`](ReconcileOutcome::UpToDate) — nothing to do;
199    /// - [`Reconciled`](ReconcileOutcome::Reconciled) — the member was behind and replayed the
200    ///   missed commits (the server-authoritative state);
201    /// - [`Diverged`](ReconcileOutcome::Diverged) — the member is ahead with an honestly-lost
202    ///   commit (surfaced to the user; the [`LostCommitTracker`] drives the actual re-submit),
203    ///   never silently merged;
204    /// - [`Unrecoverable`](ReconcileOutcome::Unrecoverable) — a provable fork, or a missed commit
205    ///   that will not apply (e.g. this member was removed) — re-bootstrap.
206    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, local_epoch = self.mls_epoch()))]
207    pub fn reconcile_with_server(&mut self, view: ServerChainView) -> Result<ReconcileOutcome> {
208        let local_epoch = self.mls_epoch();
209        match view {
210            ServerChainView::UpToDate => {
211                tracing::debug!(album_id = %self.album_id, "reconcile: already up to date");
212                Ok(ReconcileOutcome::UpToDate)
213            }
214            ServerChainView::Behind {
215                server_epoch,
216                missed_commits,
217            } => {
218                let mut applied = Vec::with_capacity(missed_commits.len());
219                for bytes in missed_commits {
220                    let commit_hash = CommitHash(hash::hash_bytes(&bytes));
221                    let message =
222                        MlsMessageIn::tls_deserialize_exact(bytes.as_slice()).map_err(|e| {
223                            OpenMlsAuthorityError::Resilience(format!(
224                                "missed commit failed to deserialize: {e:?}"
225                            ))
226                        })?;
227                    match self.process_commit(message) {
228                        Ok(_) => applied.push(commit_hash),
229                        Err(e) => {
230                            // A missed commit that will not apply (evicted, corrupt) is unrecoverable
231                            // by replay — the member re-bootstraps.
232                            tracing::warn!(album_id = %self.album_id, error = %e, "reconcile: missed commit unapplicable; unrecoverable");
233                            return Ok(ReconcileOutcome::Unrecoverable);
234                        }
235                    }
236                }
237                tracing::info!(album_id = %self.album_id, server_epoch, applied = applied.len(), "reconcile: replayed missed commits");
238                Ok(ReconcileOutcome::Reconciled {
239                    applied_commits: applied,
240                })
241            }
242            ServerChainView::LocalAhead {
243                server_epoch,
244                provable_fork,
245            } => {
246                if provable_fork {
247                    tracing::warn!(album_id = %self.album_id, local_epoch, server_epoch, "reconcile: provable fork; unrecoverable");
248                    Ok(ReconcileOutcome::Unrecoverable)
249                } else {
250                    // Honestly-lost local commit: surface the divergence (the LostCommitTracker
251                    // drives the re-submit within its budget). Never silently merged.
252                    tracing::warn!(album_id = %self.album_id, local_epoch, server_epoch, "reconcile: local ahead (lost commit); diverged");
253                    Ok(ReconcileOutcome::Diverged {
254                        local_epoch,
255                        server_epoch,
256                    })
257                }
258            }
259        }
260    }
261
262    // ── Group re-keying ceremony ─────────────────────────────────────────────
263
264    /// The full group re-keying ceremony (mls-resilience.md § Group re-keying ceremony): mint a
265    /// fresh epoch (new AMK + write-tier key) for the whole group as one `intent_id`-keyed
266    /// operation, and prepare the fresh epoch's broadcast. Epoch rotation is the primitive; this is
267    /// the doc-specified orchestration. Assets are **not** re-encrypted (content-addressed; prior
268    /// AMKs are retained for reading history) — the ceremony re-attests the fresh epoch's write-tier
269    /// and re-broadcasts the fresh AMK, which is what makes pre-compromise keys useless post-rekey.
270    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, ?reason))]
271    pub fn rekey_group(&mut self, ids: IdSource<'_>, reason: RekeyReason) -> Result<RekeyOutcome> {
272        let (intent_id, commit) = self.begin_rekey(ids, reason)?;
273        let key_delivery = self.finish_rekey()?;
274        tracing::info!(album_id = %self.album_id, %intent_id, epoch = self.ceiling, "group re-keyed");
275        Ok(RekeyOutcome {
276            intent_id,
277            reason,
278            commit,
279            key_delivery,
280        })
281    }
282
283    /// Phase 1 of the re-key: mint the fresh epoch via a self-update commit (fresh epoch secrets ⇒
284    /// fresh AMK, fresh minted write-tier), record the resume state, and return the commit for the
285    /// other members. The single commit is the atomic cutover — until a member applies it, the album
286    /// stays on the prior epoch, so a partial run never leaves two live write-tier keys.
287    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, ?reason))]
288    pub fn begin_rekey(
289        &mut self,
290        ids: IdSource<'_>,
291        reason: RekeyReason,
292    ) -> Result<(Uuid, MlsMessageOut)> {
293        self.ensure_not_tombstoned()?;
294        let intent_id = ids.uuid_v7();
295        let minted = HybridSigningKey::generate();
296        self.set_write_tier_aad(&minted)?;
297        let commit = self
298            .group
299            .self_update(
300                &self.identity.provider,
301                &self.identity.mls_signer,
302                LeafNodeParameters::default(),
303            )
304            .map(CommitMessageBundle::into_commit)
305            .map_err(|e| OpenMlsAuthorityError::Resilience(format!("re-key commit: {e:?}")))?;
306        self.group
307            .merge_pending_commit(&self.identity.provider)
308            .map_err(|e| OpenMlsAuthorityError::Resilience(format!("re-key merge: {e:?}")))?;
309        self.ingest_current_epoch(WriteTierIngest::Minted(minted), true)?;
310        self.rekey_pending = Some(RekeyState { intent_id, reason });
311        tracing::info!(album_id = %self.album_id, %intent_id, epoch = self.ceiling, "re-key phase 1 committed (fresh AMK + write-tier)");
312        Ok((intent_id, commit))
313    }
314
315    /// Phase 2 of the re-key: broadcast the fresh epoch's AMK + write-tier private half and clear the
316    /// resume state. Idempotent — resuming after the intent already completed is a no-op returning no
317    /// messages. The commit is **not** re-produced here (it merged in phase 1), so a resume after a
318    /// crash never advances the epoch a second time.
319    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
320    pub fn finish_rekey(&mut self) -> Result<Vec<MlsMessageOut>> {
321        let state = self.rekey_pending.take().ok_or_else(|| {
322            OpenMlsAuthorityError::Resilience("no re-key in progress to finish".into())
323        })?;
324        if self.completed_intents.contains(&state.intent_id) {
325            return Ok(Vec::new()); // already broadcast — idempotent no-op
326        }
327        let version = self.epoch_ceiling();
328        let key_delivery = vec![
329            self.build_key_distribution(version)?,
330            self.build_write_tier_distribution(version)?,
331        ];
332        self.completed_intents.insert(state.intent_id);
333        tracing::info!(album_id = %self.album_id, intent_id = %state.intent_id, "re-key phase 2 broadcast");
334        Ok(key_delivery)
335    }
336
337    /// Resume an interrupted re-key on restart (crash-resume): if a re-key was mid-flight
338    /// ([`begin_rekey`](Self::begin_rekey) ran but [`finish_rekey`](Self::finish_rekey) did not),
339    /// complete phase 2; otherwise `None`. The `intent_id` guarantees the epoch is never advanced a
340    /// second time.
341    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
342    pub fn resume_rekey(&mut self) -> Result<Option<Vec<MlsMessageOut>>> {
343        if self.rekey_pending.is_some() {
344            tracing::info!(album_id = %self.album_id, "resuming interrupted re-key");
345            Ok(Some(self.finish_rekey()?))
346        } else {
347            Ok(None)
348        }
349    }
350
351    /// Whether a re-key is mid-flight (its commit merged but its broadcast not yet sent).
352    pub fn rekey_in_progress(&self) -> bool {
353        self.rekey_pending.is_some()
354    }
355}