Skip to main content

hide_mls/
lib.rs

1//! Group messaging for HIDE identities, over MLS (RFC 9420).
2//!
3//! Everything HIDE does elsewhere protects objects at rest. This is different:
4//! a live group where members join and leave, and where a message sent today
5//! must stay unreadable to a member removed yesterday and to one who joins
6//! tomorrow. That is a ratchet problem, not a file-format problem, so the
7//! protocol machinery is `mls-rs` and **this crate adds no cryptography**.
8//!
9//! What it does add is the join between an MLS group and a HIDE identity: the
10//! credential carried in the group names a device from an identity log **and
11//! proves it**. The HIDE hybrid signing key of that device signs the MLS
12//! signature public key, so a roster entry cannot claim to be a device it does
13//! not hold the key for. "Who is in this group" and "which devices does this
14//! person trust" are then answered from the same place, and revoking a device
15//! is not silently independent of removing it from a group.
16//!
17//! # Honest limits
18//!
19//! - **`mls-rs` has no third-party security audit**, and neither does HIDE.
20//! - The cipher suite here is **classical X25519**, not post-quantum. MLS's PQ
21//!   ciphersuites are still an IETF draft and no Rust provider implements them
22//!   yet; see [`PQ_STATUS`]. HIDE's own object encryption *is* hybrid PQ, so a
23//!   group message is protected differently from a sealed file. Saying that
24//!   plainly matters more than implying uniform protection.
25//! - Removing a device from an identity does not by itself evict it from every
26//!   group. HIDE checks the link, it does not make eviction automatic: the
27//!   group still has to remove the device with an MLS commit, and
28//!   [`untrusted_members`] is how a caller finds out which ones are due.
29
30use hide_identity::{DeviceId, Membership, device_id};
31use hide_sign::{
32    SIGNATURE_LENGTH, SigningIdentity as HideSigner, VERIFYING_KEY_LENGTH, VerifyingIdentity,
33};
34use mls_rs::client_builder::MlsConfig;
35use mls_rs::group::{ReceivedMessage, Roster, Sender};
36use mls_rs::identity::SigningIdentity;
37use mls_rs::mls_rules::{
38    CommitDirection, CommitOptions, CommitSource, EncryptionOptions, ProposalBundle,
39};
40use mls_rs::{CipherSuite, Client, CryptoProvider, MlsMessage, MlsRules};
41use mls_rs_core::crypto::CipherSuiteProvider;
42use mls_rs_core::error::IntoAnyError;
43use mls_rs_core::extension::ExtensionList;
44use mls_rs_core::identity::IdentityProvider;
45use mls_rs_core::identity::{
46    Credential, CredentialType, CustomCredential, MemberValidationContext,
47};
48use mls_rs_core::time::MlsTime;
49use mls_rs_crypto_rustcrypto::RustCryptoProvider;
50use thiserror::Error;
51
52/// Where post-quantum group messaging actually stands, so a caller reading the
53/// API does not have to guess. Checked against the IETF drafts on 2026-09-07.
54pub const PQ_STATUS: &str = "MLS PQ ciphersuites (draft-ietf-mls-pq-ciphersuites) are an \
55Internet-Draft, not an RFC, and no Rust MLS provider implements them yet. Group messages \
56here use X25519, which is not post-quantum. HIDE's object encryption is hybrid PQ.";
57
58/// The suite used for groups. Classical, deliberately and visibly.
59const SUITE: CipherSuite = CipherSuite::CURVE25519_AES128;
60
61/// Private-use credential type carrying a HIDE device binding. RFC 9420 §17.5
62/// reserves 0xF000..=0xFFFF for private use.
63pub const HIDE_CREDENTIAL: CredentialType = CredentialType::new(0xF01D);
64
65/// Domain separator for the binding signature. Bumped with the layout.
66const BINDING_CONTEXT: &[u8] = b"HIDE/0.7 mls binding";
67
68const DEVICE_ID_LEN: usize = 32;
69const CREDENTIAL_LEN: usize = DEVICE_ID_LEN + VERIFYING_KEY_LENGTH + SIGNATURE_LENGTH;
70
71/// Largest wire message accepted from the network. `mls-rs` is third-party and
72/// unaudited, so nothing arbitrary is handed to its parser: a legitimate
73/// handshake or application message is orders of magnitude below this.
74pub const MAX_MLS_MESSAGE: usize = 1024 * 1024;
75
76#[derive(Debug, Error)]
77pub enum MlsError {
78    #[error("this device is not trusted by the identity")]
79    UntrustedDevice,
80    #[error("the message is larger than {MAX_MLS_MESSAGE} bytes")]
81    MessageTooLarge,
82    #[error("the message came from a device the identity does not trust")]
83    UntrustedSender,
84    #[error("the credential is not a HIDE device binding")]
85    NotADeviceCredential,
86    #[error("the credential's binding signature does not verify")]
87    ForgedCredential,
88    #[error("MLS: {0}")]
89    Protocol(String),
90}
91
92fn protocol<E: core::fmt::Display>(error: E) -> MlsError {
93    MlsError::Protocol(error.to_string())
94}
95
96impl IntoAnyError for MlsError {
97    fn into_dyn_error(self) -> Result<Box<dyn std::error::Error + Send + Sync>, Self> {
98        Ok(Box::new(self))
99    }
100}
101
102/// What the HIDE key signs: the device it speaks for and the MLS key it vouches
103/// for. Both fixed width, so no length prefix is needed.
104fn binding_message(device: &DeviceId, mls_public_key: &[u8]) -> Vec<u8> {
105    let mut out = Vec::with_capacity(DEVICE_ID_LEN + mls_public_key.len());
106    out.extend_from_slice(device);
107    out.extend_from_slice(mls_public_key);
108    out
109}
110
111/// A parsed HIDE credential: `device_id(32) || hide_verifying_key || signature`.
112struct Binding {
113    device: DeviceId,
114    key: VerifyingIdentity,
115    signature: [u8; SIGNATURE_LENGTH],
116}
117
118impl Binding {
119    fn parse(credential: &Credential) -> Result<Self, MlsError> {
120        let custom = credential
121            .as_custom()
122            .filter(|c| c.credential_type() == HIDE_CREDENTIAL)
123            .ok_or(MlsError::NotADeviceCredential)?;
124        let data = custom.data();
125        if data.len() != CREDENTIAL_LEN {
126            return Err(MlsError::NotADeviceCredential);
127        }
128        let device: DeviceId = data[..DEVICE_ID_LEN]
129            .try_into()
130            .map_err(|_| MlsError::NotADeviceCredential)?;
131        let key = VerifyingIdentity::from_bytes(
132            &data[DEVICE_ID_LEN..DEVICE_ID_LEN + VERIFYING_KEY_LENGTH],
133        )
134        .map_err(|_| MlsError::NotADeviceCredential)?;
135        let signature: [u8; SIGNATURE_LENGTH] = data[DEVICE_ID_LEN + VERIFYING_KEY_LENGTH..]
136            .try_into()
137            .map_err(|_| MlsError::NotADeviceCredential)?;
138        // The id must be the hash of the key it travels with, or the two halves
139        // came from different devices.
140        if device_id(&key) != device {
141            return Err(MlsError::ForgedCredential);
142        }
143        Ok(Self {
144            device,
145            key,
146            signature,
147        })
148    }
149
150    /// The signature must cover THIS MLS key: a valid binding lifted from
151    /// another key package is a forgery here.
152    fn verify(&self, mls_public_key: &[u8]) -> Result<(), MlsError> {
153        self.key
154            .verify(
155                BINDING_CONTEXT,
156                &binding_message(&self.device, mls_public_key),
157                &self.signature,
158            )
159            .map_err(|_| MlsError::ForgedCredential)
160    }
161}
162
163/// Validates roster entries against a HIDE identity's membership.
164///
165/// Every member the group admits must present a credential whose binding
166/// signature verifies under a key that is currently trusted by the identity.
167/// MLS calls this on join, on every commit that adds a member, and when
168/// processing an external sender; it is the hook that makes `BasicCredential`'s
169/// self-asserted name into something an attacker cannot simply claim.
170#[derive(Clone, Debug)]
171pub struct HideIdentityProvider {
172    // Shared with every clone MLS makes of the provider, so `update` reaches
173    // the copy inside a long-lived client (spec §15.8).
174    membership: std::sync::Arc<std::sync::RwLock<Membership>>,
175}
176
177impl HideIdentityProvider {
178    pub fn new(membership: Membership) -> Self {
179        Self {
180            membership: std::sync::Arc::new(std::sync::RwLock::new(membership)),
181        }
182    }
183
184    /// Replaces the membership every clone of this provider validates
185    /// against. Call it after replaying a newer identity log, so a revoked
186    /// device is refused at the next commit without rebuilding the client.
187    pub fn update(&self, membership: Membership) {
188        match self.membership.write() {
189            Ok(mut guard) => *guard = membership,
190            Err(poisoned) => *poisoned.into_inner() = membership,
191        }
192    }
193
194    /// The membership currently enforced.
195    pub fn membership(&self) -> Membership {
196        match self.membership.read() {
197            Ok(guard) => guard.clone(),
198            Err(poisoned) => poisoned.into_inner().clone(),
199        }
200    }
201
202    fn validate(&self, signing_identity: &SigningIdentity) -> Result<(), MlsError> {
203        let binding = Binding::parse(&signing_identity.credential)?;
204        binding.verify(signing_identity.signature_key.as_bytes())?;
205        let membership = self.membership();
206        let trusted = membership
207            .get(&binding.device)
208            .ok_or(MlsError::UntrustedDevice)?;
209        // The log's key for this device, not the one in the credential, is the
210        // authority; they must agree or the credential is for a different key
211        // that happens to hash to the same id, which is not possible, or stale.
212        if trusted.key != binding.key {
213            return Err(MlsError::ForgedCredential);
214        }
215        Ok(())
216    }
217
218    /// Whether a signing identity is a device the identity trusts right now.
219    /// Public because the MLS rules below need the same verdict.
220    pub fn is_trusted(&self, signing_identity: &SigningIdentity) -> bool {
221        self.validate(signing_identity).is_ok()
222    }
223}
224
225impl IdentityProvider for HideIdentityProvider {
226    type Error = MlsError;
227
228    fn validate_member(
229        &self,
230        signing_identity: &SigningIdentity,
231        _timestamp: Option<MlsTime>,
232        _context: MemberValidationContext<'_>,
233    ) -> Result<(), Self::Error> {
234        self.validate(signing_identity)
235    }
236
237    fn validate_external_sender(
238        &self,
239        signing_identity: &SigningIdentity,
240        _timestamp: Option<MlsTime>,
241        _extensions: Option<&ExtensionList>,
242    ) -> Result<(), Self::Error> {
243        self.validate(signing_identity)
244    }
245
246    fn identity(
247        &self,
248        signing_identity: &SigningIdentity,
249        _extensions: &ExtensionList,
250    ) -> Result<Vec<u8>, Self::Error> {
251        Ok(Binding::parse(&signing_identity.credential)?
252            .device
253            .to_vec())
254    }
255
256    fn valid_successor(
257        &self,
258        predecessor: &SigningIdentity,
259        successor: &SigningIdentity,
260        _extensions: &ExtensionList,
261    ) -> Result<bool, Self::Error> {
262        // Only the same device may replace itself via external commit, and the
263        // successor must itself pass member validation (spec §13 items 4-6)
264        // rather than relying on the MLS library to have run it.
265        let a = Binding::parse(&predecessor.credential)?;
266        let b = Binding::parse(&successor.credential)?;
267        if a.device != b.device {
268            return Ok(false);
269        }
270        Ok(self.validate(successor).is_ok())
271    }
272
273    fn supported_types(&self) -> Vec<CredentialType> {
274        vec![HIDE_CREDENTIAL]
275    }
276}
277
278/// MLS checks the roster when a member is added, and never again. A device
279/// that HIDE revoked afterwards is still a member MLS is happy to hear from:
280/// it can commit, and it can leave a by-reference proposal in the cache for an
281/// honest client to fold into its next commit (for example a Remove of the
282/// honest device). These rules close that window, using the same membership
283/// the identity provider validates against, so `update` reaches both.
284#[derive(Clone, Debug)]
285pub struct HideMlsRules {
286    membership: HideIdentityProvider,
287}
288
289impl HideMlsRules {
290    pub fn new(membership: HideIdentityProvider) -> Self {
291        Self { membership }
292    }
293
294    /// Whether the member at `index` is a device the identity still trusts.
295    /// A sender that cannot be attributed to a roster member is not trusted:
296    /// HIDE configures no external senders, so there is no honest case for one.
297    fn trusted_member(&self, roster: &Roster<'_>, index: u32) -> bool {
298        roster
299            .member_with_index(index)
300            .map(|member| self.membership.is_trusted(&member.signing_identity))
301            .unwrap_or(false)
302    }
303}
304
305impl MlsRules for HideMlsRules {
306    type Error = MlsError;
307
308    fn filter_proposals(
309        &self,
310        direction: CommitDirection,
311        source: CommitSource,
312        current_roster: &Roster<'_>,
313        _current_context: &mls_rs::group::GroupContext,
314        mut proposals: ProposalBundle,
315    ) -> Result<ProposalBundle, Self::Error> {
316        // The commit's own author first: a revoked device must not be able to
317        // author anything at all.
318        if let CommitSource::ExistingMember(member) = &source
319            && !self.membership.is_trusted(&member.signing_identity)
320        {
321            return Err(MlsError::UntrustedSender);
322        }
323        let mut dropped = false;
324        proposals.retain(|info| {
325            let keep = match info.sender {
326                Sender::Member(index) => self.trusted_member(current_roster, index),
327                _ => false,
328            };
329            dropped |= !keep;
330            Ok::<bool, MlsError>(keep)
331        })?;
332        // Receiving: an untrusted proposal means the group is in a state the
333        // caller must not continue from. Sending: a stale by-reference proposal
334        // is dropped rather than folded in, so one bad proposal cannot deadlock
335        // every later commit.
336        if dropped && matches!(direction, CommitDirection::Receive) {
337            return Err(MlsError::UntrustedSender);
338        }
339        Ok(proposals)
340    }
341
342    fn commit_options(
343        &self,
344        _new_roster: &Roster<'_>,
345        _new_context: &mls_rs::group::GroupContext,
346        _proposals: &ProposalBundle,
347    ) -> Result<CommitOptions, Self::Error> {
348        // An update path always: a commit that removes someone must rekey the
349        // epoch, not merely announce the removal.
350        Ok(CommitOptions::new().with_path_required(true))
351    }
352
353    fn encryption_options(
354        &self,
355        _current_roster: &Roster<'_>,
356        _current_context: &mls_rs::group::GroupContext,
357    ) -> Result<EncryptionOptions, Self::Error> {
358        Ok(EncryptionOptions::default())
359    }
360}
361
362/// Builds the MLS client for one device of a HIDE identity.
363///
364/// The credential carries the device id, the device's HIDE verifying key, and a
365/// HIDE signature over the freshly generated MLS signature key. A group member
366/// therefore cannot present a device it does not hold the signing key for, and
367/// the identity provider checks every roster entry against `membership`.
368pub fn client_for(
369    membership: &Membership,
370    device: &HideSigner,
371) -> Result<Client<impl MlsConfig + use<>>, MlsError> {
372    client_with_provider(HideIdentityProvider::new(membership.clone()), device)
373}
374
375/// As [`client_for`], with a provider the caller keeps a handle to, so it can
376/// push a newer membership into the running client with
377/// [`HideIdentityProvider::update`].
378pub fn client_with_provider(
379    provider_handle: HideIdentityProvider,
380    device: &HideSigner,
381) -> Result<Client<impl MlsConfig + use<>>, MlsError> {
382    let membership = provider_handle.membership();
383    let verifying = device.verifying_key();
384    let id = device_id(&verifying);
385    if !membership.contains(&id) {
386        return Err(MlsError::UntrustedDevice);
387    }
388
389    let crypto = RustCryptoProvider::default();
390    let provider = crypto.cipher_suite_provider(SUITE).ok_or_else(|| {
391        MlsError::Protocol("the cipher suite is unavailable in this build".into())
392    })?;
393    // MLS signs with its own key; HIDE's hybrid signing key authorises the
394    // device in the identity log AND vouches for the MLS key, below.
395    let (secret, public) = provider.signature_key_generate().map_err(protocol)?;
396
397    let signature = device.sign(BINDING_CONTEXT, &binding_message(&id, public.as_bytes()));
398    let mut data = Vec::with_capacity(CREDENTIAL_LEN);
399    data.extend_from_slice(&id);
400    data.extend_from_slice(&verifying.to_bytes());
401    data.extend_from_slice(&signature);
402    let credential = Credential::Custom(CustomCredential::new(HIDE_CREDENTIAL, data));
403    let signing = SigningIdentity::new(credential, public);
404
405    // The rules share the provider (and therefore the same `RwLock`), so a
406    // later `update` narrows what the rules accept and what the provider
407    // validates, together.
408    let rules = HideMlsRules::new(provider_handle.clone());
409    Ok(Client::builder()
410        .identity_provider(provider_handle)
411        .mls_rules(rules)
412        .crypto_provider(crypto)
413        .signing_identity(signing, secret, SUITE)
414        .build())
415}
416
417/// Extracts the HIDE device id from an MLS credential, after checking that the
418/// credential's binding signature covers the MLS key it travels with.
419fn credential_device(signing: &SigningIdentity) -> Result<DeviceId, MlsError> {
420    let binding = Binding::parse(&signing.credential)?;
421    binding.verify(signing.signature_key.as_bytes())?;
422    Ok(binding.device)
423}
424
425/// Checks every member of a group against an identity's current membership.
426///
427/// This is the check that keeps revocation meaningful: a device removed from
428/// the identity is reported here even though MLS itself has no opinion about
429/// HIDE identities.
430pub fn untrusted_members<C: MlsConfig>(
431    group: &mls_rs::Group<C>,
432    membership: &Membership,
433) -> Result<Vec<DeviceId>, MlsError> {
434    let mut stale = Vec::new();
435    for member in group.roster().members_iter() {
436        let device = credential_device(&member.signing_identity)?;
437        if !membership.contains(&device) {
438            stale.push(device);
439        }
440    }
441    Ok(stale)
442}
443
444/// The device id behind a received application message, so a caller can decide
445/// whether it still trusts the sender.
446pub fn sender_device<C: MlsConfig>(
447    group: &mls_rs::Group<C>,
448    message: &ReceivedMessage,
449) -> Result<Option<DeviceId>, MlsError> {
450    let ReceivedMessage::ApplicationMessage(app) = message else {
451        return Ok(None);
452    };
453    let member = group
454        .member_at_index(app.sender_index)
455        .ok_or_else(|| MlsError::Protocol("sender is not in the roster".into()))?;
456    credential_device(&member.signing_identity).map(Some)
457}
458
459/// Rejects an application message whose sender the identity no longer trusts.
460///
461/// MLS guarantees the message came from a group member; it cannot know that the
462/// member's device was revoked in the identity log a minute ago.
463pub fn accept_from_trusted<C: MlsConfig>(
464    group: &mls_rs::Group<C>,
465    message: &ReceivedMessage,
466    membership: &Membership,
467) -> Result<(), MlsError> {
468    match sender_device(group, message)? {
469        Some(device) if !membership.contains(&device) => Err(MlsError::UntrustedSender),
470        _ => Ok(()),
471    }
472}
473
474/// Re-exported so callers need not depend on `mls-rs` directly for the common
475/// path.
476pub use mls_rs::MlsMessage as Message;
477pub use mls_rs::group::ReceivedMessage as Received;
478
479/// Serialises a message for transport.
480pub fn encode_message(message: &MlsMessage) -> Result<Vec<u8>, MlsError> {
481    message.to_bytes().map_err(protocol)
482}
483
484pub fn decode_message(bytes: &[u8]) -> Result<MlsMessage, MlsError> {
485    if bytes.len() > MAX_MLS_MESSAGE {
486        return Err(MlsError::MessageTooLarge);
487    }
488    MlsMessage::from_bytes(bytes).map_err(protocol)
489}