Skip to main content

capsule_core/crypto/authority/openmls_authority/
mod.rs

1//! The live [`AlbumAuthority`] backed by a real OpenMLS group (RFC 9420), pinned to the
2//! X-Wing PQ ciphersuite `MLS_256_XWING_CHACHA20POLY1305_SHA256_Ed25519` (`0x004D`) via the
3//! formally-verified libcrux provider. This is the design-target authority the offline
4//! [`ReferenceAuthority`](super::ReferenceAuthority) stands in for — it drops in behind the same
5//! `&dyn AlbumAuthority` seam without touching [`verify_asset`](crate::crypto::verify_asset::verify_asset).
6//!
7//! The backend/authority layer provides single-member (self) group creation and the
8//! epoch-ledger semantics `verify_asset` consumes (monotonic ceiling, per-epoch write-tier key,
9//! AMK export, `has_amk` pending window). The membership layer (this module) adds:
10//!
11//! - the four lifecycle ceremonies — [add member](OpenMlsAuthority::add_member),
12//!   [remove member](OpenMlsAuthority::remove_member), [self-update /
13//!   rotate](OpenMlsAuthority::rotate_epoch), and [join via Welcome](OpenMlsAuthority::join_via_welcome)
14//!   — every one driven through OpenMLS commits/Welcome processing, never server-asserted state;
15//! - in-band [`AlbumKeyDistribution`] AMK delivery and per-album [`HistoryPolicy`] history batches
16//!   ([messages]);
17//! - **minted-and-distributed write-tier keys**: the committer of every epoch-advancing commit
18//!   mints the epoch's hybrid write-tier keypair; the *public* half is attested by the commit
19//!   itself (authenticated AAD, i.e. the admin-signed chain), and the *private* half is delivered
20//!   over an MLS [`WriteTierDistribution`] application message to the epoch's
21//!   [writers](OpenMlsAuthority::writers). It is **never derivable from group secrets**, so a
22//!   member outside the distribution set can verify manifests but cannot sign them — the
23//!   keys-doc "distributed via MLS to writers only" shape (today's writer set is all members;
24//!   the filter is the documented roles seam);
25//! - the hybrid **MLS ↔ device-identity LeafNode binding** ([identity]);
26//! - durable group **persistence** via an [export](OpenMlsAuthority::export_state) /
27//!   [import](OpenMlsAuthority::import_state) blob over an owned, serializable storage
28//!   [provider].
29//!
30//! The [upgrade] and [resilience] submodules add the album **upgrade ceremony** and **MLS
31//! resilience**:
32//!
33//! - the **tombstone-plus-fork** upgrade ceremony ([upgrade]): a version-pinned album is frozen by
34//!   an `AlbumTombstone` commit and re-founded as a fork at a target `protocol_version` /
35//!   `crypto_suite_id`, with an `upgraded_from` continuity pointer. Suite-parametric (the general
36//!   vehicle for a future move off the `0x004D` X-Wing suite), `intent_id`-keyed and resumable;
37//! - the **group re-keying ceremony** ([resilience]): a compromise/scheduled response that mints a
38//!   fresh AMK + write-tier key for every member as one `intent_id`-keyed, resumable operation;
39//! - **reconciliation** ([`ReconcileOutcome`]): the single "bring-me-current" entry point over
40//!   the server-authoritative commit chain, plus the lost-commit retry primitive.
41//!
42//! SSoT: [Cryptography — MLS](https://docs/design/cryptography/mls/),
43//! [Keys — Write Authority](https://docs/design/cryptography/keys/#write-authorization),
44//! [MLS Resilience](https://docs/design/mls-resilience/),
45//! [Versioning — Album Upgrade Ceremony](https://docs/design/versioning/#album-upgrade-ceremony).
46
47mod identity;
48mod messages;
49mod provider;
50mod resilience;
51mod upgrade;
52
53use std::collections::{BTreeMap, BTreeSet};
54
55pub use identity::MlsDeviceIdentity;
56use messages::MlsAppPayload;
57pub use messages::{
58    AlbumHistoryBundle, AlbumKeyDistribution, AmkHistoryEntry, HistoryPolicy, WriteTierDistribution,
59};
60use openmls::group::{
61    CommitMessageBundle, GroupId, MlsGroup, MlsGroupJoinConfig, StagedCommit, StagedWelcome,
62};
63use openmls::prelude::{
64    Capabilities, Ciphersuite, LeafNodeIndex, LeafNodeParameters, MlsMessageBodyIn, MlsMessageIn,
65    MlsMessageOut, ProcessedMessageContent,
66};
67use openmls_basic_credential::SignatureKeyPair;
68use openmls_traits::OpenMlsProvider;
69use provider::CapsuleMlsProvider;
70use resilience::RekeyState;
71pub use resilience::{
72    CommitHash, LostCommitTracker, ReconcileOutcome, RekeyOutcome, RekeyReason, ServerChainView,
73};
74use serde::{Deserialize, Serialize};
75use thiserror::Error;
76use upgrade::Quiescence;
77pub use upgrade::{
78    AlbumStateSummary, DEFAULT_UPGRADE_DEADLINE, SignedUpgradeIntent, TombstoneOutcome,
79    UpgradeIntent, UpgradeLineage, UpgradeProposal,
80};
81use uuid::Uuid;
82
83use super::AlbumAuthority;
84use crate::ambient::IdSource;
85use crate::crypto::keys::{AmkVersion, DeviceDirectory, HybridSigningKey, HybridVerifyingKey};
86
87/// The MLS ciphersuite Capsule pins every album group to: X-Wing (ML-KEM-768 + X25519) KEM,
88/// ChaCha20-Poly1305 AEAD, SHA-256, Ed25519 signatures — codepoint `0x004D`. The suite ships
89/// today in OpenMLS via its libcrux provider (SSoT: [Cryptography — MLS](https://docs/design/cryptography/mls/)).
90pub(crate) const PINNED_CIPHERSUITE: Ciphersuite =
91    Ciphersuite::MLS_256_XWING_CHACHA20POLY1305_SHA256_Ed25519;
92
93/// The wire codepoint of `PINNED_CIPHERSUITE`. Asserted in tests so an upstream re-pin can
94/// never silently change the suite Capsule negotiates.
95pub const PINNED_CIPHERSUITE_ID: u16 = 0x004D;
96
97/// The leaf-node capabilities every Capsule key package and founding leaf advertises: exactly
98/// [`PINNED_CIPHERSUITE`], with OpenMLS's defaults for versions, extensions, proposals and
99/// credentials.
100///
101/// Set explicitly because OpenMLS 0.9 lists the X-Wing suite in its *default* capabilities only
102/// under its own `draft-ietf-mls-pq-ciphersuites` feature, which Capsule enables on the leaf
103/// crates instead (see `capsule-core/Cargo.toml`). Without this a leaf would not claim the suite
104/// its group runs, and every add would fail `CiphersuiteNotInCapabilities`. Member commits keep
105/// the leaf's existing capabilities, so the key package and the founder are the only two sites.
106pub(crate) fn pinned_capabilities() -> Capabilities {
107    Capabilities::builder()
108        .ciphersuites(vec![PINNED_CIPHERSUITE])
109        .build()
110}
111
112/// The RFC 9420 exporter label the AMK content key is derived under. A fixed, suite-scoped
113/// domain-separation string; the album id is the exporter *context*, so two albums at the same
114/// epoch never export the same AMK.
115const AMK_EXPORT_LABEL: &str = "capsule amk v1";
116
117/// The AMK content-key length (32 bytes), matching [`Amk`](crate::crypto::keys::Amk).
118pub(crate) const AMK_LEN: usize = 32;
119
120/// The seed length of a hybrid write-tier signing key (32-byte Ed25519 seed ‖ 32-byte ML-DSA ξ).
121/// The per-epoch write-tier keypair is **minted** by the committer (never derived from group
122/// secrets) and its private half distributed via [`WriteTierDistribution`]; this is the length
123/// that message and the persistence blob carry.
124pub(crate) const WRITE_TIER_SEED_LEN: usize = 64;
125
126/// Errors from constructing, advancing, or running a membership ceremony on an
127/// [`OpenMlsAuthority`]. OpenMLS/libcrux error details are captured as English strings
128/// (server-internal diagnostics, not user-facing).
129#[derive(Debug, Error)]
130pub enum OpenMlsAuthorityError {
131    /// The libcrux crypto provider failed to initialise.
132    #[error("libcrux provider init failed: {0}")]
133    Provider(String),
134    /// The MLS leaf signature keypair could not be created or stored.
135    #[error("mls signature keypair: {0}")]
136    Signature(String),
137    /// The MLS group could not be created at the pinned ciphersuite.
138    #[error("mls group create failed: {0}")]
139    GroupCreate(String),
140    /// A self-update commit (epoch advance) failed to be produced or merged.
141    #[error("mls self-update commit failed: {0}")]
142    SelfUpdate(String),
143    /// The RFC 9420 exporter failed to derive the AMK for the current epoch.
144    #[error("mls exporter failed: {0}")]
145    Export(String),
146    /// The exporter returned an AMK of the wrong length (never expected under a fixed suite).
147    #[error("exported AMK wrong length: expected {AMK_LEN}, got {0}")]
148    AmkLength(usize),
149    /// A KeyPackage could not be built for a joining device.
150    #[error("mls key package build failed: {0}")]
151    KeyPackage(String),
152    /// An `Add` proposal + commit failed.
153    #[error("mls add-member ceremony failed: {0}")]
154    AddMember(String),
155    /// A `Remove` proposal + commit failed.
156    #[error("mls remove-member ceremony failed: {0}")]
157    RemoveMember(String),
158    /// Processing an incoming MLS message (commit / application) failed.
159    #[error("mls process-message failed: {0}")]
160    ProcessMessage(String),
161    /// A received message was not the kind the ceremony expected (e.g. a proposal where a commit
162    /// or application message was required).
163    #[error("unexpected mls message: {0}")]
164    UnexpectedMessage(String),
165    /// A `Welcome` could not be processed into a joined group.
166    #[error("mls welcome processing failed: {0}")]
167    Welcome(String),
168    /// The MLS ↔ device-identity LeafNode binding failed to build or verify.
169    #[error("mls leaf identity binding: {0}")]
170    Binding(String),
171    /// An in-band key-delivery message could not be encoded/decoded or applied.
172    #[error("mls key-delivery message: {0}")]
173    Message(String),
174    /// Durable group-state export/import failed.
175    #[error("mls persistence: {0}")]
176    Persist(String),
177    /// A write / ceremony was attempted on a **tombstoned** (frozen) album: the album has been
178    /// upgraded and all activity has moved to the fork. Reads are unaffected — only writes refuse.
179    #[error("album is tombstoned under upgrade intent {0}")]
180    Tombstoned(Uuid),
181    /// A step of the tombstone-plus-fork upgrade ceremony failed (intent signature,
182    /// quiescence conflict, or fork construction).
183    #[error("album upgrade ceremony: {0}")]
184    Upgrade(String),
185    /// A received `AlbumTombstone`'s `frozen_state_hash` disagrees with this member's own recomputed
186    /// hash — at least one member's album view diverges. The upgrade aborts and the album returns to
187    /// normal operation (each member independently).
188    #[error("frozen-state hash mismatch: at least one member's album view diverges")]
189    FrozenStateMismatch,
190    /// A resilience operation (reconciliation / re-keying) failed.
191    #[error("mls resilience: {0}")]
192    Resilience(String),
193    /// [`block_user`](OpenMlsAuthority::block_user) was asked to block the **local** user. A device
194    /// cannot evict itself from its own group, and returning success would tell the caller a block
195    /// took effect when nothing was removed.
196    #[error(
197        "refusing to block the local user {0}: a device cannot remove itself from its own album"
198    )]
199    BlockSelf(Uuid),
200}
201
202impl From<crate::crypto::upgrade::UpgradeError> for OpenMlsAuthorityError {
203    /// The ceremony's wire vocabulary is ungated, so its errors arrive from outside
204    /// this module and are folded into the one variant that already names this ceremony.
205    fn from(error: crate::crypto::upgrade::UpgradeError) -> Self {
206        Self::Upgrade(error.to_string())
207    }
208}
209
210type Result<T> = std::result::Result<T, OpenMlsAuthorityError>;
211
212/// Per-epoch write authority + content key.
213///
214/// The write-tier keypair is **minted by the epoch's committer** and explicitly distributed —
215/// never derived from group secrets — so what a member holds depends on what was delivered to it:
216///
217/// - `write_tier_pub`: `Some` once attested — by the epoch's own commit (authenticated AAD), by a
218///   received [`WriteTierDistribution`], or by a join-time history entry. `None` only in the
219///   narrow window where a joiner has adopted the current epoch from its Welcome but the
220///   committer's write-tier delivery has not yet been applied.
221/// - `write_tier_priv`: `Some` only for an epoch whose [`WriteTierDistribution`] this member
222///   received (or that it minted itself as committer). This is the **only** way signing capability
223///   exists — pending semantics analogous to `has_amk`: a member that has not received the
224///   distribution has no sign-capable handle for the epoch and cannot produce a `write_sig`.
225struct EpochState {
226    write_tier_pub: Option<HybridVerifyingKey>,
227    write_tier_priv: Option<HybridSigningKey>,
228    amk: [u8; AMK_LEN],
229}
230
231/// How an epoch's write-tier key material arrives at
232/// [`OpenMlsAuthority::ingest_current_epoch`].
233enum WriteTierIngest {
234    /// This member is the committer: it minted the keypair (holds both halves).
235    Minted(HybridSigningKey),
236    /// A peer's commit attested the public half through its authenticated AAD; the private half
237    /// awaits the [`WriteTierDistribution`] delivery.
238    Attested(HybridVerifyingKey),
239    /// A joiner adopting the current epoch from a Welcome: neither half yet — both arrive with
240    /// the committer's [`WriteTierDistribution`] in the join's history messages.
241    Deferred,
242}
243
244/// The commit-AAD payload attesting the fresh epoch's write-tier **public** key. Riding the
245/// commit's authenticated data means the attestation is covered by the committer's leaf signature
246/// and validated by OpenMLS with the commit itself — the code-level form of the keys-doc's
247/// "write-tier public key learned from the admin-signed attestation chain", exactly parallel to
248/// how [`ReferenceAuthority`](super::ReferenceAuthority) epochs attest their pubkey.
249#[derive(Serialize, Deserialize)]
250struct WriteTierAttestation {
251    /// The epoch the commit advances the group to.
252    amk_version: u32,
253    /// The write-tier public key minted for that epoch.
254    write_tier_pub: HybridVerifyingKey,
255}
256
257/// The authenticated-data payload every epoch-advancing commit carries. Always attests the fresh
258/// epoch's write-tier public key; on the single `AlbumTombstone` commit of an upgrade ceremony it
259/// **also** carries the [`TombstoneMark`](upgrade::TombstoneMark) so every receiving member can
260/// recompute and check the `frozen_state_hash` before adopting the freeze. Wrapping the two in one
261/// enum keeps a single commit-processing path — [`process_commit`](OpenMlsAuthority::process_commit)
262/// dispatches on the variant.
263#[derive(Serialize, Deserialize)]
264enum CommitAad {
265    /// An ordinary epoch-advancing commit (add / remove / self-update / rotation / re-key).
266    WriteTier(WriteTierAttestation),
267    /// The `AlbumTombstone` commit that freezes the album for an upgrade ceremony. Still attests the
268    /// terminal epoch's write-tier (so ingestion is uniform), plus the tombstone mark.
269    Tombstone {
270        /// The terminal epoch's write-tier attestation (unused for signing — the group is frozen —
271        /// but ingested so the epoch ledger stays well-formed).
272        write_tier: WriteTierAttestation,
273        /// The freeze marker recomputed and checked by every receiving member.
274        mark: upgrade::TombstoneMark,
275    },
276}
277
278/// The outcome of an [`add_member`](OpenMlsAuthority::add_member) ceremony: the artifacts the
279/// caller relays over the (out-of-scope, server-side) delivery service.
280pub struct AddOutcome {
281    /// The `Add` commit, for delivery to the **existing** members so they advance to the new epoch.
282    pub commit: MlsMessageOut,
283    /// The `Welcome`, for delivery to the **joining** device(s).
284    pub welcome: MlsMessageOut,
285    /// In-band key-delivery application messages: the new epoch's [`AlbumKeyDistribution`] (read
286    /// capability, all members), its [`WriteTierDistribution`] (write capability, the
287    /// [writers](OpenMlsAuthority::writers) set), and the joiner's [`AlbumHistoryBundle`] per the
288    /// album's [`HistoryPolicy`]. Recipients apply the ones addressed to their role (application
289    /// is idempotent). Deliver **after** the commit/welcome so recipients are at the new epoch.
290    pub key_delivery: Vec<MlsMessageOut>,
291}
292
293/// The outcome of a [`remove_member`](OpenMlsAuthority::remove_member) ceremony.
294pub struct RemoveOutcome {
295    /// The `Remove` commit, for delivery to the **remaining** members. The removed device cannot
296    /// process it (it is evicted), so it never advances past its removal epoch.
297    pub commit: MlsMessageOut,
298    /// The fresh (re-keyed) epoch's [`AlbumKeyDistribution`] (all remaining members) and
299    /// [`WriteTierDistribution`] (the remaining [writers](OpenMlsAuthority::writers)).
300    pub key_delivery: Vec<MlsMessageOut>,
301}
302
303/// The outcome of a [`block_user`](OpenMlsAuthority::block_user) ceremony.
304///
305/// Deliberately distinguishes "removed them" from "they were not here", because the two have
306/// different consequences for the caller: only the first produces a commit to deliver and a new
307/// epoch to publish keys for.
308pub struct BlockOutcome {
309    /// The user that was blocked.
310    pub user_id: Uuid,
311    /// The leaf indices removed — one per device the blocked user had in this album. Empty iff
312    /// they were not a member.
313    pub removed_leaves: Vec<u32>,
314    /// The epoch new writes are authorized under after the block. Bumped by exactly one when a
315    /// removal happened; the unchanged ceiling otherwise.
316    pub amk_version: AmkVersion,
317    /// The `Remove` commit + the fresh epoch's key delivery, or `None` when the blocked user held
318    /// no leaves in this album (nothing to commit, no epoch burnt).
319    pub removal: Option<RemoveOutcome>,
320}
321
322impl BlockOutcome {
323    /// Whether the blocked user was already absent from this album, so no MLS commit was produced
324    /// and the epoch did not move.
325    pub fn already_absent(&self) -> bool {
326        self.removal.is_none()
327    }
328}
329
330/// An [`AlbumAuthority`] backed by a live OpenMLS group pinned to `PINNED_CIPHERSUITE`.
331///
332/// One instance owns one album's group **as seen by one device**. Its epoch ledger is produced by
333/// real MLS commits (self-update, add, remove) and Welcome processing; every `verify_asset` answer
334/// is read from live MLS state, never a server assertion.
335pub struct OpenMlsAuthority {
336    album_id: Uuid,
337    /// This device's MLS participation identity: the owned provider (crypto + rand + serializable
338    /// storage), the MLS leaf signer, and the hybrid DSK that attests the leaf binding.
339    identity: MlsDeviceIdentity,
340    /// The live MLS group. Its epoch (`u64`) maps to `amk_version = epoch + 1`.
341    group: MlsGroup,
342    /// The album's fixed history policy (album metadata; never chosen per-add).
343    history_policy: HistoryPolicy,
344    /// Per-epoch write authority + AMK, keyed by `amk_version`.
345    epochs: BTreeMap<u32, EpochState>,
346    /// The epochs whose AMK content key is considered locally delivered. `has_amk` reads this,
347    /// modelling the pending window: a commit can attest an epoch (bumping the ceiling) before its
348    /// in-band [`AlbumKeyDistribution`] broadcast arrives locally.
349    amk_held: BTreeSet<u32>,
350    /// The monotonic epoch ceiling (`= max attested amk_version`).
351    ceiling: u32,
352    /// The write-tier keypair minted for a [staged](Self::stage_self_update) (not-yet-merged)
353    /// self-update commit. Consumed by [`merge_pending`](Self::merge_pending) (won) or dropped by
354    /// [`discard_pending_and_process`](Self::discard_pending_and_process) (lost). Transient — not
355    /// persisted (a pending commit does not survive a restart either).
356    staged_write_tier: Option<HybridSigningKey>,
357    // ── upgrade ceremony + resilience state ────────────────────────────
358    /// If this group is a **fork** produced by an upgrade ceremony, the continuity pointer back to
359    /// the album it forked from (the manifest `upgraded_from` field). `None` for an original album.
360    upgraded_from: Option<UpgradeLineage>,
361    /// Set once this album has been **tombstoned** (frozen by an `AlbumTombstone` commit) — carries
362    /// the upgrade `intent_id`. A tombstoned album refuses new write ceremonies (see
363    /// [`ensure_not_tombstoned`](Self::ensure_not_tombstoned)); reads/`verify_asset` are unaffected.
364    tombstoned: Option<Uuid>,
365    /// Upgrade **quiescence**: set on issuing/receiving an [`UpgradeIntent`], so a second intent
366    /// under a *different* `intent_id` is rejected (only one upgrade in flight) and new writes are
367    /// queued locally rather than sent.
368    quiescence: Option<Quiescence>,
369    /// Writes queued locally during upgrade quiescence (`pending_until_upgrade`), replayed into the
370    /// fork after cutover. Opaque encoded payloads — the caller owns the manifest re-encode against
371    /// `to_version` (an application-layer concern outside this authority).
372    pending_writes: Vec<Vec<u8>>,
373    /// Idempotency ledger of completed ceremony `intent_id`s (re-key, upgrade fork). A duplicate
374    /// intent is a no-op — the crash-resume guarantee both ceremonies share.
375    completed_intents: BTreeSet<Uuid>,
376    /// An in-flight re-keying ceremony's resume state (two-phase: commit, then broadcast). Persisted
377    /// so a crash between the two phases resumes on restart.
378    rekey_pending: Option<RekeyState>,
379}
380
381impl OpenMlsAuthority {
382    // ── Construction ────────────────────────────────────────────────────────
383
384    /// Found a new album: create the MLS group for `album_id` with `identity` as its first
385    /// (admin) member, at the pinned X-Wing ciphersuite, and attest the genesis epoch
386    /// (`amk_version = 1`, MLS epoch 0). Mints the epoch-1 write-tier key and AMK; the AMK is held
387    /// locally (the founder authored the epoch). `history_policy` is fixed for the album here.
388    #[tracing::instrument(skip_all, fields(album_id = %album_id, ciphersuite = PINNED_CIPHERSUITE_ID, ?history_policy))]
389    pub fn create_album(
390        identity: MlsDeviceIdentity,
391        album_id: Uuid,
392        history_policy: HistoryPolicy,
393    ) -> Result<Self> {
394        identity.store_signer()?;
395        let credential = identity.credential_with_key()?;
396        let group = MlsGroup::builder()
397            .ciphersuite(PINNED_CIPHERSUITE)
398            .with_capabilities(pinned_capabilities())
399            .use_ratchet_tree_extension(true)
400            .with_group_id(GroupId::from_slice(album_id.as_bytes()))
401            .build(&identity.provider, &identity.mls_signer, credential)
402            .map_err(|e| OpenMlsAuthorityError::GroupCreate(format!("{e:?}")))?;
403
404        let mut authority = Self {
405            album_id,
406            identity,
407            group,
408            history_policy,
409            epochs: BTreeMap::new(),
410            amk_held: BTreeSet::new(),
411            ceiling: 0,
412            staged_write_tier: None,
413            upgraded_from: None,
414            tombstoned: None,
415            quiescence: None,
416            pending_writes: Vec::new(),
417            completed_intents: BTreeSet::new(),
418            rekey_pending: None,
419        };
420        // The founder mints the genesis epoch's write-tier keypair (committer role).
421        authority
422            .ingest_current_epoch(WriteTierIngest::Minted(HybridSigningKey::generate()), true)?;
423        tracing::info!(album_id = %album_id, epoch = authority.ceiling, "OpenMLS album founded");
424        Ok(authority)
425    }
426
427    /// Create a fresh **single-member (self) album group** with a freshly-generated device
428    /// identity and the default [`HistoryPolicy::Full`]. This is the single-member entry point,
429    /// kept for the offline/parity surface; multi-member ceremonies use
430    /// [`create_album`](Self::create_album) with an explicit [`MlsDeviceIdentity`]. The identity's
431    /// user and device ids are UUIDv7s minted from `ids`.
432    #[tracing::instrument(skip_all, fields(album_id = %album_id, ciphersuite = PINNED_CIPHERSUITE_ID))]
433    pub fn create_self_group(ids: IdSource<'_>, album_id: Uuid) -> Result<Self> {
434        let identity = MlsDeviceIdentity::generate(ids.uuid_v7(), ids.uuid_v7())?;
435        Self::create_album(identity, album_id, HistoryPolicy::Full)
436    }
437
438    // ── Ceremony 1/2: add member / add device ────────────────────────────────
439
440    /// **Add** a device (a new user's device, or an existing user's new device) to the album.
441    ///
442    /// Verifies the KeyPackage's hybrid **LeafNode identity binding** against `joiner_directory`
443    /// first — a leaf whose Ed25519 MLS key is not covered by the device DSK's Ed25519 **and**
444    /// ML-DSA identity signature is rejected before any group mutation. Then runs the MLS `Add`
445    /// proposal + `Commit`, advancing to a fresh epoch, and prepares the in-band key delivery:
446    /// the new epoch's AMK for existing members, and the joiner's history batch per the album's
447    /// fixed [`HistoryPolicy`] (never a per-add choice — SSoT: MLS § History Delivery).
448    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, from_epoch = self.ceiling))]
449    pub fn add_member(
450        &mut self,
451        key_package: openmls::prelude::KeyPackage,
452        joiner_directory: &DeviceDirectory,
453    ) -> Result<AddOutcome> {
454        self.ensure_not_tombstoned()?;
455        // Gate: the joining leaf must be identity-bound to a device in the joiner's directory.
456        let (user_id, device_id) = identity::verify_leaf_binding(
457            key_package.leaf_node().credential(),
458            key_package.leaf_node().signature_key().as_slice(),
459            joiner_directory,
460        )?;
461
462        let prior_ceiling = self.ceiling;
463        // Mint the fresh epoch's write-tier keypair and attest its public half in the commit's
464        // authenticated AAD (the admin-signed chain), before building the commit.
465        let minted = HybridSigningKey::generate();
466        self.set_write_tier_aad(&minted)?;
467        let (commit, welcome, _group_info) = self
468            .group
469            .add_members(
470                &self.identity.provider,
471                &self.identity.mls_signer,
472                &[key_package],
473            )
474            .map_err(|e| OpenMlsAuthorityError::AddMember(format!("{e:?}")))?;
475        self.group
476            .merge_pending_commit(&self.identity.provider)
477            .map_err(|e| OpenMlsAuthorityError::AddMember(format!("merge: {e:?}")))?;
478
479        // The add commit advanced the epoch; the committer holds the new AMK + write-tier key.
480        let new_version = self.ingest_current_epoch(WriteTierIngest::Minted(minted), true)?;
481
482        // Key delivery for the fresh epoch: the AMK broadcast (read, all members), the write-tier
483        // private half (write, the writers set — includes the joiner today), and the joiner's
484        // history batch (read-only prior epochs it is entitled to).
485        let key_delivery = vec![
486            self.build_key_distribution(new_version)?,
487            self.build_write_tier_distribution(new_version)?,
488            self.build_history_bundle(new_version)?,
489        ];
490
491        tracing::info!(
492            album_id = %self.album_id, %user_id, %device_id,
493            from_epoch = prior_ceiling, to_epoch = new_version.0,
494            "OpenMLS member added"
495        );
496        Ok(AddOutcome {
497            commit,
498            welcome,
499            key_delivery,
500        })
501    }
502
503    // ── Ceremony 3: remove member / remove device ────────────────────────────
504
505    /// **Remove** a device from the album by its leaf index and re-key: the MLS `Remove` +
506    /// `Commit` advances to a fresh epoch whose new AMK and write-tier key the removed device does
507    /// not hold, so it cannot read or write future epochs. The removed device cannot even process
508    /// the commit (it is evicted). Prepares the fresh AMK's [`AlbumKeyDistribution`] for the
509    /// remaining members (SSoT: MLS § Remove user).
510    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, from_epoch = self.ceiling, leaf = leaf.u32()))]
511    pub fn remove_member(&mut self, leaf: LeafNodeIndex) -> Result<RemoveOutcome> {
512        self.remove_leaves(&[leaf])
513    }
514
515    /// The one remove ceremony, over **one or more** leaves in a single `Remove` + `Commit`.
516    ///
517    /// A per-device removal passes one leaf; a [per-user block](Self::block_user) passes all of
518    /// that user's leaves, which is what the design's "MLS `Remove` proposal + `Commit` removing
519    /// **all** Charlie's devices" means — one commit, therefore exactly **one** epoch bump, not
520    /// one per device. Both spellings share this body so there is a single re-key path to reason
521    /// about.
522    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, from_epoch = self.ceiling, leaves = leaves.len()))]
523    fn remove_leaves(&mut self, leaves: &[LeafNodeIndex]) -> Result<RemoveOutcome> {
524        self.ensure_not_tombstoned()?;
525        // Mint the re-keyed epoch's write-tier keypair; the removed member never receives its
526        // private half (it cannot even decrypt the distribution — it is evicted by the commit).
527        let minted = HybridSigningKey::generate();
528        self.set_write_tier_aad(&minted)?;
529        let (commit, _welcome, _group_info) = self
530            .group
531            .remove_members(&self.identity.provider, &self.identity.mls_signer, leaves)
532            .map_err(|e| OpenMlsAuthorityError::RemoveMember(format!("{e:?}")))?;
533        self.group
534            .merge_pending_commit(&self.identity.provider)
535            .map_err(|e| OpenMlsAuthorityError::RemoveMember(format!("merge: {e:?}")))?;
536
537        let new_version = self.ingest_current_epoch(WriteTierIngest::Minted(minted), true)?;
538        let key_delivery = vec![
539            self.build_key_distribution(new_version)?,
540            self.build_write_tier_distribution(new_version)?,
541        ];
542        tracing::info!(album_id = %self.album_id, to_epoch = new_version.0, removed = leaves.len(), "OpenMLS member removed + re-keyed");
543        Ok(RemoveOutcome {
544            commit,
545            key_delivery,
546        })
547    }
548
549    /// The leaf index of the member whose LeafNode binding names `device_id`, or `None`.
550    /// Convenience for driving a [`remove_member`](Self::remove_member) by device rather than by
551    /// raw leaf index.
552    pub fn leaf_index_of_device(&self, device_id: Uuid) -> Option<LeafNodeIndex> {
553        self.group.members().find_map(|m| {
554            let binding =
555                identity::LeafBinding::from_credential_bytes(m.credential.serialized_content())
556                    .ok()?;
557            (binding.core.device_id == device_id).then_some(m.index)
558        })
559    }
560
561    /// Every leaf index whose LeafNode binding names `user_id` — a user's **whole device set** in
562    /// this album, which is the unit a per-user block removes. Sorted, so the removal is
563    /// deterministic; empty when the user is not a member.
564    ///
565    /// Reads the same hybrid identity binding [`leaf_index_of_device`](Self::leaf_index_of_device)
566    /// does, so a leaf that never passed `verify_leaf_binding` cannot smuggle in a `user_id`.
567    pub fn leaf_indices_of_user(&self, user_id: Uuid) -> Vec<LeafNodeIndex> {
568        let mut leaves: Vec<LeafNodeIndex> = self
569            .group
570            .members()
571            .filter_map(|m| {
572                let binding =
573                    identity::LeafBinding::from_credential_bytes(m.credential.serialized_content())
574                        .ok()?;
575                (binding.core.user_id == user_id).then_some(m.index)
576            })
577            .collect();
578        leaves.sort_by_key(LeafNodeIndex::u32);
579        leaves
580    }
581
582    // ── Ceremony 3b: per-user block (moderation) ─────────────────────────────
583
584    /// **Block a user** from this album: remove *all* of their devices in one MLS
585    /// `Remove` + `Commit` and bump the AMK epoch, so the blocked user loses read access to every
586    /// future epoch and their write-tier capability is rotated out from under them.
587    ///
588    /// This is the crypto half of the [moderation doc's per-user block]; the server-visible half
589    /// (revoking the blocker's `album_share` rows) is enforced independently, so a block is
590    /// complete only when both have run. Per the design, prior epochs' keys the blocked user
591    /// already holds are **not** clawed back — assets they could already read stay readable, which
592    /// is the same removal semantics as any [`remove_member`](Self::remove_member).
593    ///
594    /// Blocking a user who is not a member is a **no-op**, not an error: it reports
595    /// [`BlockOutcome::already_absent`] with the unchanged epoch and no commit. That makes the
596    /// ceremony idempotent, which matters because the server-side block row is itself idempotent
597    /// and a retry must not burn an epoch (and a spurious epoch bump would strand every honest
598    /// concurrent uploader in the pending window for nothing).
599    ///
600    /// Refuses to block the **local** user: a device cannot evict itself from its own group, and
601    /// silently succeeding would leave the caller believing a block took effect.
602    ///
603    /// [moderation doc's per-user block]: https://docs/design/moderation/#blocklists
604    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, from_epoch = self.ceiling, blocked = %user_id))]
605    pub fn block_user(&mut self, user_id: Uuid) -> Result<BlockOutcome> {
606        self.ensure_not_tombstoned()?;
607        if user_id == self.identity.user_id() {
608            return Err(OpenMlsAuthorityError::BlockSelf(user_id));
609        }
610
611        let leaves = self.leaf_indices_of_user(user_id);
612        if leaves.is_empty() {
613            tracing::info!(
614                album_id = %self.album_id,
615                blocked = %user_id,
616                "per-user block: not a member of this album; no MLS Remove, no epoch bump"
617            );
618            return Ok(BlockOutcome {
619                user_id,
620                removed_leaves: Vec::new(),
621                amk_version: AmkVersion(self.ceiling),
622                removal: None,
623            });
624        }
625
626        let removed_leaves: Vec<u32> = leaves.iter().map(LeafNodeIndex::u32).collect();
627        let removal = self.remove_leaves(&leaves)?;
628        let amk_version = AmkVersion(self.ceiling);
629        tracing::info!(
630            album_id = %self.album_id,
631            blocked = %user_id,
632            devices = removed_leaves.len(),
633            to_epoch = amk_version.0,
634            "per-user block: every device removed in one commit; AMK epoch bumped and write-tier \
635             key rotated"
636        );
637        Ok(BlockOutcome {
638            user_id,
639            removed_leaves,
640            amk_version,
641            removal: Some(removal),
642        })
643    }
644
645    // ── Ceremony 4: self-update / scheduled rotation ─────────────────────────
646
647    /// Advance to a fresh epoch via a self-update commit (the scheduled-rotation ceremony): the
648    /// RFC 9420 ratchet moves forward (new epoch secrets ⇒ new AMK + write-tier key), the ceiling
649    /// bumps by one. `amk_present` records whether this epoch's AMK is locally delivered — `true`
650    /// in the committer's own view. Returns the new `amk_version`.
651    ///
652    /// This is the single-member rotation. For the multi-member rotation that also broadcasts
653    /// the fresh AMK to the other members, use [`rotate_epoch`](Self::rotate_epoch).
654    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, amk_present))]
655    pub fn advance_epoch(&mut self, amk_present: bool) -> Result<AmkVersion> {
656        self.ensure_not_tombstoned()?;
657        let minted = HybridSigningKey::generate();
658        self.set_write_tier_aad(&minted)?;
659        self.group
660            .self_update(
661                &self.identity.provider,
662                &self.identity.mls_signer,
663                LeafNodeParameters::default(),
664            )
665            .map_err(|e| OpenMlsAuthorityError::SelfUpdate(format!("{e:?}")))?;
666        self.group
667            .merge_pending_commit(&self.identity.provider)
668            .map_err(|e| OpenMlsAuthorityError::SelfUpdate(format!("merge: {e:?}")))?;
669        let version = self.ingest_current_epoch(WriteTierIngest::Minted(minted), amk_present)?;
670        tracing::info!(album_id = %self.album_id, epoch = version.0, "OpenMLS epoch advanced");
671        Ok(version)
672    }
673
674    /// Scheduled rotation as a ceremony: [`advance_epoch(true)`](Self::advance_epoch) plus the
675    /// commit and the fresh epoch's [`AlbumKeyDistribution`] for the other members.
676    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
677    pub fn rotate_epoch(&mut self) -> Result<RemoveOutcome> {
678        self.ensure_not_tombstoned()?;
679        let minted = HybridSigningKey::generate();
680        self.set_write_tier_aad(&minted)?;
681        // The self-update stages a pending commit; capture it for the other members before merge.
682        let commit = self
683            .group
684            .self_update(
685                &self.identity.provider,
686                &self.identity.mls_signer,
687                LeafNodeParameters::default(),
688            )
689            .map(CommitMessageBundle::into_commit)
690            .map_err(|e| OpenMlsAuthorityError::SelfUpdate(format!("{e:?}")))?;
691        self.group
692            .merge_pending_commit(&self.identity.provider)
693            .map_err(|e| OpenMlsAuthorityError::SelfUpdate(format!("merge: {e:?}")))?;
694        let version = self.ingest_current_epoch(WriteTierIngest::Minted(minted), true)?;
695        let key_delivery = vec![
696            self.build_key_distribution(version)?,
697            self.build_write_tier_distribution(version)?,
698        ];
699        Ok(RemoveOutcome {
700            commit,
701            key_delivery,
702        })
703    }
704
705    // ── Concurrent-commit resolution (two members commit against one epoch) ───
706    //
707    // These are the OpenMLS convergence primitives: a member *stages* a self-update commit
708    // without merging it, then either merges it (its commit won the delivery-service ordering) or
709    // discards it and processes the winning peer's commit (it lost, and rebases). This is how two
710    // parallel commits against the same epoch converge with no group split. The full partition /
711    // reconciliation ceremony (`ReconcileOutcome`, tombstone-fork) lives in `resilience`/`upgrade`.
712
713    /// Stage a self-update commit **without merging** it, returning the commit for the other
714    /// members. Mints (and stashes) the prospective epoch's write-tier keypair; the group holds
715    /// the pending commit until [`merge_pending`](Self::merge_pending) (won) or
716    /// [`discard_pending_and_process`](Self::discard_pending_and_process) (lost — the stashed
717    /// keypair is dropped with the commit).
718    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, epoch = self.ceiling))]
719    pub fn stage_self_update(&mut self) -> Result<MlsMessageOut> {
720        self.ensure_not_tombstoned()?;
721        let minted = HybridSigningKey::generate();
722        self.set_write_tier_aad(&minted)?;
723        let commit = self
724            .group
725            .self_update(
726                &self.identity.provider,
727                &self.identity.mls_signer,
728                LeafNodeParameters::default(),
729            )
730            .map(CommitMessageBundle::into_commit)
731            .map_err(|e| OpenMlsAuthorityError::SelfUpdate(format!("{e:?}")))?;
732        self.staged_write_tier = Some(minted);
733        Ok(commit)
734    }
735
736    /// Merge this member's own staged pending commit — the "my commit won" path. Advances the
737    /// epoch, holds the fresh AMK, and installs the write-tier keypair minted at staging.
738    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
739    pub fn merge_pending(&mut self) -> Result<AmkVersion> {
740        let minted = self
741            .staged_write_tier
742            .take()
743            .ok_or_else(|| OpenMlsAuthorityError::SelfUpdate("no staged commit to merge".into()))?;
744        self.group
745            .merge_pending_commit(&self.identity.provider)
746            .map_err(|e| OpenMlsAuthorityError::SelfUpdate(format!("merge: {e:?}")))?;
747        self.ingest_current_epoch(WriteTierIngest::Minted(minted), true)
748    }
749
750    /// Discard this member's own staged pending commit and process the winning peer's commit
751    /// instead — the "my commit lost, rebase" path. Leaves this member converged on the peer's
752    /// epoch with no divergence; the write-tier keypair minted at staging is dropped (its epoch
753    /// never existed on the chain).
754    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
755    pub fn discard_pending_and_process(
756        &mut self,
757        winning_commit: MlsMessageIn,
758    ) -> Result<AmkVersion> {
759        self.staged_write_tier = None;
760        self.group
761            .clear_pending_commit(<CapsuleMlsProvider as OpenMlsProvider>::storage(
762                &self.identity.provider,
763            ))
764            .map_err(|e| OpenMlsAuthorityError::ProcessMessage(format!("clear pending: {e:?}")))?;
765        self.process_commit(winning_commit)
766    }
767
768    // ── Receive side: process a peer's commit / key delivery ─────────────────
769
770    /// Process a peer's commit (add / remove / self-update) delivered over the group channel:
771    /// merge it, advancing this member's view to the new epoch. The commit's authenticated AAD
772    /// attests the fresh epoch's write-tier **public** key (installed immediately, so
773    /// `verify_asset` can check the epoch's manifests); the AMK and the write-tier **private**
774    /// half are both **pending** until their [`AlbumKeyDistribution`] / [`WriteTierDistribution`]
775    /// deliveries arrive via [`process_key_delivery`](Self::process_key_delivery). Returns the new
776    /// `amk_version`.
777    ///
778    /// A member removed by this commit is evicted: OpenMLS marks the group inactive and this
779    /// returns the merged (now-inactive) state.
780    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, from_epoch = self.ceiling))]
781    pub fn process_commit(&mut self, message: MlsMessageIn) -> Result<AmkVersion> {
782        let protocol = protocol_message(message)?;
783        let processed = self
784            .group
785            .process_message(&self.identity.provider, protocol)
786            .map_err(|e| OpenMlsAuthorityError::ProcessMessage(format!("{e:?}")))?;
787        // The committer's write-tier attestation rides the commit's authenticated data — covered
788        // by the committer's leaf signature, validated with the commit by OpenMLS.
789        let aad = processed.aad().to_vec();
790        match processed.into_content() {
791            ProcessedMessageContent::StagedCommitMessage(staged) => {
792                let attestation = match parse_commit_aad(&aad)? {
793                    CommitAad::WriteTier(a) => a,
794                    CommitAad::Tombstone { .. } => {
795                        return Err(OpenMlsAuthorityError::Upgrade(
796                            "AlbumTombstone commit must be processed via process_tombstone".into(),
797                        ));
798                    }
799                };
800                let staged: StagedCommit = *staged;
801                self.group
802                    .merge_staged_commit(&self.identity.provider, staged)
803                    .map_err(|e| OpenMlsAuthorityError::ProcessMessage(format!("merge: {e:?}")))?;
804                // A member removed by this commit is now inactive; its exporter is unavailable.
805                if !self.group.is_active() {
806                    tracing::info!(album_id = %self.album_id, "OpenMLS: evicted by processed commit");
807                    return Err(OpenMlsAuthorityError::ProcessMessage(
808                        "evicted from group by this commit".into(),
809                    ));
810                }
811                let version = self.ingest_current_epoch(
812                    WriteTierIngest::Attested(attestation.write_tier_pub),
813                    false,
814                )?;
815                if attestation.amk_version != version.0 {
816                    return Err(OpenMlsAuthorityError::ProcessMessage(format!(
817                        "commit attests write-tier for epoch {}, but advances the group to {}",
818                        attestation.amk_version, version.0
819                    )));
820                }
821                tracing::debug!(album_id = %self.album_id, epoch = version.0, "OpenMLS peer commit merged (AMK + write-tier private pending)");
822                Ok(version)
823            }
824            other => Err(OpenMlsAuthorityError::UnexpectedMessage(format!(
825                "expected a commit, got {}",
826                describe_content(&other)
827            ))),
828        }
829    }
830
831    /// Apply an in-band key-delivery application message — an [`AlbumKeyDistribution`] (a single
832    /// epoch's AMK, flipping it from pending to present), a [`WriteTierDistribution`] (the epoch's
833    /// write-tier private half, granting signing capability), or an [`AlbumHistoryBundle`] (a
834    /// joiner's prior-epoch batch). This is the vehicle that closes the pending windows.
835    #[tracing::instrument(skip_all, fields(album_id = %self.album_id))]
836    pub fn process_key_delivery(&mut self, message: MlsMessageIn) -> Result<()> {
837        let protocol = protocol_message(message)?;
838        let processed = self
839            .group
840            .process_message(&self.identity.provider, protocol)
841            .map_err(|e| OpenMlsAuthorityError::ProcessMessage(format!("{e:?}")))?;
842        match processed.into_content() {
843            ProcessedMessageContent::ApplicationMessage(app) => {
844                match MlsAppPayload::from_bytes(&app.into_bytes())? {
845                    MlsAppPayload::KeyDistribution(kd) => self.apply_key_distribution(&kd),
846                    MlsAppPayload::WriteTier(wt) => self.apply_write_tier_distribution(&wt),
847                    MlsAppPayload::History(bundle) => {
848                        for entry in &bundle.entries {
849                            self.apply_history_entry(entry);
850                        }
851                        Ok(())
852                    }
853                    MlsAppPayload::Upgrade(_) => Err(OpenMlsAuthorityError::Upgrade(
854                        "upgrade intent must be processed via receive_upgrade_intent".into(),
855                    )),
856                }
857            }
858            other => Err(OpenMlsAuthorityError::UnexpectedMessage(format!(
859                "expected an application message, got {}",
860                describe_content(&other)
861            ))),
862        }
863    }
864
865    // ── Ceremony 4 (join side): adopt a Welcome ──────────────────────────────
866
867    /// Join an album as a new member by processing a `Welcome`. Adopts the group, learns the
868    /// album's **current epoch as its monotonic ceiling from the commit chain** (never the
869    /// server), derives + holds the current epoch's AMK, then applies the committer's
870    /// `history_messages` (the [`AlbumHistoryBundle`] and current-epoch [`AlbumKeyDistribution`])
871    /// to populate the prior epochs its [`HistoryPolicy`] entitles it to.
872    ///
873    /// `history_policy` is the album's fixed policy, communicated to the joiner with the invite;
874    /// binding it into the group's context extension so it is cryptographically album-fixed (not
875    /// merely conveyed) is a follow-up (see module docs).
876    #[tracing::instrument(skip_all, fields(ciphersuite = PINNED_CIPHERSUITE_ID))]
877    pub fn join_via_welcome(
878        identity: MlsDeviceIdentity,
879        welcome_message: MlsMessageIn,
880        history_messages: Vec<MlsMessageIn>,
881        history_policy: HistoryPolicy,
882    ) -> Result<Self> {
883        // `into_welcome` is `test-utils`-gated upstream; `extract` (the public body accessor) is not.
884        let MlsMessageBodyIn::Welcome(welcome) = welcome_message.extract() else {
885            return Err(OpenMlsAuthorityError::Welcome(
886                "message is not a Welcome".into(),
887            ));
888        };
889        let join_config = MlsGroupJoinConfig::builder()
890            .use_ratchet_tree_extension(true)
891            .build();
892        let staged =
893            StagedWelcome::new_from_welcome(&identity.provider, &join_config, welcome, None)
894                .map_err(|e| OpenMlsAuthorityError::Welcome(format!("{e:?}")))?;
895        let group = staged
896            .into_group(&identity.provider)
897            .map_err(|e| OpenMlsAuthorityError::Welcome(format!("into_group: {e:?}")))?;
898
899        let album_id = uuid_from_group_id(group.group_id())?;
900        let mut authority = Self {
901            album_id,
902            identity,
903            group,
904            history_policy,
905            epochs: BTreeMap::new(),
906            amk_held: BTreeSet::new(),
907            ceiling: 0,
908            staged_write_tier: None,
909            upgraded_from: None,
910            tombstoned: None,
911            quiescence: None,
912            pending_writes: Vec::new(),
913            completed_intents: BTreeSet::new(),
914            rekey_pending: None,
915        };
916        // The joiner is a full member at the current epoch: derive + hold its AMK. This also sets
917        // the monotonic ceiling from the (chain-attested) group epoch. The epoch's write-tier key
918        // material is deferred — both halves arrive with the committer's `WriteTierDistribution`
919        // in `history_messages` (a joiner has no signing capability until it does).
920        let current = authority.ingest_current_epoch(WriteTierIngest::Deferred, true)?;
921        tracing::info!(album_id = %album_id, epoch = current.0, "OpenMLS joined via Welcome");
922
923        for message in history_messages {
924            authority.process_key_delivery(message)?;
925        }
926        Ok(authority)
927    }
928
929    // ── Write-path guard ─────────────────────────────────────────────────────
930
931    /// Refuse a write-producing ceremony on a [tombstoned](Self::is_tombstoned) (frozen) album. The
932    /// album has been upgraded; all new activity belongs on the fork. Reads are never gated here —
933    /// only commit-producing entry points call this, so `verify_asset` stays byte-for-byte untouched.
934    fn ensure_not_tombstoned(&self) -> Result<()> {
935        match self.tombstoned {
936            Some(intent_id) => Err(OpenMlsAuthorityError::Tombstoned(intent_id)),
937            None => Ok(()),
938        }
939    }
940
941    // ── Epoch ingestion + derivation ─────────────────────────────────────────
942
943    /// Record the group's *current* epoch as `amk_version = mls_epoch + 1`: export its AMK from
944    /// the live MLS epoch secrets, install its write-tier key material per how it arrived
945    /// ([`WriteTierIngest`]), and raise the ceiling. `amk_present` marks whether this member holds
946    /// the AMK content key locally (the pending window seam).
947    fn ingest_current_epoch(
948        &mut self,
949        write_tier: WriteTierIngest,
950        amk_present: bool,
951    ) -> Result<AmkVersion> {
952        let version = u32::try_from(self.group.epoch().as_u64() + 1).map_err(|_| {
953            OpenMlsAuthorityError::Export("mls epoch overflows u32 amk_version".into())
954        })?;
955        let (write_tier_pub, write_tier_priv) = match write_tier {
956            WriteTierIngest::Minted(key) => (Some(key.verifying_key()), Some(key)),
957            WriteTierIngest::Attested(pub_key) => (Some(pub_key), None),
958            WriteTierIngest::Deferred => (None, None),
959        };
960        let amk = self.export_current_amk()?;
961        self.epochs.insert(
962            version,
963            EpochState {
964                write_tier_pub,
965                write_tier_priv,
966                amk,
967            },
968        );
969        if amk_present {
970            self.amk_held.insert(version);
971        }
972        self.ceiling = self.ceiling.max(version);
973        Ok(AmkVersion(version))
974    }
975
976    /// Set the pending commit's authenticated AAD to the [`WriteTierAttestation`] for the epoch
977    /// the commit will advance the group to (`current mls_epoch + 2` in `amk_version` terms:
978    /// current version is `epoch + 1`, the commit bumps it by one). Must be called immediately
979    /// before the commit-building operation — OpenMLS consumes and resets the AAD per operation.
980    fn set_write_tier_aad(&mut self, minted: &HybridSigningKey) -> Result<()> {
981        self.set_commit_aad(&CommitAad::WriteTier(
982            self.next_write_tier_attestation(minted)?,
983        ))
984    }
985
986    /// The [`WriteTierAttestation`] for the epoch the next commit will advance the group to
987    /// (`current mls_epoch + 2` in `amk_version` terms).
988    fn next_write_tier_attestation(
989        &self,
990        minted: &HybridSigningKey,
991    ) -> Result<WriteTierAttestation> {
992        let next_version = u32::try_from(self.group.epoch().as_u64() + 2).map_err(|_| {
993            OpenMlsAuthorityError::Export("mls epoch overflows u32 amk_version".into())
994        })?;
995        Ok(WriteTierAttestation {
996            amk_version: next_version,
997            write_tier_pub: minted.verifying_key(),
998        })
999    }
1000
1001    /// Encode a [`CommitAad`] into the group's pending-commit authenticated data. Must be called
1002    /// immediately before the commit-building operation — OpenMLS consumes and resets the AAD per
1003    /// operation.
1004    fn set_commit_aad(&mut self, aad: &CommitAad) -> Result<()> {
1005        let bytes = crate::cbor::to_canonical_vec(aad)
1006            .map_err(|e| OpenMlsAuthorityError::Message(format!("commit aad encode: {e}")))?;
1007        self.group.set_aad(bytes);
1008        Ok(())
1009    }
1010
1011    /// Export the AMK content key for the group's **current** epoch from the RFC 9420 exporter.
1012    /// Deterministic for a fixed epoch; the album id is the exporter context so two albums never
1013    /// collide at the same epoch.
1014    pub fn export_current_amk(&self) -> Result<[u8; AMK_LEN]> {
1015        let bytes = self
1016            .group
1017            .export_secret(
1018                self.identity.provider.crypto(),
1019                AMK_EXPORT_LABEL,
1020                self.album_id.as_bytes(),
1021                AMK_LEN,
1022            )
1023            .map_err(|e| OpenMlsAuthorityError::Export(format!("{e:?}")))?;
1024        bytes
1025            .try_into()
1026            .map_err(|v: Vec<u8>| OpenMlsAuthorityError::AmkLength(v.len()))
1027    }
1028
1029    // ── Key-delivery construction + application ──────────────────────────────
1030
1031    /// Build the steady-state [`AlbumKeyDistribution`] application message for `version`.
1032    fn build_key_distribution(&mut self, version: AmkVersion) -> Result<MlsMessageOut> {
1033        let amk = self
1034            .epochs
1035            .get(&version.0)
1036            .ok_or_else(|| {
1037                OpenMlsAuthorityError::Message(format!("no AMK for epoch {}", version.0))
1038            })?
1039            .amk;
1040        let payload = MlsAppPayload::KeyDistribution(AlbumKeyDistribution {
1041            amk_version: version.0,
1042            amk_bytes: amk,
1043        });
1044        self.create_app_message(&payload)
1045    }
1046
1047    /// Build the [`WriteTierDistribution`] application message delivering `version`'s write-tier
1048    /// **private** half to the epoch's writers — the only vehicle by which signing capability
1049    /// exists (SSoT: [Keys — AMKs], "distributed via MLS to writers only").
1050    ///
1051    /// **Writer-set seam:** the recipient set is [`writers()`](Self::writers). Today that is every
1052    /// member, so the delivery is a single group-encrypted application message; when the roles
1053    /// model lands, a proper subset forces per-writer delivery (e.g. HPKE to each writer's leaf
1054    /// encryption key) instead of the group channel — the seam is this method's send-path, not the
1055    /// message shape.
1056    ///
1057    /// [Keys — AMKs]: https://docs/design/cryptography/keys/#album-master-keys-amks
1058    fn build_write_tier_distribution(&mut self, version: AmkVersion) -> Result<MlsMessageOut> {
1059        let seed = self
1060            .epochs
1061            .get(&version.0)
1062            .and_then(|e| e.write_tier_priv.as_ref())
1063            .ok_or_else(|| {
1064                OpenMlsAuthorityError::Message(format!(
1065                    "no write-tier private key held for epoch {}",
1066                    version.0
1067                ))
1068            })?
1069            .to_seed_bytes();
1070        debug_assert_eq!(
1071            self.writers().len(),
1072            self.member_count(),
1073            "roles model not in core yet: the writer set must be all members, so the group \
1074             channel is a faithful delivery of the writers-only message"
1075        );
1076        let payload = MlsAppPayload::WriteTier(WriteTierDistribution {
1077            amk_version: version.0,
1078            write_tier_seed: seed.to_vec(),
1079        });
1080        self.create_app_message(&payload)
1081    }
1082
1083    /// Build the joiner's [`AlbumHistoryBundle`]: the prior epochs (strictly below `current`) the
1084    /// album's [`HistoryPolicy`] entitles a joiner to, each with its AMK and write-tier public key
1085    /// (read-only — prior epochs never carry the private half; nobody signs new writes under an
1086    /// old epoch).
1087    fn build_history_bundle(&mut self, current: AmkVersion) -> Result<MlsMessageOut> {
1088        let range = self.history_policy.entitled_range(current.0);
1089        let entries = range
1090            .filter(|v| *v < current.0)
1091            .filter_map(|v| {
1092                self.epochs.get(&v).and_then(|e| {
1093                    e.write_tier_pub.as_ref().map(|pub_key| AmkHistoryEntry {
1094                        amk_version: v,
1095                        amk_bytes: e.amk,
1096                        write_tier_pub: pub_key.clone(),
1097                    })
1098                })
1099            })
1100            .collect();
1101        let payload = MlsAppPayload::History(AlbumHistoryBundle { entries });
1102        self.create_app_message(&payload)
1103    }
1104
1105    fn create_app_message(&mut self, payload: &MlsAppPayload) -> Result<MlsMessageOut> {
1106        let bytes = payload.to_bytes()?;
1107        self.group
1108            .create_message(&self.identity.provider, &self.identity.mls_signer, &bytes)
1109            .map_err(|e| OpenMlsAuthorityError::Message(format!("create app message: {e:?}")))
1110    }
1111
1112    /// Apply a received [`AlbumKeyDistribution`]: mark the epoch's AMK present. The epoch must
1113    /// already be attested (its commit processed) — the pending window always closes *after* the
1114    /// commit that opened it — and the delivered bytes must match what this member derived, or the
1115    /// delivery is a forgery/inconsistency and is rejected.
1116    fn apply_key_distribution(&mut self, kd: &AlbumKeyDistribution) -> Result<()> {
1117        match self.epochs.get(&kd.amk_version) {
1118            Some(state) => {
1119                if state.amk != kd.amk_bytes {
1120                    return Err(OpenMlsAuthorityError::Message(format!(
1121                        "delivered AMK for epoch {} disagrees with derived AMK",
1122                        kd.amk_version
1123                    )));
1124                }
1125                self.amk_held.insert(kd.amk_version);
1126                Ok(())
1127            }
1128            None => Err(OpenMlsAuthorityError::Message(format!(
1129                "AMK delivery for unattested epoch {} (commit not yet processed)",
1130                kd.amk_version
1131            ))),
1132        }
1133    }
1134
1135    /// Apply a received [`WriteTierDistribution`]: install the epoch's write-tier private half,
1136    /// granting signing capability. The epoch must already be attested (its commit processed), and
1137    /// when the commit's AAD attested a public key, the delivered private half must derive exactly
1138    /// that key — a mismatch is a forgery/inconsistency and is rejected.
1139    fn apply_write_tier_distribution(&mut self, wt: &WriteTierDistribution) -> Result<()> {
1140        let key = HybridSigningKey::from_seed64(&wt.seed64()?);
1141        match self.epochs.get_mut(&wt.amk_version) {
1142            Some(state) => {
1143                let derived_pub = key.verifying_key();
1144                if let Some(attested) = &state.write_tier_pub {
1145                    if *attested != derived_pub {
1146                        return Err(OpenMlsAuthorityError::Message(format!(
1147                            "write-tier delivery for epoch {} disagrees with the chain-attested \
1148                             public key",
1149                            wt.amk_version
1150                        )));
1151                    }
1152                } else {
1153                    // Joiner path: the Welcome carried no attestation; adopt the delivered key's
1154                    // public half (same committer trust as the AMK history batch).
1155                    state.write_tier_pub = Some(derived_pub);
1156                }
1157                state.write_tier_priv = Some(key);
1158                Ok(())
1159            }
1160            None => Err(OpenMlsAuthorityError::Message(format!(
1161                "write-tier delivery for unattested epoch {} (commit not yet processed)",
1162                wt.amk_version
1163            ))),
1164        }
1165    }
1166
1167    /// Apply a received history entry: install a prior epoch's read-only state (AMK + write-tier
1168    /// public key), marking it present. Skips epochs the member already holds derived (idempotent)
1169    /// and any entry at/above the current ceiling (history is strictly prior).
1170    fn apply_history_entry(&mut self, entry: &AmkHistoryEntry) {
1171        if entry.amk_version >= self.ceiling || self.epochs.contains_key(&entry.amk_version) {
1172            // Current-or-future epoch (derived by the joiner) or already known — nothing to add.
1173            self.amk_held.insert(entry.amk_version);
1174            return;
1175        }
1176        self.epochs.insert(
1177            entry.amk_version,
1178            EpochState {
1179                write_tier_pub: Some(entry.write_tier_pub.clone()),
1180                write_tier_priv: None,
1181                amk: entry.amk_bytes,
1182            },
1183        );
1184        self.amk_held.insert(entry.amk_version);
1185    }
1186
1187    // ── Accessors ────────────────────────────────────────────────────────────
1188
1189    /// This device's MLS participation identity.
1190    pub fn identity(&self) -> &MlsDeviceIdentity {
1191        &self.identity
1192    }
1193
1194    /// The album's fixed history policy.
1195    pub fn history_policy(&self) -> HistoryPolicy {
1196        self.history_policy
1197    }
1198
1199    /// The number of members currently in the group.
1200    pub fn member_count(&self) -> usize {
1201        self.group.members().count()
1202    }
1203
1204    /// The epoch's **writer set** — the recipients of a [`WriteTierDistribution`].
1205    ///
1206    /// **Roles seam:** core has no roles model yet, so every member is a writer and this returns
1207    /// all leaves — which is what makes the group-encrypted application channel a faithful
1208    /// "writers-only" delivery today. When the roles model lands, this filter narrows to the
1209    /// role-holding leaves and `build_write_tier_distribution`'s
1210    /// send-path switches to per-writer delivery (the group channel is readable by every member,
1211    /// so a proper subset cannot ride it).
1212    pub fn writers(&self) -> Vec<LeafNodeIndex> {
1213        self.group.members().map(|m| m.index).collect()
1214    }
1215
1216    /// The cached AMK content key for `epoch`, or `None` if this member holds no state for it.
1217    pub fn amk(&self, epoch: AmkVersion) -> Option<[u8; AMK_LEN]> {
1218        self.epochs.get(&epoch.0).map(|e| e.amk)
1219    }
1220
1221    /// Mark an epoch's AMK content key as locally delivered — mirrors
1222    /// [`ReferenceAuthority::mark_amk_present`](super::ReferenceAuthority::mark_amk_present).
1223    pub fn mark_amk_present(&mut self, epoch: AmkVersion) {
1224        if self.epochs.contains_key(&epoch.0) {
1225            self.amk_held.insert(epoch.0);
1226        }
1227    }
1228
1229    /// The write-tier **signing** key for `epoch` — the private half a writer signs manifests
1230    /// with. `None` unless this member minted the key (committer) or received the epoch's
1231    /// [`WriteTierDistribution`]: signing capability is **never derivable from group state** —
1232    /// no distribution, no sign-capable handle. Also `None` for a read-only prior epoch delivered
1233    /// through a join-time history bundle.
1234    pub fn write_tier_signing_key(&self, epoch: AmkVersion) -> Option<&HybridSigningKey> {
1235        self.epochs
1236            .get(&epoch.0)
1237            .and_then(|e| e.write_tier_priv.as_ref())
1238    }
1239
1240    /// The current (ceiling) epoch's write-tier signing key — the one new writes are signed under.
1241    ///
1242    /// Panics if this member holds no signing capability for the current epoch (its
1243    /// [`WriteTierDistribution`] has not arrived) — committer-side convenience; a receive-side
1244    /// caller must use [`write_tier_signing_key`](Self::write_tier_signing_key) and treat `None`
1245    /// as "cannot write yet" (pending, analogous to `has_amk`).
1246    pub fn current_write_tier(&self) -> &HybridSigningKey {
1247        self.epochs
1248            .get(&self.ceiling)
1249            .and_then(|e| e.write_tier_priv.as_ref())
1250            .expect("current epoch write-tier distribution not yet received: no signing capability")
1251    }
1252
1253    /// The live MLS group epoch (`u64`). `amk_version` is always this plus one.
1254    pub fn mls_epoch(&self) -> u64 {
1255        self.group.epoch().as_u64()
1256    }
1257
1258    /// The ciphersuite the group is actually running — asserted `== PINNED_CIPHERSUITE` in tests.
1259    pub fn ciphersuite(&self) -> Ciphersuite {
1260        self.group.ciphersuite()
1261    }
1262
1263    // ── Durable persistence (export / import) ────────────────────────────────
1264
1265    /// Export the full durable group state to a self-contained byte blob: the OpenMLS storage
1266    /// keyspace (ratchet tree, epoch secrets, queued proposals, the leaf signer, key-package
1267    /// bundles) plus Capsule's epoch ledger and this device's identity. Round-trips through
1268    /// [`import_state`](Self::import_state). *Where* the blob is stored (a `library.sqlite` row, a
1269    /// file) is the caller's lifecycle concern.
1270    #[tracing::instrument(skip_all, fields(album_id = %self.album_id, epoch = self.ceiling))]
1271    pub fn export_state(&self) -> Result<Vec<u8>> {
1272        let epochs = self
1273            .epochs
1274            .iter()
1275            .map(|(version, state)| PersistedEpoch {
1276                version: *version,
1277                write_tier_priv_seed64: state
1278                    .write_tier_priv
1279                    .as_ref()
1280                    .map(|k| serde_bytes::ByteBuf::from(k.to_seed_bytes().to_vec())),
1281                write_tier_pub: state.write_tier_pub.clone(),
1282                amk: state.amk,
1283                held: self.amk_held.contains(version),
1284            })
1285            .collect();
1286        let persisted = PersistedState {
1287            album_id: self.album_id,
1288            history_policy: self.history_policy,
1289            user_id: self.identity.user_id,
1290            device_id: self.identity.device_id,
1291            dsk_seed64: serde_bytes::ByteBuf::from(self.identity.dsk.to_seed_bytes().to_vec()),
1292            // Only the *public* MLS signer key is persisted here; the keypair itself lives in the
1293            // OpenMLS storage blob (it was `store`d on create/join), so it round-trips there and is
1294            // read back with `SignatureKeyPair::read` on import (the `private()` accessor is
1295            // `test-utils`-gated upstream, so we never touch the private bytes directly).
1296            mls_signer_public: serde_bytes::ByteBuf::from(
1297                self.identity.mls_signer.public().to_vec(),
1298            ),
1299            group_id: serde_bytes::ByteBuf::from(self.group.group_id().to_vec()),
1300            storage_blob: serde_bytes::ByteBuf::from(self.identity.provider.export_bytes()?),
1301            epochs,
1302            ceiling: self.ceiling,
1303            upgraded_from: self.upgraded_from.clone(),
1304            tombstoned: self.tombstoned,
1305            quiescence: self.quiescence.clone(),
1306            pending_writes: self
1307                .pending_writes
1308                .iter()
1309                .map(|w| serde_bytes::ByteBuf::from(w.clone()))
1310                .collect(),
1311            completed_intents: self.completed_intents.iter().copied().collect(),
1312            rekey_pending: self.rekey_pending.clone(),
1313        };
1314        crate::cbor::to_canonical_vec(&persisted)
1315            .map_err(|e| OpenMlsAuthorityError::Persist(format!("encode: {e}")))
1316    }
1317
1318    /// Reconstruct an authority from an [`export_state`](Self::export_state) blob.
1319    #[tracing::instrument(skip_all)]
1320    pub fn import_state(bytes: &[u8]) -> Result<Self> {
1321        let persisted: PersistedState = crate::cbor::from_slice(bytes)
1322            .map_err(|e| OpenMlsAuthorityError::Persist(format!("decode: {e}")))?;
1323
1324        let provider = CapsuleMlsProvider::import_bytes(&persisted.storage_blob)?;
1325        // Recover the MLS leaf signer from the storage keyspace by its public key.
1326        let mls_signer = SignatureKeyPair::read(
1327            <CapsuleMlsProvider as OpenMlsProvider>::storage(&provider),
1328            &persisted.mls_signer_public,
1329            PINNED_CIPHERSUITE.signature_algorithm(),
1330        )
1331        .ok_or_else(|| OpenMlsAuthorityError::Persist("mls signer not found in storage".into()))?;
1332        let identity = MlsDeviceIdentity {
1333            user_id: persisted.user_id,
1334            device_id: persisted.device_id,
1335            dsk: HybridSigningKey::from_seed64(&seed64(&persisted.dsk_seed64)?),
1336            mls_signer,
1337            provider,
1338        };
1339        let group = MlsGroup::load(
1340            <CapsuleMlsProvider as OpenMlsProvider>::storage(&identity.provider),
1341            &GroupId::from_slice(&persisted.group_id),
1342        )
1343        .map_err(|e| OpenMlsAuthorityError::Persist(format!("group load: {e:?}")))?
1344        .ok_or_else(|| OpenMlsAuthorityError::Persist("group not found in storage".into()))?;
1345
1346        let mut epochs = BTreeMap::new();
1347        let mut amk_held = BTreeSet::new();
1348        for pe in persisted.epochs {
1349            if pe.held {
1350                amk_held.insert(pe.version);
1351            }
1352            let write_tier_priv = pe
1353                .write_tier_priv_seed64
1354                .map(|s| {
1355                    Ok::<_, OpenMlsAuthorityError>(HybridSigningKey::from_seed64(&seed64(&s)?))
1356                })
1357                .transpose()?;
1358            epochs.insert(
1359                pe.version,
1360                EpochState {
1361                    write_tier_pub: pe.write_tier_pub,
1362                    write_tier_priv,
1363                    amk: pe.amk,
1364                },
1365            );
1366        }
1367        Ok(Self {
1368            album_id: persisted.album_id,
1369            identity,
1370            group,
1371            history_policy: persisted.history_policy,
1372            epochs,
1373            amk_held,
1374            ceiling: persisted.ceiling,
1375            // A pending (staged, unmerged) commit does not survive a restart; neither does the
1376            // write-tier keypair minted for it.
1377            staged_write_tier: None,
1378            upgraded_from: persisted.upgraded_from,
1379            tombstoned: persisted.tombstoned,
1380            quiescence: persisted.quiescence,
1381            pending_writes: persisted
1382                .pending_writes
1383                .into_iter()
1384                .map(serde_bytes::ByteBuf::into_vec)
1385                .collect(),
1386            completed_intents: persisted.completed_intents.into_iter().collect(),
1387            rekey_pending: persisted.rekey_pending,
1388        })
1389    }
1390}
1391
1392/// Convert a persisted seed byte string back into a fixed 64-byte seed pair.
1393fn seed64(bytes: &[u8]) -> Result<[u8; WRITE_TIER_SEED_LEN]> {
1394    bytes
1395        .try_into()
1396        .map_err(|_| OpenMlsAuthorityError::Persist("persisted seed is not 64 bytes".into()))
1397}
1398
1399/// One epoch's ledger row in a [`PersistedState`].
1400#[derive(Serialize, Deserialize)]
1401struct PersistedEpoch {
1402    version: u32,
1403    write_tier_priv_seed64: Option<serde_bytes::ByteBuf>,
1404    write_tier_pub: Option<HybridVerifyingKey>,
1405    amk: [u8; AMK_LEN],
1406    held: bool,
1407}
1408
1409/// The durable state blob for an [`OpenMlsAuthority`].
1410#[derive(Serialize, Deserialize)]
1411struct PersistedState {
1412    album_id: Uuid,
1413    history_policy: HistoryPolicy,
1414    user_id: Uuid,
1415    device_id: Uuid,
1416    dsk_seed64: serde_bytes::ByteBuf,
1417    mls_signer_public: serde_bytes::ByteBuf,
1418    group_id: serde_bytes::ByteBuf,
1419    storage_blob: serde_bytes::ByteBuf,
1420    epochs: Vec<PersistedEpoch>,
1421    ceiling: u32,
1422    // ── Upgrade ceremony state ───────────────────────────────────────────────
1423    upgraded_from: Option<UpgradeLineage>,
1424    tombstoned: Option<Uuid>,
1425    quiescence: Option<Quiescence>,
1426    pending_writes: Vec<serde_bytes::ByteBuf>,
1427    completed_intents: Vec<Uuid>,
1428    rekey_pending: Option<RekeyState>,
1429}
1430
1431/// Recover an album [`Uuid`] from an MLS [`GroupId`] set to the album id's 16 bytes.
1432fn uuid_from_group_id(group_id: &GroupId) -> Result<Uuid> {
1433    let bytes: [u8; 16] = group_id
1434        .as_slice()
1435        .try_into()
1436        .map_err(|_| OpenMlsAuthorityError::Welcome("group id is not a 16-byte album id".into()))?;
1437    Ok(Uuid::from_bytes(bytes))
1438}
1439
1440/// A short human label for an unexpected processed-message content, for error diagnostics.
1441fn describe_content(content: &ProcessedMessageContent) -> &'static str {
1442    match content {
1443        ProcessedMessageContent::ApplicationMessage(_) => "application message",
1444        ProcessedMessageContent::ProposalMessage(_) => "proposal",
1445        ProcessedMessageContent::ExternalJoinProposalMessage(_) => "external-join proposal",
1446        ProcessedMessageContent::StagedCommitMessage(_) => "commit",
1447        ProcessedMessageContent::OwnPendingCommit => "own pending commit",
1448        ProcessedMessageContent::OwnPrivateMessage => "own private message",
1449    }
1450}
1451
1452/// Turn an incoming MLS message into a [`ProtocolMessage`](openmls::prelude::ProtocolMessage) (a
1453/// commit or application message) or a typed error. Uses OpenMLS's public
1454/// `try_into_protocol_message` (the `into_protocol_message` convenience is `test-utils`-gated
1455/// upstream).
1456fn protocol_message(message: MlsMessageIn) -> Result<openmls::prelude::ProtocolMessage> {
1457    message.try_into_protocol_message().map_err(|e| {
1458        OpenMlsAuthorityError::UnexpectedMessage(format!("not a protocol message: {e:?}"))
1459    })
1460}
1461
1462/// Decode a commit's authenticated data into the [`CommitAad`] the committer attached, or a typed
1463/// error if the commit carries no valid Capsule attestation (never expected on a well-formed chain).
1464fn parse_commit_aad(aad: &[u8]) -> Result<CommitAad> {
1465    crate::cbor::from_slice(aad).map_err(|e| {
1466        OpenMlsAuthorityError::ProcessMessage(format!(
1467            "commit carries no valid Capsule attestation: {e}"
1468        ))
1469    })
1470}
1471
1472impl AlbumAuthority for OpenMlsAuthority {
1473    fn album_id(&self) -> Uuid {
1474        self.album_id
1475    }
1476
1477    fn epoch_ceiling(&self) -> AmkVersion {
1478        AmkVersion(self.ceiling)
1479    }
1480
1481    fn write_tier_pubkey(&self, epoch: AmkVersion) -> Option<HybridVerifyingKey> {
1482        // `None` both for an unattested epoch and for the narrow joiner window where the current
1483        // epoch's write-tier delivery has not yet been applied (no attested key to verify against).
1484        self.epochs
1485            .get(&epoch.0)
1486            .and_then(|e| e.write_tier_pub.clone())
1487    }
1488
1489    fn has_amk(&self, epoch: AmkVersion) -> bool {
1490        self.amk_held.contains(&epoch.0)
1491    }
1492
1493    fn admin_chain_verifies(&self) -> bool {
1494        // The live group *is* the admin-signed commit chain: OpenMLS validated every commit as it
1495        // was processed, so a group we hold is trusted iff it is the pinned suite, still active
1496        // (not evicted), and has attested at least the genesis epoch with a consistent ceiling.
1497        self.group.ciphersuite() == PINNED_CIPHERSUITE
1498            && self.group.is_active()
1499            && self.ceiling >= 1
1500            && self.ceiling == self.epochs.keys().copied().max().unwrap_or(0)
1501    }
1502}
1503
1504#[cfg(test)]
1505mod tests;