Skip to main content

capsule_core/crypto/
upgrade.rs

1//! The album-upgrade ceremony's **wire vocabulary** — the parts both ends need and neither end
2//! needs MLS for.
3//!
4//! SSoT: [Versioning — Album Upgrade Ceremony](https://docs/design/versioning/#album-upgrade-ceremony).
5//!
6//! # Why this is not in `crypto::authority`
7//!
8//! It was, and it was unreachable. `openmls_authority` is behind the `mls` feature, and a
9//! **key-free server** does not enable it — it holds no group state and cannot read an MLS
10//! message. But the server owns four of the ceremony's steps: the deadline is evaluated on its
11//! trusted clock, the `409` on a stale upload session is its refusal, the drain count is its
12//! answer, and the lineage travels in a manifest it stores. All four need these three types, and
13//! none of them needs a group.
14//!
15//! So the types that are *pure data plus a signature check* live here, ungated, and
16//! `openmls_authority` re-exports them. The custody receipt is shared the same way,
17//! for the same reason: a structure defined at both ends is one added field away from a signature
18//! that stops verifying, so there is one definition and both ends read it.
19//!
20//! What stays behind the feature is everything that touches a group: the `AlbumTombstone` commit,
21//! its receive-side verification, the quiescence state an MLS client persists, and the
22//! `frozen_state_hash` pre-image, which is computed over the MLS-derived member list.
23//!
24//! # What the server can decide from here, and what it cannot
25//!
26//! It can verify [`SignedUpgradeIntent`] against the account's published
27//! [`DeviceDirectory`] — the same trust anchor
28//! the roster uses — so a quiescence it records is one an admin device really asked for. It can
29//! evaluate [`UpgradeIntent::is_expired`] against its own clock, which is the whole point of the
30//! deadline being a *duration*: a skewed member clock can neither extend nor shorten the window.
31//!
32//! It cannot verify the `frozen_state_hash`, and must never try. That hash is each member's
33//! independent statement about its own view of the album, and a server that adjudicated it would
34//! be the single point the ceremony's *"hostile member sabotage"* defence exists to avoid.
35
36use jiff::Timestamp;
37use serde::{Deserialize, Serialize};
38use uuid::Uuid;
39
40use crate::crypto::hash::Hash32;
41use crate::crypto::keys::{DeviceDirectory, HybridSignature};
42
43/// What went wrong reading or verifying an upgrade intent.
44#[derive(Debug, thiserror::Error, PartialEq, Eq)]
45pub enum UpgradeError {
46    /// The intent could not be canonically encoded for signing.
47    #[error("the upgrade intent could not be encoded: {0}")]
48    Encode(String),
49    /// The signature did not verify, or the proposer is not a device of the named account.
50    #[error("the upgrade intent's proposer signature did not verify: {0}")]
51    Proposer(&'static str),
52}
53
54/// The default upgrade deadline (7 days), as a [`jiff::SignedDuration`] the caller can pass to
55/// `OpenMlsAuthority::propose_upgrade`.
56pub const DEFAULT_UPGRADE_DEADLINE: jiff::SignedDuration = jiff::SignedDuration::from_hours(24 * 7);
57
58/// The signed-over content of an upgrade proposal (versioning.md step 1). Every field is covered by
59/// the proposer's DSK hybrid signature in the enclosing [`SignedUpgradeIntent`].
60#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61pub struct UpgradeIntent {
62    /// UUIDv7 idempotency key for the whole ceremony — a duplicate/contradictory proposal under a
63    /// *different* id is rejected while one is in flight; a *replayed* one is a no-op.
64    pub intent_id: Uuid,
65    /// The album's current (immutable) `protocol_version`.
66    pub from_protocol_version: String,
67    /// The target `protocol_version` the fork is pinned to.
68    pub to_protocol_version: String,
69    /// The album's current `crypto_suite_id` wire codepoint.
70    pub from_suite_id: u16,
71    /// The target `crypto_suite_id` wire codepoint (may equal `from_suite_id` for a protocol-only
72    /// upgrade; differs for a suite migration).
73    pub to_suite_id: u16,
74    /// The account the proposing admin device belongs to.
75    pub proposer_user: Uuid,
76    /// The proposing admin device (its DSK signs this intent; verified against the device directory).
77    pub proposer_device: Uuid,
78    /// The deadline **duration** in whole seconds (default [`DEFAULT_UPGRADE_DEADLINE`]). The
79    /// effective expiry is `received_at + deadline` on the **server's** trusted clock — see
80    /// [`is_expired`](Self::is_expired); a member clock can neither extend nor shorten it.
81    pub deadline_secs: u64,
82}
83
84impl UpgradeIntent {
85    /// The canonical-CBOR signing bytes the proposer's DSK covers.
86    ///
87    /// # Errors
88    ///
89    /// Returns [`UpgradeError::Encode`] if the intent cannot be canonically encoded.
90    pub fn signing_bytes(&self) -> Result<Vec<u8>, UpgradeError> {
91        crate::cbor::to_canonical_vec(self).map_err(|e| UpgradeError::Encode(e.to_string()))
92    }
93
94    /// Whether this intent has expired: `now >= received_at + deadline` on the caller's (server's)
95    /// trusted clock. Overflow is treated as expired (fail-closed). This is the **only** clock
96    /// evaluation; it is a server concern here and is exercised in isolation.
97    pub fn is_expired(&self, received_at: Timestamp, now: Timestamp) -> bool {
98        let secs = i64::try_from(self.deadline_secs).unwrap_or(i64::MAX);
99        match received_at.checked_add(jiff::SignedDuration::from_secs(secs)) {
100            Ok(expiry) => now >= expiry,
101            Err(_) => true,
102        }
103    }
104}
105
106/// An [`UpgradeIntent`] plus the proposing admin device's DSK **hybrid** signature over it. Rides
107/// the group's application-message channel (self-describing as the `MlsAppPayload::Upgrade` variant).
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub struct SignedUpgradeIntent {
110    /// The proposed upgrade.
111    pub intent: UpgradeIntent,
112    /// The proposer DSK's hybrid signature over [`UpgradeIntent::signing_bytes`].
113    pub proposer_sig: HybridSignature,
114}
115
116impl SignedUpgradeIntent {
117    /// Verify the proposer's DSK hybrid signature (Ed25519 **and** ML-DSA) against the device
118    /// directory — the same trust resolution `verify_leaf_binding` uses. A stale, forged, or
119    /// wrong-device signature is rejected before any quiescence state is entered.
120    /// # Errors
121    ///
122    /// Returns [`UpgradeError::Proposer`] when the directory names a different account, does not
123    /// hold the proposing device, or the signature does not verify under its DSK.
124    pub fn verify(&self, directory: &DeviceDirectory) -> Result<(), UpgradeError> {
125        if directory.core.user_id != self.intent.proposer_user {
126            return Err(UpgradeError::Proposer(
127                "the intent's proposer_user is not this directory's account",
128            ));
129        }
130        let entry =
131            directory
132                .device(&self.intent.proposer_device)
133                .ok_or(UpgradeError::Proposer(
134                    "the proposing device is not in the directory",
135                ))?;
136        if !entry
137            .dsk_public
138            .verify(&self.intent.signing_bytes()?, &self.proposer_sig)
139        {
140            return Err(UpgradeError::Proposer(
141                "the proposer's DSK signature does not verify",
142            ));
143        }
144        Ok(())
145    }
146}
147
148/// The `upgraded_from` continuity pointer the fork's manifests carry — the normative link between
149/// the old album and its fork (never the MLS group name, which is an internal detail).
150#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
151pub struct UpgradeLineage {
152    /// The album this fork was upgraded from.
153    pub old_album_id: Uuid,
154    /// The ceremony's idempotency key.
155    pub intent_id: Uuid,
156    /// The frozen old-album state hash the tombstone committed to.
157    pub frozen_state_hash: Hash32,
158    /// The old album's `crypto_suite_id`.
159    pub from_suite_id: u16,
160    /// The fork's `crypto_suite_id`.
161    pub to_suite_id: u16,
162}