capsule_core/crypto/authority/openmls_authority/identity.rs
1//! A device's MLS participation identity, and the **hybrid identity binding** that ties an MLS
2//! LeafNode to Capsule's device identity layer.
3//!
4//! SSoT: [Cryptography — MLS](https://docs/design/cryptography/mls/) (leaf/identity binding) and
5//! [Keys — Device Directory](https://docs/design/cryptography/keys/#device-directory).
6//!
7//! MLS binds LeafNode signatures to **Ed25519** in the X-Wing suite, so the post-quantum ML-DSA
8//! half of Capsule's [hybrid signature scheme](https://docs/design/cryptography/primitives/#signature-scheme)
9//! lives at the **identity layer**: a device's identity key (its DSK, published in the signed
10//! [device directory](crate::crypto::keys::DeviceDirectory)) signs the device's MLS Ed25519 leaf
11//! key with **both** Ed25519 and ML-DSA. Peers verify both halves before accepting the leaf into a
12//! group — so a leaf whose Ed25519 key is not covered by a valid hybrid identity signature is
13//! rejected, preserving PQ authentication end-to-end while MLS itself stays pure Ed25519.
14//!
15//! The binding rides the LeafNode's `BasicCredential` identity bytes as a canonical-CBOR
16//! [`LeafBinding`]; [`verify_leaf_binding`] is the gate every membership ceremony runs before
17//! admitting a KeyPackage or trusting a joiner.
18
19use openmls::prelude::{
20 BasicCredential, Credential, CredentialType, CredentialWithKey, KeyPackage, KeyPackageBundle,
21};
22use openmls_basic_credential::SignatureKeyPair;
23use serde::{Deserialize, Serialize};
24use uuid::Uuid;
25
26use super::provider::CapsuleMlsProvider;
27use super::{OpenMlsAuthorityError, PINNED_CIPHERSUITE, pinned_capabilities};
28use crate::crypto::keys::directory::{DeviceEntry, DirectoryCore};
29use crate::crypto::keys::{DeviceDirectory, HybridSignature, HybridSigningKey};
30
31/// The signed core of a [`LeafBinding`] — the bytes the device DSK's hybrid signature covers.
32#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33pub(crate) struct LeafBindingCore {
34 /// The account the device belongs to (must equal the device directory's `user_id`).
35 pub user_id: Uuid,
36 /// The device whose DSK signs this binding (looked up in the directory).
37 pub device_id: Uuid,
38 /// The device's MLS **Ed25519** leaf signature public key, as bound into the group.
39 #[serde(with = "serde_bytes")]
40 pub mls_signature_key: Vec<u8>,
41}
42
43impl LeafBindingCore {
44 fn signing_bytes(&self) -> Result<Vec<u8>, OpenMlsAuthorityError> {
45 crate::cbor::to_canonical_vec(self)
46 .map_err(|e| OpenMlsAuthorityError::Binding(format!("encode: {e}")))
47 }
48}
49
50/// The hybrid identity binding carried in an MLS LeafNode's `BasicCredential`: the device's DSK
51/// (Ed25519 + ML-DSA) signature over its MLS Ed25519 leaf key. This is what makes a Capsule leaf
52/// post-quantum-authenticated even though MLS signs leaves with Ed25519 alone.
53#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
54pub(crate) struct LeafBinding {
55 /// The bound facts.
56 pub core: LeafBindingCore,
57 /// The device DSK's hybrid signature over [`LeafBindingCore::signing_bytes`].
58 pub identity_sig: HybridSignature,
59}
60
61impl LeafBinding {
62 /// Build a binding: sign `(user_id, device_id, mls_signature_key)` with the device DSK.
63 fn create(
64 user_id: Uuid,
65 device_id: Uuid,
66 mls_signature_key: Vec<u8>,
67 dsk: &HybridSigningKey,
68 ) -> Result<Self, OpenMlsAuthorityError> {
69 let core = LeafBindingCore {
70 user_id,
71 device_id,
72 mls_signature_key,
73 };
74 let identity_sig = dsk.sign(&core.signing_bytes()?);
75 Ok(Self { core, identity_sig })
76 }
77
78 /// Canonical-CBOR encoding — the bytes placed in the LeafNode's `BasicCredential` identity.
79 fn to_credential_bytes(&self) -> Result<Vec<u8>, OpenMlsAuthorityError> {
80 crate::cbor::to_canonical_vec(self)
81 .map_err(|e| OpenMlsAuthorityError::Binding(format!("encode: {e}")))
82 }
83
84 pub(super) fn from_credential_bytes(bytes: &[u8]) -> Result<Self, OpenMlsAuthorityError> {
85 crate::cbor::from_slice(bytes)
86 .map_err(|e| OpenMlsAuthorityError::Binding(format!("decode: {e}")))
87 }
88}
89
90/// Verify a LeafNode's hybrid identity binding against a user's device directory.
91///
92/// Returns the bound `(user_id, device_id)` on success, or a [`OpenMlsAuthorityError::Binding`] if
93/// **any** of the following fails — every one is a leaf that must not be admitted to the group:
94/// 1. the credential is not a Capsule `BasicCredential` binding;
95/// 2. the bound MLS key is not the LeafNode's actual signature key (transplant / substitution);
96/// 3. the directory speaks for a different user than the binding claims;
97/// 4. the claimed device is not in the directory;
98/// 5. the device DSK's **hybrid** signature (Ed25519 **and** ML-DSA — both halves) does not verify.
99///
100/// `leaf_signature_key` is the LeafNode's own signature public key
101/// (`key_package.leaf_node().signature_key().as_slice()`).
102pub(crate) fn verify_leaf_binding(
103 credential: &Credential,
104 leaf_signature_key: &[u8],
105 directory: &DeviceDirectory,
106) -> Result<(Uuid, Uuid), OpenMlsAuthorityError> {
107 if credential.credential_type() != CredentialType::Basic {
108 return Err(OpenMlsAuthorityError::Binding(
109 "leaf credential is not a Capsule basic-credential binding".into(),
110 ));
111 }
112 let binding = LeafBinding::from_credential_bytes(credential.serialized_content())?;
113
114 // The binding must cover *this* leaf's key, not some other key transplanted in.
115 if binding.core.mls_signature_key != leaf_signature_key {
116 return Err(OpenMlsAuthorityError::Binding(
117 "leaf signature key is not the key covered by the identity binding".into(),
118 ));
119 }
120 if directory.core.user_id != binding.core.user_id {
121 return Err(OpenMlsAuthorityError::Binding(
122 "binding user_id does not match the device directory".into(),
123 ));
124 }
125 let Some(entry) = directory.device(&binding.core.device_id) else {
126 return Err(OpenMlsAuthorityError::Binding(
127 "binding device_id is not present in the device directory".into(),
128 ));
129 };
130 // The load-bearing check: the device DSK's hybrid signature (both Ed25519 and ML-DSA halves,
131 // enforced inside `HybridVerifyingKey::verify`) must cover the MLS leaf key.
132 if !entry
133 .dsk_public
134 .verify(&binding.core.signing_bytes()?, &binding.identity_sig)
135 {
136 return Err(OpenMlsAuthorityError::Binding(
137 "device DSK hybrid signature over the MLS leaf key did not verify".into(),
138 ));
139 }
140 Ok((binding.core.user_id, binding.core.device_id))
141}
142
143/// One device's MLS participation identity: the owned OpenMLS provider (`CapsuleMlsProvider`)
144/// (crypto + rand + serializable storage), the device's **MLS Ed25519 leaf signer**, and the
145/// device's **hybrid DSK identity key** used to attest the leaf binding.
146///
147/// This is the unit that founds an album ([`OpenMlsAuthority::create_album`](super::OpenMlsAuthority::create_album))
148/// or joins one ([`OpenMlsAuthority::join_via_welcome`](super::OpenMlsAuthority::join_via_welcome));
149/// a would-be joiner uses it to publish a [`key_package`](Self::key_package) first.
150pub struct MlsDeviceIdentity {
151 pub(super) user_id: Uuid,
152 pub(super) device_id: Uuid,
153 /// The device identity key (published in the device directory); attests the MLS leaf binding.
154 pub(super) dsk: HybridSigningKey,
155 /// The MLS Ed25519 leaf signature keypair that authors this device's commits.
156 pub(super) mls_signer: SignatureKeyPair,
157 /// The owned crypto/rand/storage provider (its storage is the durable group state).
158 pub(super) provider: CapsuleMlsProvider,
159}
160
161impl MlsDeviceIdentity {
162 /// Create a device identity with a freshly-generated DSK (software Ed25519 + ML-DSA-65).
163 pub fn generate(user_id: Uuid, device_id: Uuid) -> Result<Self, OpenMlsAuthorityError> {
164 Self::with_dsk(user_id, device_id, HybridSigningKey::generate())
165 }
166
167 /// Create a device identity around a caller-supplied DSK — the device identity key that is (or
168 /// will be) published in the user's [`DeviceDirectory`]. The MLS leaf signer is minted fresh
169 /// and stored in the provider so the group can author commits with it.
170 pub fn with_dsk(
171 user_id: Uuid,
172 device_id: Uuid,
173 dsk: HybridSigningKey,
174 ) -> Result<Self, OpenMlsAuthorityError> {
175 let provider = CapsuleMlsProvider::new()?;
176 let mls_signer = SignatureKeyPair::new(PINNED_CIPHERSUITE.signature_algorithm())
177 .map_err(|e| OpenMlsAuthorityError::Signature(format!("{e:?}")))?;
178 Ok(Self {
179 user_id,
180 device_id,
181 dsk,
182 mls_signer,
183 provider,
184 })
185 }
186
187 /// The account this device belongs to.
188 pub fn user_id(&self) -> Uuid {
189 self.user_id
190 }
191
192 /// This device's id.
193 pub fn device_id(&self) -> Uuid {
194 self.device_id
195 }
196
197 /// Persist the MLS leaf signer into the provider storage so the group can load it. Idempotent.
198 pub(super) fn store_signer(&self) -> Result<(), OpenMlsAuthorityError> {
199 self.mls_signer
200 .store(<CapsuleMlsProvider as openmls_traits::OpenMlsProvider>::storage(&self.provider))
201 .map_err(|e| OpenMlsAuthorityError::Signature(format!("store: {e:?}")))
202 }
203
204 /// The MLS [`CredentialWithKey`] for this device — a `BasicCredential` carrying the hybrid
205 /// [`LeafBinding`] over this device's MLS Ed25519 leaf key.
206 pub(super) fn credential_with_key(&self) -> Result<CredentialWithKey, OpenMlsAuthorityError> {
207 let mls_pub = self.mls_signer.to_public_vec();
208 let binding =
209 LeafBinding::create(self.user_id, self.device_id, mls_pub.clone(), &self.dsk)?;
210 let credential = BasicCredential::new(binding.to_credential_bytes()?);
211 Ok(CredentialWithKey {
212 credential: credential.into(),
213 signature_key: mls_pub.into(),
214 })
215 }
216
217 /// Publish a [`KeyPackage`] for this device so an admin can add it to an album. The bundle
218 /// (with its private init/encryption keys) is stored in the provider for later Welcome
219 /// processing; the returned public [`KeyPackage`] is what the admin consumes.
220 pub fn key_package(&self) -> Result<KeyPackage, OpenMlsAuthorityError> {
221 self.store_signer()?;
222 let cwk = self.credential_with_key()?;
223 let bundle: KeyPackageBundle = KeyPackage::builder()
224 .leaf_node_capabilities(pinned_capabilities())
225 .build(PINNED_CIPHERSUITE, &self.provider, &self.mls_signer, cwk)
226 .map_err(|e| OpenMlsAuthorityError::KeyPackage(format!("{e:?}")))?;
227 Ok(bundle.key_package().clone())
228 }
229
230 /// This device's [`DeviceEntry`] (its DSK public half) for inclusion in a directory.
231 pub fn directory_entry(&self, added_at: &str) -> DeviceEntry {
232 DeviceEntry {
233 device_id: self.device_id,
234 dsk_public: self.dsk.verifying_key(),
235 dek_public: None,
236 added_at: added_at.to_string(),
237 revoked_at: None,
238 unknown: Default::default(),
239 }
240 }
241
242 /// A single-device [`DeviceDirectory`] for this device, signed by the user IK `ik` — the trust
243 /// anchor `verify_leaf_binding` (and `verify_asset`) resolve the device's DSK through.
244 pub fn signed_directory(
245 &self,
246 ik: &HybridSigningKey,
247 directory_version: u64,
248 updated_at: &str,
249 ) -> DeviceDirectory {
250 DirectoryCore {
251 user_id: self.user_id,
252 directory_version,
253 updated_at: updated_at.to_string(),
254 devices: vec![self.directory_entry(updated_at)],
255 unknown: Default::default(),
256 }
257 .sign(ik)
258 }
259}