Skip to main content

capsule_core/crypto/authority/openmls_authority/
upgrade.rs

1//! The **tombstone-plus-fork album upgrade ceremony**.
2//!
3//! SSoT: [Versioning — Album Upgrade Ceremony](https://docs/design/versioning/#album-upgrade-ceremony).
4//!
5//! A version-pinned album's `protocol_version` is immutable for its lifetime, so adopting a new
6//! protocol feature — or migrating to a new `crypto_suite_id` (e.g. a future move off the `0x004D`
7//! X-Wing suite) — requires **freezing** the old album and **forking** a fresh one at the target
8//! version. The ceremony is atomic at the user level (the single `AlbumTombstone` commit is the
9//! cutover) and resumable (`intent_id`-keyed). This module owns the MLS-layer half: the signed
10//! `UpgradeIntent`, quiescence, the `frozen_state_hash`, the `AlbumTombstone` commit + its
11//! receive-side verification, and the fork's `upgraded_from` continuity pointer.
12//!
13//! **Suite-parametric.** The intent and lineage carry `from_suite_id` / `to_suite_id` as `u16`
14//! wire codepoints, so the ceremony is the general migration vehicle even though only `0x0001`
15//! (whose MLS suite is `0x004D`) exists in this build. Reads of the old album are never gated —
16//! only *writes* refuse after a tombstone (`verify_asset` stays byte-for-byte untouched).
17//!
18//! **The wire vocabulary moved out.** [`UpgradeIntent`], [`SignedUpgradeIntent`] and
19//! [`UpgradeLineage`] now live in [`crate::crypto::upgrade`], **ungated**, because the key-free
20//! server owns four of the ceremony's steps and does not enable the `mls` feature. They
21//! are re-exported here so this module reads as it did. What stays is everything that touches a
22//! group.
23
24use openmls::group::CommitMessageBundle;
25use openmls::prelude::{LeafNodeParameters, MlsMessageIn, MlsMessageOut, ProcessedMessageContent};
26use serde::{Deserialize, Serialize};
27use uuid::Uuid;
28
29use super::identity::{LeafBinding, LeafBindingCore};
30use super::messages::MlsAppPayload;
31use super::{
32    CommitAad, OpenMlsAuthority, OpenMlsAuthorityError, Result, WriteTierIngest, describe_content,
33    parse_commit_aad, protocol_message,
34};
35use crate::ambient::IdSource;
36use crate::crypto::hash::{self, Hash32};
37use crate::crypto::keys::{DeviceDirectory, HybridSigningKey};
38pub use crate::crypto::upgrade::{
39    DEFAULT_UPGRADE_DEADLINE, SignedUpgradeIntent, UpgradeIntent, UpgradeLineage,
40};
41
42/// The caller-supplied facts about an album's full state that the `frozen_state_hash` is computed
43/// over, **alongside** the MLS-derived sorted member list. Owned by the application/library layer
44/// (this authority has no view of manifests or the provenance log), so the caller assembles it from
45/// its own accepted state; a member whose view diverges yields a different hash and aborts the
46/// tombstone (each member independently).
47#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
48pub struct AlbumStateSummary {
49    /// Every accepted manifest's content hash (order-independent — hashed sorted).
50    pub manifest_hashes: Vec<Hash32>,
51    /// The head of the album's provenance log, if any.
52    pub provenance_head: Option<Hash32>,
53}
54
55/// The freeze marker an `AlbumTombstone` commit carries in its authenticated data (inside
56/// [`CommitAad::Tombstone`]). Every receiving member recomputes `frozen_state_hash` over its own
57/// state and compares — mismatch aborts the upgrade.
58#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
59pub(super) struct TombstoneMark {
60    /// The ceremony's idempotency key.
61    pub intent_id: Uuid,
62    /// The proposer's `frozen_state_hash` over the album's full state.
63    pub frozen_state_hash: Hash32,
64}
65
66/// The upgrade-quiescence state an album enters on issuing/receiving an [`UpgradeIntent`]. Persisted
67/// (so a crash mid-ceremony resumes) and consulted to reject a second, conflicting intent.
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69pub(super) struct Quiescence {
70    /// The in-flight ceremony's idempotency key.
71    pub intent_id: Uuid,
72    /// The `protocol_version` the fork will be pinned to (drives queued-write re-encoding).
73    pub to_protocol_version: String,
74    /// The fork's `crypto_suite_id`.
75    pub to_suite_id: u16,
76    /// The proposing admin device.
77    pub proposer_device: Uuid,
78}
79
80/// The artifacts a [`propose_upgrade`](OpenMlsAuthority::propose_upgrade) call produces.
81pub struct UpgradeProposal {
82    /// The signed intent (kept by the proposer; also carried in `message`).
83    pub signed_intent: SignedUpgradeIntent,
84    /// The MLS application message broadcasting the intent to the other members.
85    pub message: MlsMessageOut,
86}
87
88/// The artifacts a [`commit_tombstone`](OpenMlsAuthority::commit_tombstone) call produces.
89pub struct TombstoneOutcome {
90    /// The ceremony's idempotency key.
91    pub intent_id: Uuid,
92    /// The `frozen_state_hash` the tombstone committed to.
93    pub frozen_state_hash: Hash32,
94    /// The `AlbumTombstone` commit, for delivery to the other members (they verify + freeze).
95    pub commit: MlsMessageOut,
96}
97
98/// The canonical-CBOR pre-image of an album's `frozen_state_hash`: the album id, the sorted member
99/// list, and the caller-supplied [`AlbumStateSummary`] (with its manifest hashes sorted).
100#[derive(Serialize)]
101struct FrozenState {
102    album_id: Uuid,
103    members: Vec<LeafBindingCore>,
104    manifest_hashes: Vec<Hash32>,
105    provenance_head: Option<Hash32>,
106}
107
108impl OpenMlsAuthority {
109    // ── Step 1: propose (admin) / receive (member) ───────────────────────────
110
111    /// **Step 1 (admin).** Issue a hybrid-signed [`UpgradeIntent`] and enter upgrade quiescence.
112    /// The `intent_id` is minted here, a UUIDv7 from `ids`. Returns the signed intent + the MLS
113    /// application message to broadcast to the other members. Refused if the album is already
114    /// tombstoned or already quiescing under another intent.
115    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, %to_suite_id))]
116    pub fn propose_upgrade(
117        &mut self,
118        ids: IdSource<'_>,
119        from_protocol_version: impl Into<String>,
120        from_suite_id: u16,
121        to_protocol_version: impl Into<String>,
122        to_suite_id: u16,
123        deadline: jiff::SignedDuration,
124    ) -> Result<UpgradeProposal> {
125        self.ensure_not_tombstoned()?;
126        if let Some(q) = &self.quiescence {
127            return Err(OpenMlsAuthorityError::Upgrade(format!(
128                "album is already quiescing under upgrade intent {}",
129                q.intent_id
130            )));
131        }
132        let deadline_secs = u64::try_from(deadline.as_secs().max(0)).unwrap_or(0);
133        let intent = UpgradeIntent {
134            intent_id: ids.uuid_v7(),
135            from_protocol_version: from_protocol_version.into(),
136            to_protocol_version: to_protocol_version.into(),
137            from_suite_id,
138            to_suite_id,
139            proposer_user: self.identity.user_id,
140            proposer_device: self.identity.device_id,
141            deadline_secs,
142        };
143        let proposer_sig = self.identity.dsk.sign(&intent.signing_bytes()?);
144        let signed = SignedUpgradeIntent {
145            intent: intent.clone(),
146            proposer_sig,
147        };
148        let message = self.create_app_message(&MlsAppPayload::Upgrade(signed.clone()))?;
149        self.enter_quiescence(&intent);
150        tracing::info!(album_id = %self.album_id, intent_id = %intent.intent_id, "album upgrade proposed; entering quiescence");
151        Ok(UpgradeProposal {
152            signed_intent: signed,
153            message,
154        })
155    }
156
157    /// **Step 1/2 (member).** Process a broadcast [`UpgradeIntent`]: verify the proposer's DSK
158    /// hybrid signature against `directory`, then enter quiescence. Rejects a *different* intent
159    /// while one is already in flight (only one upgrade per album); a re-receipt of the same intent
160    /// is idempotent. Returns the verified signed intent.
161    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
162    pub fn receive_upgrade_intent(
163        &mut self,
164        message: MlsMessageIn,
165        directory: &DeviceDirectory,
166    ) -> Result<SignedUpgradeIntent> {
167        let protocol = protocol_message(message)?;
168        let processed = self
169            .group
170            .process_message(&self.identity.provider, protocol)
171            .map_err(|e| OpenMlsAuthorityError::ProcessMessage(format!("{e:?}")))?;
172        let signed = match processed.into_content() {
173            ProcessedMessageContent::ApplicationMessage(app) => {
174                match MlsAppPayload::from_bytes(&app.into_bytes())? {
175                    MlsAppPayload::Upgrade(signed) => signed,
176                    _ => {
177                        return Err(OpenMlsAuthorityError::UnexpectedMessage(
178                            "expected an upgrade intent application message".into(),
179                        ));
180                    }
181                }
182            }
183            other => {
184                return Err(OpenMlsAuthorityError::UnexpectedMessage(format!(
185                    "expected an application message, got {}",
186                    describe_content(&other)
187                )));
188            }
189        };
190        signed.verify(directory)?;
191        if let Some(q) = &self.quiescence {
192            if q.intent_id != signed.intent.intent_id {
193                return Err(OpenMlsAuthorityError::Upgrade(format!(
194                    "album is already quiescing under a different upgrade intent {}",
195                    q.intent_id
196                )));
197            }
198            return Ok(signed); // idempotent re-receipt
199        }
200        self.enter_quiescence(&signed.intent);
201        tracing::info!(album_id = %self.album_id, intent_id = %signed.intent.intent_id, "upgrade intent accepted; entering quiescence");
202        Ok(signed)
203    }
204
205    // ── Step 2/3: quiescence write queue ─────────────────────────────────────
206
207    /// Queue a write locally during upgrade quiescence (`pending_until_upgrade`). The caller owns
208    /// the opaque encoding; the writes are handed back by [`take_pending_writes`](Self::take_pending_writes)
209    /// after cutover for re-encoding against the fork's `to_version`. Refused if not quiescing.
210    pub fn queue_pending_write(&mut self, encoded_write: Vec<u8>) -> Result<()> {
211        if self.quiescence.is_none() {
212            return Err(OpenMlsAuthorityError::Upgrade(
213                "album is not in upgrade quiescence; write directly".into(),
214            ));
215        }
216        self.pending_writes.push(encoded_write);
217        Ok(())
218    }
219
220    /// Drain the locally-queued `pending_until_upgrade` writes (for replay into the fork). Draining
221    /// is the caller's cue to re-encode each against the fork's `to_version` and replay it.
222    pub fn take_pending_writes(&mut self) -> Vec<Vec<u8>> {
223        std::mem::take(&mut self.pending_writes)
224    }
225
226    // ── Step 4: tombstone (freeze) ───────────────────────────────────────────
227
228    /// The album's `frozen_state_hash` over its full state: the album id, the sorted member list
229    /// (from live MLS group state), and the caller's [`AlbumStateSummary`]. Suite-fixed SHA-256.
230    pub fn frozen_state_hash(&self, summary: &AlbumStateSummary) -> Result<Hash32> {
231        let members = self.sorted_member_bindings()?;
232        let mut manifest_hashes = summary.manifest_hashes.clone();
233        manifest_hashes.sort();
234        let frozen = FrozenState {
235            album_id: self.album_id,
236            members,
237            manifest_hashes,
238            provenance_head: summary.provenance_head,
239        };
240        let bytes = crate::cbor::to_canonical_vec(&frozen)
241            .map_err(|e| OpenMlsAuthorityError::Upgrade(format!("frozen-state encode: {e}")))?;
242        Ok(hash::hash_bytes(&bytes))
243    }
244
245    /// **Step 4 (admin).** Freeze the album with an `AlbumTombstone` commit: compute the
246    /// `frozen_state_hash` over `summary`, attach it (with the terminal epoch's write-tier
247    /// attestation) to the commit's authenticated data, advance the group one terminal epoch, and
248    /// mark the album tombstoned. Requires an in-flight quiescence ([`propose_upgrade`](Self::propose_upgrade)).
249    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
250    pub fn commit_tombstone(&mut self, summary: &AlbumStateSummary) -> Result<TombstoneOutcome> {
251        self.ensure_not_tombstoned()?;
252        let quiescence = self.quiescence.clone().ok_or_else(|| {
253            OpenMlsAuthorityError::Upgrade(
254                "no upgrade in quiescence; call propose_upgrade first".into(),
255            )
256        })?;
257        let frozen_state_hash = self.frozen_state_hash(summary)?;
258        let minted = HybridSigningKey::generate();
259        let write_tier = self.next_write_tier_attestation(&minted)?;
260        let mark = TombstoneMark {
261            intent_id: quiescence.intent_id,
262            frozen_state_hash,
263        };
264        self.set_commit_aad(&CommitAad::Tombstone {
265            write_tier,
266            mark: mark.clone(),
267        })?;
268        let commit = self
269            .group
270            .self_update(
271                &self.identity.provider,
272                &self.identity.mls_signer,
273                LeafNodeParameters::default(),
274            )
275            .map(CommitMessageBundle::into_commit)
276            .map_err(|e| OpenMlsAuthorityError::Upgrade(format!("tombstone commit: {e:?}")))?;
277        self.group
278            .merge_pending_commit(&self.identity.provider)
279            .map_err(|e| OpenMlsAuthorityError::Upgrade(format!("tombstone merge: {e:?}")))?;
280        self.ingest_current_epoch(WriteTierIngest::Minted(minted), true)?;
281        self.tombstoned = Some(quiescence.intent_id);
282        self.completed_intents.insert(quiescence.intent_id);
283        tracing::info!(album_id = %self.album_id, intent_id = %quiescence.intent_id, %frozen_state_hash, "album tombstoned (frozen for upgrade)");
284        Ok(TombstoneOutcome {
285            intent_id: quiescence.intent_id,
286            frozen_state_hash,
287            commit,
288        })
289    }
290
291    /// **Step 4 (member).** Process a received `AlbumTombstone` commit: recompute `frozen_state_hash`
292    /// over this member's own `summary` and compare it to the committed mark. On mismatch the
293    /// upgrade **aborts cleanly** — the staged commit is dropped, the album stays at its prior epoch
294    /// and normal operation ([`FrozenStateMismatch`](OpenMlsAuthorityError::FrozenStateMismatch)).
295    /// On match, the freeze is adopted (album tombstoned). Idempotent for a re-delivered tombstone
296    /// of an already-frozen album.
297    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
298    pub fn process_tombstone(
299        &mut self,
300        message: MlsMessageIn,
301        summary: &AlbumStateSummary,
302    ) -> Result<()> {
303        let protocol = protocol_message(message)?;
304        let processed = self
305            .group
306            .process_message(&self.identity.provider, protocol)
307            .map_err(|e| OpenMlsAuthorityError::ProcessMessage(format!("{e:?}")))?;
308        let aad = processed.aad().to_vec();
309        match processed.into_content() {
310            ProcessedMessageContent::StagedCommitMessage(staged) => {
311                let (write_tier, mark) = match parse_commit_aad(&aad)? {
312                    CommitAad::Tombstone { write_tier, mark } => (write_tier, mark),
313                    CommitAad::WriteTier(_) => {
314                        return Err(OpenMlsAuthorityError::Upgrade(
315                            "expected an AlbumTombstone commit, got an ordinary commit".into(),
316                        ));
317                    }
318                };
319                // Verify BEFORE merging: a self-update tombstone leaves the member list unchanged,
320                // so the local hash is stable across the merge. On mismatch we drop the staged
321                // commit (never merge) — the album stays at its prior epoch.
322                let local_hash = self.frozen_state_hash(summary)?;
323                if local_hash != mark.frozen_state_hash {
324                    tracing::warn!(album_id = %self.album_id, intent_id = %mark.intent_id, "tombstone frozen-state hash mismatch; aborting upgrade");
325                    return Err(OpenMlsAuthorityError::FrozenStateMismatch);
326                }
327                self.group
328                    .merge_staged_commit(&self.identity.provider, *staged)
329                    .map_err(|e| {
330                        OpenMlsAuthorityError::Upgrade(format!("tombstone merge: {e:?}"))
331                    })?;
332                let version = self.ingest_current_epoch(
333                    WriteTierIngest::Attested(write_tier.write_tier_pub),
334                    false,
335                )?;
336                if write_tier.amk_version != version.0 {
337                    return Err(OpenMlsAuthorityError::Upgrade(format!(
338                        "tombstone attests epoch {}, but advances the group to {}",
339                        write_tier.amk_version, version.0
340                    )));
341                }
342                self.tombstoned = Some(mark.intent_id);
343                self.completed_intents.insert(mark.intent_id);
344                tracing::info!(album_id = %self.album_id, intent_id = %mark.intent_id, "tombstone accepted; album frozen for upgrade");
345                Ok(())
346            }
347            other => Err(OpenMlsAuthorityError::UnexpectedMessage(format!(
348                "expected a commit, got {}",
349                describe_content(&other)
350            ))),
351        }
352    }
353
354    // ── Step 5: fork ─────────────────────────────────────────────────────────
355
356    /// **Step 5.** Found the fork: a fresh MLS album group at `new_album_id` and the target
357    /// version, minting `AMK_v1` + a fresh write-tier key (via [`create_album`](Self::create_album)),
358    /// and recording the `upgraded_from` continuity pointer. Members are then migrated with the
359    /// standard [`add_member`](Self::add_member) / [`join_via_welcome`](Self::join_via_welcome) flow.
360    /// Assets are **not** re-encrypted — the fork references the existing ciphertext by content hash.
361    #[tracing::instrument(skip_all, fields(%new_album_id, old_album_id = %lineage.old_album_id, to_suite = lineage.to_suite_id))]
362    pub fn fork_upgrade(
363        admin_identity: super::MlsDeviceIdentity,
364        new_album_id: Uuid,
365        lineage: UpgradeLineage,
366        history_policy: super::HistoryPolicy,
367    ) -> Result<OpenMlsAuthority> {
368        let mut forked =
369            OpenMlsAuthority::create_album(admin_identity, new_album_id, history_policy)?;
370        tracing::info!(%new_album_id, intent_id = %lineage.intent_id, "album forked for upgrade");
371        forked.upgraded_from = Some(lineage);
372        Ok(forked)
373    }
374
375    // ── Accessors ────────────────────────────────────────────────────────────
376
377    /// The upgrade `intent_id` this album was tombstoned under, or `None` if it is live.
378    pub fn is_tombstoned(&self) -> Option<Uuid> {
379        self.tombstoned
380    }
381
382    /// The `upgraded_from` continuity pointer, if this album is a fork produced by an upgrade.
383    pub fn upgraded_from(&self) -> Option<&UpgradeLineage> {
384        self.upgraded_from.as_ref()
385    }
386
387    /// The `intent_id` of an in-flight upgrade quiescence, or `None`.
388    pub fn quiescing_intent(&self) -> Option<Uuid> {
389        self.quiescence.as_ref().map(|q| q.intent_id)
390    }
391
392    /// Whether a ceremony `intent_id` has already completed on this authority (idempotency ledger).
393    pub fn has_completed_intent(&self, intent_id: Uuid) -> bool {
394        self.completed_intents.contains(&intent_id)
395    }
396
397    // ── Internals ────────────────────────────────────────────────────────────
398
399    /// The live group's members as sorted [`LeafBindingCore`]s (by `user_id` then `device_id`) —
400    /// the deterministic member list the `frozen_state_hash` folds in.
401    fn sorted_member_bindings(&self) -> Result<Vec<LeafBindingCore>> {
402        let mut members: Vec<LeafBindingCore> = self
403            .group
404            .members()
405            .map(|m| {
406                LeafBinding::from_credential_bytes(m.credential.serialized_content())
407                    .map(|b| b.core)
408            })
409            .collect::<Result<_>>()?;
410        members.sort_by_key(|m| (m.user_id, m.device_id));
411        Ok(members)
412    }
413
414    fn enter_quiescence(&mut self, intent: &UpgradeIntent) {
415        self.quiescence = Some(Quiescence {
416            intent_id: intent.intent_id,
417            to_protocol_version: intent.to_protocol_version.clone(),
418            to_suite_id: intent.to_suite_id,
419            proposer_device: intent.proposer_device,
420        });
421    }
422}