Skip to main content

capsule_core/crypto/authority/
reference.rs

1//! A deterministic, admin-signature-backed [`AlbumAuthority`] used in place of a live
2//! OpenMLS group (deferred). It is an **admin-signed epoch ledger**: each epoch entry
3//! binds `(album_id, epoch, write_tier_pubkey)` under the album's admin-tier signing key,
4//! plus a local-only flag for whether that epoch's AMK content key has arrived.
5//!
6//! Guardrails that keep the deferral honest:
7//! - The admin signature on every entry is **mandatory** and verified by
8//!   [`admin_chain_verifies`](AlbumAuthority::admin_chain_verifies); a forged or unsigned
9//!   entry makes the whole authority untrusted.
10//! - The epoch ceiling is **data, not honor system**: it is the max attested epoch and
11//!   never regresses across `attest_epoch` calls.
12//! - Minting an epoch sets the write-tier key and (optionally) the AMK presence **together**
13//!   — the design's "AMK epoch bump + write-tier rotation are one commit" atomicity.
14
15use std::collections::{BTreeMap, BTreeSet};
16
17use serde::{Deserialize, Serialize};
18use uuid::Uuid;
19
20use super::AlbumAuthority;
21use crate::cbor;
22use crate::crypto::keys::{AmkVersion, HybridSignature, HybridSigningKey, HybridVerifyingKey};
23
24/// The canonical bytes an admin signs to attest one epoch.
25#[derive(Serialize)]
26struct EpochAttestation {
27    album_id: Uuid,
28    epoch: u32,
29    #[serde(with = "serde_bytes")]
30    write_tier_pub: Vec<u8>,
31}
32
33struct Entry {
34    write_tier_pub: HybridVerifyingKey,
35    admin_sig: HybridSignature,
36    amk_present: bool,
37}
38
39/// The portable, admin-signed epoch ledger: every attested `(epoch, write_tier_pub)` with its
40/// admin signature. `amk_present` is **local-only** state and deliberately is *not* part of this
41/// signed artifact — on reload it is restored from the epochs a device actually holds AMKs for.
42#[derive(Clone, Debug, Serialize, Deserialize)]
43pub struct SignedEpochLedger {
44    /// Album this ledger speaks for.
45    pub album_id: Uuid,
46    /// The admin-tier public key every entry is signed under.
47    pub admin_pub: HybridVerifyingKey,
48    /// The attested epoch ceiling (must equal the max attested epoch).
49    pub ceiling: u32,
50    /// One entry per attested epoch.
51    pub entries: Vec<LedgerEntry>,
52}
53
54/// One epoch's signed attestation within a [`SignedEpochLedger`].
55#[derive(Clone, Debug, Serialize, Deserialize)]
56pub struct LedgerEntry {
57    /// Epoch number (`amk_version`).
58    pub epoch: u32,
59    /// The write-tier public key attested for this epoch.
60    pub write_tier_pub: HybridVerifyingKey,
61    /// The admin signature over `(album_id, epoch, write_tier_pub)`.
62    pub admin_sig: HybridSignature,
63}
64
65/// A reference album authority backed by an admin-signed epoch ledger.
66pub struct ReferenceAuthority {
67    album_id: Uuid,
68    admin_pub: HybridVerifyingKey,
69    ceiling: AmkVersion,
70    entries: BTreeMap<u32, Entry>,
71}
72
73fn attestation_bytes(
74    album_id: Uuid,
75    epoch: AmkVersion,
76    write_tier_pub: &HybridVerifyingKey,
77) -> Vec<u8> {
78    cbor::to_canonical_vec(&EpochAttestation {
79        album_id,
80        epoch: epoch.0,
81        write_tier_pub: write_tier_pub.to_bytes(),
82    })
83    .expect("attestation serializes")
84}
85
86impl ReferenceAuthority {
87    /// An empty authority for `album_id` whose attestations are signed by `admin`.
88    pub fn new(album_id: Uuid, admin_pub: HybridVerifyingKey) -> Self {
89        Self {
90            album_id,
91            admin_pub,
92            ceiling: AmkVersion(0),
93            entries: BTreeMap::new(),
94        }
95    }
96
97    /// Attest an epoch: bind `(album_id, epoch, write_tier_pub)` with an admin signature and
98    /// record whether this epoch's AMK is locally held. Advances the ceiling monotonically.
99    /// The `admin` key's public half must match this authority's `admin_pub`.
100    pub fn attest_epoch(
101        &mut self,
102        admin: &HybridSigningKey,
103        epoch: AmkVersion,
104        write_tier_pub: &HybridVerifyingKey,
105        amk_present: bool,
106    ) {
107        debug_assert_eq!(
108            admin.verifying_key(),
109            self.admin_pub,
110            "attesting admin key must match the authority's admin public key"
111        );
112        let admin_sig = admin.sign(&attestation_bytes(self.album_id, epoch, write_tier_pub));
113        self.entries.insert(
114            epoch.0,
115            Entry {
116                write_tier_pub: write_tier_pub.clone(),
117                admin_sig,
118                amk_present,
119            },
120        );
121        if epoch > self.ceiling {
122            self.ceiling = epoch;
123        }
124    }
125
126    /// Builder-style variant of [`attest_epoch`](Self::attest_epoch).
127    pub fn with_epoch(
128        mut self,
129        admin: &HybridSigningKey,
130        epoch: AmkVersion,
131        write_tier_pub: &HybridVerifyingKey,
132        amk_present: bool,
133    ) -> Self {
134        self.attest_epoch(admin, epoch, write_tier_pub, amk_present);
135        self
136    }
137
138    /// Mark an epoch's AMK content key as now locally held (e.g. an in-flight
139    /// `AlbumKeyDistribution` arrived), flipping a *pending* asset to verifiable.
140    pub fn mark_amk_present(&mut self, epoch: AmkVersion) {
141        if let Some(e) = self.entries.get_mut(&epoch.0) {
142            e.amk_present = true;
143        }
144    }
145
146    /// Export the admin-signed epoch ledger for persistence or transport. The local-only
147    /// AMK-presence flags are excluded — they are not part of the signed history.
148    pub fn to_ledger(&self) -> SignedEpochLedger {
149        SignedEpochLedger {
150            album_id: self.album_id,
151            admin_pub: self.admin_pub.clone(),
152            ceiling: self.ceiling.0,
153            entries: self
154                .entries
155                .iter()
156                .map(|(epoch, e)| LedgerEntry {
157                    epoch: *epoch,
158                    write_tier_pub: e.write_tier_pub.clone(),
159                    admin_sig: e.admin_sig.clone(),
160                })
161                .collect(),
162        }
163    }
164
165    /// Rebuild an authority from a serialized ledger, **re-verifying the entire admin chain**.
166    /// `held_epochs` are the epochs whose AMK content key this device actually holds, restoring
167    /// the local-only `amk_present` state. Returns `None` if the admin chain does not verify (a
168    /// tampered, forged, or rewound ledger).
169    pub fn from_ledger(ledger: &SignedEpochLedger, held_epochs: &BTreeSet<u32>) -> Option<Self> {
170        let entries = ledger
171            .entries
172            .iter()
173            .map(|le| {
174                (
175                    le.epoch,
176                    Entry {
177                        write_tier_pub: le.write_tier_pub.clone(),
178                        admin_sig: le.admin_sig.clone(),
179                        amk_present: held_epochs.contains(&le.epoch),
180                    },
181                )
182            })
183            .collect();
184        let authority = Self {
185            album_id: ledger.album_id,
186            admin_pub: ledger.admin_pub.clone(),
187            ceiling: AmkVersion(ledger.ceiling),
188            entries,
189        };
190        authority.admin_chain_verifies().then_some(authority)
191    }
192}
193
194impl AlbumAuthority for ReferenceAuthority {
195    fn album_id(&self) -> Uuid {
196        self.album_id
197    }
198
199    fn epoch_ceiling(&self) -> AmkVersion {
200        self.ceiling
201    }
202
203    fn write_tier_pubkey(&self, epoch: AmkVersion) -> Option<HybridVerifyingKey> {
204        self.entries.get(&epoch.0).map(|e| e.write_tier_pub.clone())
205    }
206
207    fn has_amk(&self, epoch: AmkVersion) -> bool {
208        self.entries.get(&epoch.0).is_some_and(|e| e.amk_present)
209    }
210
211    fn admin_chain_verifies(&self) -> bool {
212        // Ceiling must equal the highest attested epoch (no fabricated/rewound ceiling)...
213        let max = self.entries.keys().copied().max().unwrap_or(0);
214        if self.ceiling.0 != max {
215            return false;
216        }
217        // ...and every entry's admin signature must verify against admin_pub.
218        self.entries.iter().all(|(epoch, e)| {
219            let bytes = attestation_bytes(self.album_id, AmkVersion(*epoch), &e.write_tier_pub);
220            self.admin_pub.verify(&bytes, &e.admin_sig)
221        })
222    }
223}
224
225#[cfg(test)]
226mod tests;