x0x 0.15.1

Agent-to-agent gossip network for AI systems — no winners, no losers, just cooperation
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Encrypted CRDT task list deltas for secure group collaboration.
//!
//! This module provides an encryption layer for `TaskListDelta`, allowing secure
//! synchronization of task lists within MLS-encrypted groups. Deltas are encrypted
//! with group keys and authenticated to prevent tampering.

use crate::crdt::TaskListDelta;
use crate::mls::{MlsCipher, MlsError, MlsGroup, MlsKeySchedule, Result as MlsResult};
use serde::{Deserialize, Serialize};

/// Encrypted task list delta for secure group synchronization.
///
/// This wraps a `TaskListDelta` with encryption, allowing task lists to be
/// synchronized securely within MLS groups. Each delta is encrypted with the
/// group's current epoch key and includes authentication via AEAD.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedTaskListDelta {
    /// Group identifier for this encrypted delta.
    group_id: Vec<u8>,
    /// Epoch when this delta was encrypted.
    epoch: u64,
    /// Encrypted delta ciphertext (includes authentication tag).
    ciphertext: Vec<u8>,
    /// Additional authenticated data (group_id + epoch).
    aad: Vec<u8>,
}

impl EncryptedTaskListDelta {
    /// Encrypts a task list delta for a specific group.
    ///
    /// Uses the group's current epoch key to encrypt the delta with ChaCha20-Poly1305 AEAD.
    /// The ciphertext includes an authentication tag to prevent tampering.
    ///
    /// # Arguments
    /// * `delta` - The task list delta to encrypt
    /// * `group` - The MLS group (provides group_id and epoch)
    /// * `cipher` - The MLS cipher with current epoch key
    ///
    /// # Returns
    /// An `EncryptedTaskListDelta` ready for transmission.
    ///
    /// # Errors
    /// Returns `MlsError::EncryptionError` if:
    /// - Delta serialization fails
    /// - Encryption operation fails
    ///
    /// # Security
    /// The group_id and epoch are included in the AAD (Additional Authenticated Data),
    /// binding the ciphertext to a specific group and epoch. This prevents replay attacks
    /// and cross-group confusion.
    pub fn encrypt(delta: &TaskListDelta, group: &MlsGroup, cipher: &MlsCipher) -> MlsResult<Self> {
        let context = group.context();
        let group_id = context.group_id().to_vec();
        let epoch = context.epoch();

        // Serialize the delta
        let plaintext = bincode::serialize(delta)
            .map_err(|e| MlsError::EncryptionError(format!("delta serialization failed: {}", e)))?;

        // Build AAD: "EncryptedDelta" || group_id || epoch
        let mut aad = Vec::new();
        aad.extend_from_slice(b"EncryptedDelta");
        aad.extend_from_slice(&group_id);
        aad.extend_from_slice(&epoch.to_le_bytes());

        // Encrypt with counter 0 (each delta is a single message)
        let ciphertext = cipher.encrypt(&plaintext, &aad, 0)?;

        Ok(Self {
            group_id,
            epoch,
            ciphertext,
            aad,
        })
    }

    /// Decrypts this encrypted delta using the provided cipher.
    ///
    /// Verifies the authentication tag and decrypts the task list delta.
    ///
    /// # Arguments
    /// * `cipher` - The MLS cipher with the appropriate epoch key
    ///
    /// # Returns
    /// The decrypted `TaskListDelta`.
    ///
    /// # Errors
    /// Returns an error if:
    /// - Authentication fails (tampering detected)
    /// - Decryption fails (wrong key or corrupted data)
    /// - Deserialization fails (invalid delta format)
    ///
    /// # Security
    /// Authentication failure indicates either:
    /// - The ciphertext was tampered with
    /// - Wrong epoch key is being used
    /// - The AAD doesn't match (wrong group or epoch)
    pub fn decrypt(&self, cipher: &MlsCipher) -> MlsResult<TaskListDelta> {
        // Decrypt with counter 0
        let plaintext = cipher.decrypt(&self.ciphertext, &self.aad, 0)?;

        // Deserialize the delta
        bincode::deserialize(&plaintext)
            .map_err(|e| MlsError::DecryptionError(format!("delta deserialization failed: {}", e)))
    }

    /// Encrypts a delta using the key schedule derived from a group.
    ///
    /// This is a convenience method that derives the cipher from the group's
    /// key schedule and encrypts the delta.
    ///
    /// # Arguments
    /// * `delta` - The task list delta to encrypt
    /// * `group` - The MLS group
    ///
    /// # Returns
    /// An `EncryptedTaskListDelta` ready for transmission.
    ///
    /// # Errors
    /// Returns `MlsError` if key derivation or encryption fails.
    pub fn encrypt_with_group(delta: &TaskListDelta, group: &MlsGroup) -> MlsResult<Self> {
        let key_schedule = MlsKeySchedule::from_group(group)?;
        let cipher = MlsCipher::new(
            key_schedule.encryption_key().to_vec(),
            key_schedule.base_nonce().to_vec(),
        );
        Self::encrypt(delta, group, &cipher)
    }

