capsule_core/crypto/authority/openmls_authority/messages.rs
1//! The in-band key-delivery messages an album group exchanges over MLS application messages,
2//! and the per-album [`HistoryPolicy`] that governs what a joiner is entitled to.
3//!
4//! SSoT: [Cryptography — MLS § History Delivery](https://docs/design/cryptography/mls/#history-delivery-for-new-joiners)
5//! and [Keys — AMKs](https://docs/design/cryptography/keys/#album-master-keys-amks) (the
6//! read/write capability split).
7//!
8//! Three payloads ride the group's encrypted application-message channel:
9//!
10//! - [`AlbumKeyDistribution`] `{ amk_version, amk_bytes }` — the doc-named steady-state broadcast:
11//! when a commit advances the epoch, the committer broadcasts the fresh epoch's AMK content key
12//! to **all members** (read capability), flipping their *pending* epoch (ceiling attested, key
13//! not yet local) to *present*.
14//! - [`WriteTierDistribution`] `{ amk_version, write_tier_seed }` — the **write capability**: the
15//! private half of the per-epoch write-tier signing keypair the committer *minted* for the fresh
16//! epoch. Per the keys doc it is "distributed via MLS to **writers only**"; the public half rides
17//! the commit itself (authenticated AAD), so readers can verify manifests without ever holding
18//! the private half. See [`OpenMlsAuthority::writers`](super::OpenMlsAuthority::writers) for the
19//! recipient-set seam (today: all members).
20//! - [`AlbumHistoryBundle`] — the join-time batch a committer sends a freshly-added member, one
21//! [`AmkHistoryEntry`] per prior epoch the album's [`HistoryPolicy`] entitles them to. Each entry
22//! carries that epoch's AMK **and** its write-tier public key, because a joiner cannot re-derive
23//! either for an epoch it never held (it joined after those epochs closed) — so without the
24//! bundle it could neither decrypt nor authorization-check a pre-join asset. Prior epochs are
25//! delivered **read-only** (no private write-tier halves — nobody signs new writes under an old
26//! epoch).
27//!
28//! All are wrapped in [`MlsAppPayload`] so one deprotected application message self-describes which
29//! kind it is. The AMK content key itself is owned by
30//! [Keys — AMKs](https://docs/design/cryptography/keys/#album-master-keys-amks); this module owns
31//! only the *delivery envelope*.
32
33use serde::{Deserialize, Serialize};
34
35use super::upgrade::SignedUpgradeIntent;
36use super::{AMK_LEN, WRITE_TIER_SEED_LEN};
37use crate::crypto::keys::HybridVerifyingKey;
38
39/// How much history a new joiner may decrypt, fixed **per album** at creation and read from the
40/// album's MLS metadata on every add — never chosen per-add, so a member's history visibility
41/// never depends on which device added them or in what order (SSoT: MLS § History Delivery).
42/// Changing it is an album upgrade ceremony, never an ad-hoc per-add decision.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
44pub enum HistoryPolicy {
45 /// Full history (the default for shared albums): the joiner receives every prior AMK
46 /// (`AMK_v1..AMK_current`) and can read every prior asset.
47 Full,
48 /// Capped history: the joiner receives only the most-recent `n` epochs' AMKs. Older assets
49 /// remain visible but not decryptable (placeholders). `n = 0` collapses to "current epoch
50 /// only"; a value ≥ the current epoch count is equivalent to [`Full`](Self::Full).
51 Capped(u32),
52}
53
54impl HistoryPolicy {
55 /// The inclusive `amk_version` range a joiner is entitled to when the album's current epoch
56 /// (ceiling) is `ceiling`. Always includes the current epoch; the lower bound is `1` for
57 /// [`Full`](Self::Full) and `ceiling - n + 1` (floored at `1`) for [`Capped(n)`](Self::Capped).
58 ///
59 /// This is a **pure function of `(policy, ceiling)`** — the load-bearing property that makes a
60 /// joiner's history independent of which admin device performs the add.
61 pub fn entitled_range(self, ceiling: u32) -> std::ops::RangeInclusive<u32> {
62 debug_assert!(
63 ceiling >= 1,
64 "an album always has at least the genesis epoch"
65 );
66 let lo = match self {
67 HistoryPolicy::Full => 1,
68 HistoryPolicy::Capped(n) => ceiling.saturating_sub(n.saturating_sub(1)).max(1),
69 };
70 lo..=ceiling
71 }
72}
73
74/// The doc-named steady-state AMK broadcast for **one** epoch: read capability delivered to all
75/// members over an MLS application message. Its shape is fixed by MLS § History Delivery.
76#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
77pub struct AlbumKeyDistribution {
78 /// The epoch this key belongs to.
79 pub amk_version: u32,
80 /// The 32-byte AMK content key for that epoch.
81 pub amk_bytes: [u8; AMK_LEN],
82}
83
84/// The per-epoch **write capability** delivery: the private half of the write-tier signing
85/// keypair the committer minted for `amk_version`, sent over an MLS application message to the
86/// epoch's writers (SSoT: [Keys — AMKs], "distributed via MLS to writers only"). The public half
87/// is attested by the epoch's commit (authenticated AAD), so this message is the *only* way a
88/// member obtains signing capability — it is never derivable from group secrets.
89///
90/// [Keys — AMKs]: https://docs/design/cryptography/keys/#album-master-keys-amks
91#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
92pub struct WriteTierDistribution {
93 /// The epoch this write-tier key signs for.
94 pub amk_version: u32,
95 /// The 64-byte hybrid seed (Ed25519 secret ‖ ML-DSA ξ) of the epoch's write-tier signing key.
96 #[serde(with = "serde_bytes")]
97 pub write_tier_seed: Vec<u8>,
98}
99
100impl WriteTierDistribution {
101 /// The seed as the fixed 64-byte array [`HybridSigningKey::from_seed64`] consumes, or a
102 /// [`Message`](super::OpenMlsAuthorityError::Message) error on a malformed length.
103 ///
104 /// [`HybridSigningKey::from_seed64`]: crate::crypto::keys::HybridSigningKey::from_seed64
105 pub(crate) fn seed64(&self) -> Result<[u8; WRITE_TIER_SEED_LEN], super::OpenMlsAuthorityError> {
106 self.write_tier_seed.as_slice().try_into().map_err(|_| {
107 super::OpenMlsAuthorityError::Message(format!(
108 "write-tier seed for epoch {} is {} bytes, expected {WRITE_TIER_SEED_LEN}",
109 self.amk_version,
110 self.write_tier_seed.len()
111 ))
112 })
113 }
114}
115
116/// One prior-epoch record in a join-time [`AlbumHistoryBundle`]. Carries both halves a joiner
117/// needs but cannot re-derive for a pre-join epoch: the AMK (to decrypt) and the write-tier public
118/// key (to authorization-check the epoch's manifests through `verify_asset`).
119#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
120pub struct AmkHistoryEntry {
121 /// The prior epoch.
122 pub amk_version: u32,
123 /// The 32-byte AMK content key for that epoch.
124 pub amk_bytes: [u8; AMK_LEN],
125 /// The write-tier public key attested for that epoch (what a manifest's `write_sig` is
126 /// verified against).
127 pub write_tier_pub: HybridVerifyingKey,
128}
129
130/// The join-time history batch a committer sends a newly-added member: the prior epochs the
131/// album's [`HistoryPolicy`] entitles them to, current epoch excluded (the joiner derives that
132/// from the group state delivered in its Welcome).
133#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
134pub struct AlbumHistoryBundle {
135 /// One entry per entitled prior epoch, ascending by `amk_version`.
136 pub entries: Vec<AmkHistoryEntry>,
137}
138
139/// The self-describing wrapper for every Capsule application message on the group channel, so a
140/// deprotected message names which key-delivery kind it carries.
141#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
142pub(crate) enum MlsAppPayload {
143 /// A single-epoch steady-state AMK broadcast (read capability, all members).
144 KeyDistribution(AlbumKeyDistribution),
145 /// A single-epoch write-tier private-key delivery (write capability, writers).
146 WriteTier(WriteTierDistribution),
147 /// A join-time history batch (read-only prior epochs).
148 History(AlbumHistoryBundle),
149 /// A hybrid-signed album [upgrade](super::upgrade) intent. Processed via
150 /// [`receive_upgrade_intent`](super::OpenMlsAuthority::receive_upgrade_intent), **not** the
151 /// key-delivery path — [`process_key_delivery`](super::OpenMlsAuthority::process_key_delivery)
152 /// rejects it.
153 Upgrade(SignedUpgradeIntent),
154}
155
156impl MlsAppPayload {
157 /// Encode to canonical CBOR — the plaintext of an MLS application message.
158 pub(crate) fn to_bytes(&self) -> Result<Vec<u8>, super::OpenMlsAuthorityError> {
159 crate::cbor::to_canonical_vec(self)
160 .map_err(|e| super::OpenMlsAuthorityError::Message(format!("encode: {e}")))
161 }
162
163 /// Decode from an MLS application message plaintext.
164 pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Self, super::OpenMlsAuthorityError> {
165 crate::cbor::from_slice(bytes)
166 .map_err(|e| super::OpenMlsAuthorityError::Message(format!("decode: {e}")))
167 }
168}
169
170#[cfg(test)]
171mod tests;