saorsa-mls 0.3.8

Experimental Message Layer Security (MLS)-inspired library for P2P secure group communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// Copyright 2024 Saorsa Labs
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Simplified API for MLS group messaging with QUIC stream integration

use crate::{
    crypto::{random_bytes, SecretBytes},
    group::MlsGroup,
    member::{MemberId, MemberIdentity},
    protocol::{ApplicationMessage, CommitMessage},
    MlsError, Result,
};
use bytes::Bytes;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// Group identifier
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct GroupId(pub Bytes);

impl GroupId {
    /// Generate a new random group ID
    pub fn generate() -> Self {
        Self(Bytes::from(random_bytes(32)))
    }

    /// Create from raw bytes
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        Self(Bytes::from(bytes))
    }
}

/// Commit options for padding and metadata
#[derive(Debug, Clone, Default)]
pub struct CommitOptions {
    /// Padding size for traffic analysis resistance
    pub padding: usize,
}

/// Encrypted ciphertext with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ciphertext {
    /// The encrypted payload
    pub data: Bytes,
    /// Sender's member ID
    pub sender_id: MemberId,
    /// Message sequence number
    pub sequence: u64,
    /// Epoch number
    pub epoch: u64,
    /// Signature over the ciphertext
    #[serde(skip)]
    pub signature: Option<crate::crypto::DebugMlDsaSignature>,
}

/// Identity type for simplified API
pub type Identity = MemberIdentity;

/// Commit type for simplified API
pub type Commit = CommitMessage;

/// Storage for group state persistence
#[derive(Debug)]
struct GroupStorage {
    /// Current epoch number
    epoch: u64,
    /// Transcript hash for epoch
    #[allow(dead_code)]
    transcript_hash: SecretBytes,
    /// Ratchet states per member
    ratchets: HashMap<MemberId, SecretBytes>,
}

/// Group manager for simplified API
#[derive(Debug)]
pub struct GroupManager {
    groups: Arc<RwLock<HashMap<GroupId, Arc<MlsGroup>>>>,
    storage: Arc<RwLock<HashMap<GroupId, GroupStorage>>>,
}

impl Default for GroupManager {
    fn default() -> Self {
        Self::new()
    }
}