    /// Decrypts this delta using the key schedule derived from a group.
    ///
    /// This is a convenience method that derives the cipher from the group's
    /// key schedule and decrypts the delta.
    ///
    /// # Arguments
    /// * `group` - The MLS group (must be at the same epoch as encryption)
    ///
    /// # Returns
    /// The decrypted `TaskListDelta`.
    ///
    /// # Errors
    /// Returns `MlsError` if:
    /// - Epoch mismatch (group is at different epoch)
    /// - Key derivation fails
    /// - Decryption fails
    pub fn decrypt_with_group(&self, group: &MlsGroup) -> MlsResult<TaskListDelta> {
        let context = group.context();

        // Verify epoch matches
        if context.epoch() != self.epoch {
            return Err(MlsError::EpochMismatch {
                current: context.epoch(),
                received: self.epoch,
            });
        }

        // Verify group_id matches
        if context.group_id() != self.group_id {
            return Err(MlsError::MlsOperation(format!(
                "group ID mismatch: expected {:?}, got {:?}",
                context.group_id(),
                self.group_id
            )));
        }

        let key_schedule = MlsKeySchedule::from_group(group)?;
        let cipher = MlsCipher::new(
            key_schedule.encryption_key().to_vec(),
            key_schedule.base_nonce().to_vec(),
        );
        self.decrypt(&cipher)
    }

    /// Gets the group ID for this encrypted delta.
    #[must_use]
    pub fn group_id(&self) -> &[u8] {
        &self.group_id
    }

    /// Gets the epoch when this delta was encrypted.
    #[must_use]
    pub fn epoch(&self) -> u64 {
        self.epoch
    }

    /// Gets the ciphertext (including authentication tag).
    #[must_use]
    pub fn ciphertext(&self) -> &[u8] {
        &self.ciphertext
    }