impl GroupManager {
    /// Create a new group manager
    pub fn new() -> Self {
        Self {
            groups: Arc::new(RwLock::new(HashMap::new())),
            storage: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Create a new group with initial members
    pub async fn group_new(&self, members: &[Identity]) -> Result<GroupId> {
        self.group_new_with_config(members, crate::GroupConfig::default())
            .await
    }

    /// Create a new group with explicit configuration (including cipher suite)
    pub async fn group_new_with_config(
        &self,
        members: &[Identity],
        config: crate::GroupConfig,
    ) -> Result<GroupId> {
        if members.is_empty() {
            return Err(MlsError::InvalidGroupState(
                "Group must have at least one member".to_string(),
            ));
        }

        let suite = crate::CipherSuite::from_id(config.cipher_suite).ok_or_else(|| {
            MlsError::InvalidGroupState(format!(
                "unsupported cipher suite 0x{:04X}",
                config.cipher_suite.as_u16()
            ))
        })?;

        if let Some(mismatch) = members
            .iter()
            .find(|identity| identity.cipher_suite() != suite)
        {
            return Err(MlsError::InvalidGroupState(format!(
                "member {} does not match group cipher suite",
                mismatch.id
            )));
        }

        let group_id = GroupId::generate();

        // Use first member as creator
        let creator = members[0].clone();
        let mut group = MlsGroup::new(config, creator).await?;

        // Add remaining members
        for member in &members[1..] {
            group.add_member(member).await?;
        }

        // Store group
        let mut groups = self.groups.write();
        groups.insert(group_id.clone(), Arc::new(group));

        // Initialize storage
        let storage = GroupStorage {
            epoch: 0,
            transcript_hash: SecretBytes::from(random_bytes(32)),
            ratchets: HashMap::new(),
        };
        let mut storages = self.storage.write();
        storages.insert(group_id.clone(), storage);

        Ok(group_id)
    }

    /// Add a member to the group
    pub async fn add_member(&self, group_id: &GroupId, id: Identity) -> Result<Commit> {
        // We need to replace the group with a mutable one temporarily
        // First, validate and remove under lock
        let mut group = {
            let mut groups = self.groups.write();
            let existing = groups
                .get(group_id)
                .ok_or_else(|| MlsError::InvalidGroupState("Group not found".to_string()))?;

            if id.cipher_suite() != existing.cipher_suite() {
                return Err(MlsError::InvalidGroupState(
                    "member identity does not match group cipher suite".to_string(),
                ));
            }

            groups
                .remove(group_id)
                .ok_or_else(|| MlsError::InvalidGroupState("group not found".to_string()))?
            // Lock is released here when `groups` goes out of scope
        };

        // Get mutable reference and add member (lock is not held during await)
        let result = {
            let group_mut = Arc::get_mut(&mut group).ok_or_else(|| {
                MlsError::InvalidGroupState("Cannot modify shared group".to_string())
            })?;

            group_mut.add_member(&id).await
        };

        // Put the group back under a new lock
        {
            let mut groups = self.groups.write();
            groups.insert(group_id.clone(), group);
        }

        let _welcome = result?;

        // Update storage with new epoch
        let mut storages = self.storage.write();
        if let Some(storage) = storages.get_mut(group_id) {
            storage.epoch += 1;
            storage
                .ratchets
                .insert(id.id, SecretBytes::from(random_bytes(32)));
        }
        let _epoch = storages.get(group_id).map(|s| s.epoch).unwrap_or(0);

        // Convert welcome to commit
        // In a real implementation, this would contain actual proposals
        Ok(Commit {
            proposals: vec![crate::protocol::ProposalRef::Reference(vec![1, 2, 3])],
            path: None,
        })
    }

    /// Remove a member from the group
    pub async fn remove_member(&self, group_id: &GroupId, id: Identity) -> Result<Commit> {
        // We need to replace the group with a mutable one temporarily
        // First, validate and remove under lock
        let mut group = {
            let mut groups = self.groups.write();
            let existing = groups
                .get(group_id)
                .ok_or_else(|| MlsError::InvalidGroupState("Group not found".to_string()))?;

            if id.cipher_suite() != existing.cipher_suite() {
                return Err(MlsError::InvalidGroupState(
                    "member identity does not match group cipher suite".to_string(),
                ));
            }

            groups
                .remove(group_id)
                .ok_or_else(|| MlsError::InvalidGroupState("group not found".to_string()))?
            // Lock is released here when `groups` goes out of scope
        };

        // Get mutable reference and remove member (lock is not held during await)
        let result = {
            let group_mut = Arc::get_mut(&mut group).ok_or_else(|| {
                MlsError::InvalidGroupState("Cannot modify shared group".to_string())
            })?;

            group_mut.remove_member(&id.id).await
        };

        // Put the group back under a new lock
        {
            let mut groups = self.groups.write();
            groups.insert(group_id.clone(), group);
        }

        result?;

        // Update storage
        let mut storages = self.storage.write();
        if let Some(storage) = storages.get_mut(group_id) {
            storage.epoch += 1;
            storage.ratchets.remove(&id.id);
        }
        let _epoch = storages.get(group_id).map(|s| s.epoch).unwrap_or(0);

        Ok(Commit {
            proposals: vec![crate::protocol::ProposalRef::Reference(vec![4, 5, 6])],
            path: None,
        })
    }

    /// Send an encrypted message to the group
    pub fn send(&self, group_id: &GroupId, app_data: &[u8]) -> Result<Ciphertext> {
        let groups = self.groups.read();
        let group = groups
            .get(group_id)
            .ok_or_else(|| MlsError::InvalidGroupState("Group not found".to_string()))?;

        // Encrypt the message
        let app_msg = group.encrypt_message(app_data)?;

        // Get current state for metadata (not needed since we use message epoch)
        let storages = self.storage.read();
        let _storage = storages
            .get(group_id)
            .ok_or_else(|| MlsError::InvalidGroupState("Storage not found".to_string()))?;

        Ok(Ciphertext {
            data: Bytes::from(app_msg.ciphertext),
            sender_id: app_msg.sender,
            sequence: app_msg.sequence,
            epoch: app_msg.epoch, // Use the actual epoch from the message
            signature: Some(app_msg.signature),
        })
    }

    /// Receive and decrypt a message from the group
    pub fn recv(&self, group_id: &GroupId, ciphertext: &Ciphertext) -> Result<Vec<u8>> {
        let groups = self.groups.read();
        let group = groups
            .get(group_id)
            .ok_or_else(|| MlsError::InvalidGroupState("Group not found".to_string()))?;

        // Reconstruct ApplicationMessage from Ciphertext
        let app_msg = ApplicationMessage {
            epoch: ciphertext.epoch,
            sender: ciphertext.sender_id,
            generation: 0, // Simplified
            sequence: ciphertext.sequence,
            ciphertext: ciphertext.data.to_vec(),
            signature: ciphertext
                .signature
                .clone()
                .ok_or_else(|| MlsError::InvalidMessage("Missing signature".to_string()))?,
        };

        // Decrypt the message
        group.decrypt_message(&app_msg)
    }
}

// Global instance for simplified API
lazy_static::lazy_static! {
    static ref MANAGER: GroupManager = GroupManager::new();
}

/// Create a new group with initial members
///
/// # Arguments
/// * `members` - Initial group members
///
/// # Returns
/// * `GroupId` - The identifier for the created group
pub async fn group_new(members: &[Identity]) -> anyhow::Result<GroupId> {
    MANAGER.group_new(members).await.map_err(Into::into)
}

/// Create a new group with explicit configuration
pub async fn group_new_with_config(
    members: &[Identity],
    config: crate::GroupConfig,
) -> anyhow::Result<GroupId> {
    MANAGER
        .group_new_with_config(members, config)
        .await
        .map_err(Into::into)
}

/// Add a member to an existing group
///
/// # Arguments
/// * `g` - The group identifier
/// * `id` - The identity of the member to add
///
/// # Returns
/// * `Commit` - The commit message for the add operation
pub async fn add_member(g: &GroupId, id: Identity) -> anyhow::Result<Commit> {
    MANAGER.add_member(g, id).await.map_err(Into::into)
}

/// Remove a member from a group
///
/// # Arguments
/// * `g` - The group identifier
/// * `id` - The identity of the member to remove
///
/// # Returns
/// * `Commit` - The commit message for the remove operation
pub async fn remove_member(g: &GroupId, id: Identity) -> anyhow::Result<Commit> {
    MANAGER.remove_member(g, id).await.map_err(Into::into)
}

/// Send an encrypted message to the group
///
/// # Arguments
/// * `g` - The group identifier
/// * `app` - The application data to encrypt
///
/// # Returns
/// * `Ciphertext` - The encrypted message
pub fn send(g: &GroupId, app: &[u8]) -> anyhow::Result<Ciphertext> {
    MANAGER.send(g, app).map_err(Into::into)
}

/// Receive and decrypt a message from the group
///
/// # Arguments
/// * `g` - The group identifier
/// * `ct` - The encrypted ciphertext
///
/// # Returns
/// * `Vec<u8>` - The decrypted application data
pub fn recv(g: &GroupId, ct: &Ciphertext) -> anyhow::Result<Vec<u8>> {
    MANAGER.recv(g, ct).map_err(Into::into)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_group_creation() {
        let member1 = MemberIdentity::generate(MemberId::generate()).unwrap();
        let member2 = MemberIdentity::generate(MemberId::generate()).unwrap();

        let members = vec![member1, member2];
        let group_id = group_new(&members).await.unwrap();

        assert!(!group_id.0.is_empty());
    }

    #[tokio::test]
    async fn test_add_remove_member() {
        let member1 = MemberIdentity::generate(MemberId::generate()).unwrap();
        let member2 = MemberIdentity::generate(MemberId::generate()).unwrap();
        let member3 = MemberIdentity::generate(MemberId::generate()).unwrap();

        let members = vec![member1.clone(), member2];
        let group_id = group_new(&members).await.unwrap();

        // Add member
        let commit = add_member(&group_id, member3.clone()).await.unwrap();
        assert!(!commit.proposals.is_empty() || commit.path.is_some());

        // Remove member
        let commit = remove_member(&group_id, member3).await.unwrap();
        assert!(!commit.proposals.is_empty() || commit.path.is_some());
    }

    #[tokio::test]
    async fn test_send_recv() {
        let member1 = MemberIdentity::generate(MemberId::generate()).unwrap();
        let member2 = MemberIdentity::generate(MemberId::generate()).unwrap();

        let members = vec![member1, member2];
        let group_id = group_new(&members).await.unwrap();

        let message = b"Hello, MLS group!";
        let ciphertext = send(&group_id, message).unwrap();

        let decrypted = recv(&group_id, &ciphertext).unwrap();
        assert_eq!(decrypted, message);
    }
}