    /// Gets the additional authenticated data.
    #[must_use]
    pub fn aad(&self) -> &[u8] {
        &self.aad
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crdt::{TaskId, TaskItem, TaskMetadata};
    use crate::identity::Identity;
    use crate::mls::MlsGroup;
    use saorsa_gossip_types::PeerId;

    async fn create_test_group() -> (MlsGroup, Vec<u8>) {
        let identity = Identity::generate().expect("identity generation failed");
        let agent_id = identity.agent_id();
        let group_id = b"test-encryption-group".to_vec();
        let group = MlsGroup::new(group_id.clone(), agent_id)
            .await
            .expect("group creation failed");
        (group, group_id)
    }

    fn create_test_delta() -> TaskListDelta {
        let mut delta = TaskListDelta::new(1);

        // Add a task
        let identity = Identity::generate().expect("identity generation failed");
        let agent_id = identity.agent_id();
        let timestamp = 1000;
        let task_id = TaskId::new("Test task", &agent_id, timestamp);

        let metadata = TaskMetadata {
            title: "Test task".to_string(),
            description: "Test description".to_string(),
            priority: 128,
            created_by: agent_id,
            owner: None,
            created_at: timestamp,
            tags: vec![],
        };

        let peer_id = PeerId::new(*agent_id.as_bytes());
        let task = TaskItem::new(task_id, metadata, peer_id);
        let tag = (peer_id, 1);
        delta.added_tasks.insert(task_id, (task, tag));

        delta
    }

    #[tokio::test]
    async fn test_encrypt_decrypt_roundtrip() {
        let (group, _group_id) = create_test_group().await;
        let delta = create_test_delta();

        // Encrypt
        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        assert_eq!(encrypted.group_id(), group.context().group_id());
        assert_eq!(encrypted.epoch(), group.current_epoch());
        assert!(!encrypted.ciphertext().is_empty());

        // Decrypt
        let decrypted = encrypted
            .decrypt_with_group(&group)
            .expect("decryption failed");

        // Verify delta content matches
        assert_eq!(decrypted.version, delta.version);
        assert_eq!(decrypted.added_tasks.len(), delta.added_tasks.len());
    }

    #[tokio::test]
    async fn test_encrypted_delta_includes_group_metadata() {
        let (group, group_id) = create_test_group().await;
        let delta = create_test_delta();

        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        assert_eq!(encrypted.group_id(), &group_id);
        assert_eq!(encrypted.epoch(), 0);
    }

    #[tokio::test]
    async fn test_decryption_fails_with_wrong_epoch() {
        let (mut group, _) = create_test_group().await;
        let delta = create_test_delta();

        // Encrypt at epoch 0
        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        // Simulate epoch change
        let commit = group.commit().expect("commit failed");
        group.apply_commit(&commit).expect("apply failed");

        // Try to decrypt with new epoch
        let result = encrypted.decrypt_with_group(&group);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            MlsError::EpochMismatch { .. }
        ));
    }

    #[tokio::test]
    async fn test_decryption_fails_with_wrong_group() {
        let identity1 = Identity::generate().expect("identity generation failed");
        let agent_id1 = identity1.agent_id();
        let group_id1 = b"test-group-1".to_vec();
        let group1 = MlsGroup::new(group_id1, agent_id1)
            .await
            .expect("group creation failed");

        let identity2 = Identity::generate().expect("identity generation failed");
        let agent_id2 = identity2.agent_id();
        let group_id2 = b"test-group-2".to_vec(); // Different group ID
        let group2 = MlsGroup::new(group_id2, agent_id2)
            .await
            .expect("group creation failed");

        let delta = create_test_delta();

        // Encrypt with group1
        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group1).expect("encryption failed");

        // Try to decrypt with group2 (different group_id)
        let result = encrypted.decrypt_with_group(&group2);
        assert!(result.is_err());
        // Should be a group ID mismatch error
        match result.unwrap_err() {
            MlsError::MlsOperation(msg) => assert!(msg.contains("group ID mismatch")),
            _ => panic!("Expected MlsOperation error for group ID mismatch"),
        }
    }

    #[tokio::test]
    async fn test_authentication_prevents_tampering() {
        let (group, _) = create_test_group().await;
        let delta = create_test_delta();

        let mut encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        // Tamper with ciphertext
        encrypted.ciphertext[0] ^= 1;

        // Decryption should fail due to authentication failure
        let result = encrypted.decrypt_with_group(&group);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), MlsError::DecryptionError(_)));
    }

    #[tokio::test]
    async fn test_different_epochs_produce_different_ciphertexts() {
        let (mut group, _) = create_test_group().await;
        let delta = create_test_delta();

        // Encrypt at epoch 0
        let encrypted1 =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        // Advance epoch
        let commit = group.commit().expect("commit failed");
        group.apply_commit(&commit).expect("apply failed");

        // Encrypt same delta at epoch 1
        let encrypted2 =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        // Ciphertexts should be different
        assert_ne!(encrypted1.ciphertext(), encrypted2.ciphertext());
        assert_ne!(encrypted1.epoch(), encrypted2.epoch());
    }

    #[tokio::test]
    async fn test_empty_delta_encryption() {
        let (group, _) = create_test_group().await;
        let delta = TaskListDelta::new(1); // Empty delta

        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        let decrypted = encrypted
            .decrypt_with_group(&group)
            .expect("decryption failed");

        assert_eq!(decrypted.version, delta.version);
        assert!(decrypted.added_tasks.is_empty());
    }

    #[tokio::test]
    async fn test_large_delta_encryption() {
        let (group, _) = create_test_group().await;
        let mut delta = TaskListDelta::new(1);

        let identity = Identity::generate().expect("identity generation failed");
        let agent_id = identity.agent_id();
        let peer_id = PeerId::new(*agent_id.as_bytes());

        // Add many tasks
        for i in 0..100 {
            let task_id = TaskId::new(&format!("Task {}", i), &agent_id, 1000 + i);

            let metadata = TaskMetadata {
                title: format!("Task {}", i),
                description: format!("Description {}", i),
                priority: 128,
                created_by: agent_id,
                owner: None,
                created_at: 1000 + i,
                tags: vec![],
            };

            let task = TaskItem::new(task_id, metadata, peer_id);
            let tag = (peer_id, i);
            delta.added_tasks.insert(task_id, (task, tag));
        }

        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        let decrypted = encrypted
            .decrypt_with_group(&group)
            .expect("decryption failed");

        assert_eq!(decrypted.added_tasks.len(), 100);
    }

    #[tokio::test]
    async fn test_encrypted_delta_serialization() {
        let (group, _) = create_test_group().await;
        let delta = create_test_delta();

        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        // Serialize and deserialize (using bincode)
        let serialized = bincode::serialize(&encrypted).expect("serialization failed");
        let deserialized: EncryptedTaskListDelta =
            bincode::deserialize(&serialized).expect("deserialization failed");

        assert_eq!(deserialized.group_id(), encrypted.group_id());
        assert_eq!(deserialized.epoch(), encrypted.epoch());
        assert_eq!(deserialized.ciphertext(), encrypted.ciphertext());
    }

    #[tokio::test]
    async fn test_aad_includes_group_and_epoch() {
        let (group, _) = create_test_group().await;
        let delta = create_test_delta();

        let encrypted =
            EncryptedTaskListDelta::encrypt_with_group(&delta, &group).expect("encryption failed");

        let aad = encrypted.aad();

        // AAD should start with "EncryptedDelta"
        assert!(aad.starts_with(b"EncryptedDelta"));

        // AAD should be longer than just the prefix (includes group_id and epoch)
        assert!(aad.len() > b"EncryptedDelta".len());
    }
}