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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! Types for MLS operations.
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// Unique identifier for an MLS group.
///
/// Group ids flow from the wire into [`crate::storage::MlsStorage`] as raw
/// `key_id` storage keys, so they are validated at construction: one or more
/// non-empty colon-separated segments (`:` is the namespace separator used by
/// `session:<a>:<b>` and `group:<uuid>` ids), each segment subject to the
/// same storage-key policy as `UserId`/`AppId` (no path-traversal components,
/// control characters, `/`, or `\`), with a total length cap of
/// [`GroupId::MAX_LEN`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct GroupId(String);
impl GroupId {
/// Maximum accepted group id length in bytes.
///
/// Matches the `EncryptedMessage` compact wire format's string-field cap.
pub const MAX_LEN: usize = 4096;
/// Creates a new group ID, rejecting storage-hostile values.
pub fn new(id: impl Into<String>) -> crate::error::Result<Self> {
let id = id.into();
Self::validate(&id)?;
Ok(Self(id))
}
fn validate(id: &str) -> crate::error::Result<()> {
if id.is_empty() {
return Err(crate::MlsError::InvalidGroupId(
"Group ID cannot be empty".to_string(),
));
}
if id.len() > Self::MAX_LEN {
return Err(crate::MlsError::InvalidGroupId(format!(
"Group ID length {} exceeds maximum {}",
id.len(),
Self::MAX_LEN
)));
}
for segment in id.split(':') {
offline_protocol_core::validate_id_chars(segment, "Group ID segment")
.map_err(|e| crate::MlsError::InvalidGroupId(e.to_string()))?;
}
Ok(())
}
/// Returns the group ID as a string slice.
pub fn as_str(&self) -> &str {
&self.0
}
/// Builds the deterministic group ID for a 1:1 session, rejecting
/// storage-hostile user ids (the id becomes a raw storage key).
///
/// Both peers must land on the same string, so the two ids are put in a
/// canonical order. When both are addresses that order is
/// [`Address`](offline_protocol_core::Address) order — the underlying hash
/// bytes — because the bech32 charset is not ASCII-monotonic (value 4
/// renders as `y` 0x79, value 5 as `9` 0x39), so sorting the rendered
/// strings would disagree with every other address comparison in the
/// protocol. Ids that are not both addresses fall back to string order,
/// which is all a nickname id has.
///
/// Either way the result is symmetric in its arguments, which is the
/// property peers actually depend on.
pub fn for_session(user_a: &str, user_b: &str) -> crate::error::Result<Self> {
use offline_protocol_core::Address;
let ordered = match (user_a.parse::<Address>(), user_b.parse::<Address>()) {
(Ok(addr_a), Ok(addr_b)) if addr_b < addr_a => [user_b, user_a],
(Ok(_), Ok(_)) => [user_a, user_b],
_ => {
let mut users = [user_a, user_b];
users.sort();
users
}
};
Self::new(format!("session:{}:{}", ordered[0], ordered[1]))
}
}
impl std::fmt::Display for GroupId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl<'de> Deserialize<'de> for GroupId {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
GroupId::new(s).map_err(serde::de::Error::custom)
}
}
/// Role a user holds within a group.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GroupRole {
/// Group administrator — can invite/remove members and change roles.
Admin,
/// Regular group member (also the fallback for unknown future variants).
#[default]
#[serde(other)]
Member,
}
impl fmt::Display for GroupRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Admin => write!(f, "admin"),
Self::Member => write!(f, "member"),
}
}
}
/// Error returned when parsing a [`GroupRole`] from a string.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("Invalid role '{0}', must be 'admin' or 'member'")]
pub struct ParseGroupRoleError(pub String);
impl FromStr for GroupRole {
type Err = ParseGroupRoleError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"admin" => Ok(Self::Admin),
"member" => Ok(Self::Member),
_ => Err(ParseGroupRoleError(s.to_string())),
}
}
}
/// A bundle containing a key package and metadata for distribution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyPackageBundle {
/// Unique identifier for this key package.
pub package_id: String,
/// User ID this key package belongs to.
pub user_id: String,
/// Serialized MLS KeyPackage bytes.
pub key_package_data: Vec<u8>,
/// Timestamp when the key package was created (milliseconds since epoch).
pub created_at_ms: u64,
/// Timestamp when the key package expires (milliseconds since epoch).
pub expires_at_ms: u64,
/// Whether this key package has been uploaded to a server.
pub synced: bool,
/// Whether this package is reserved for a publication slot.
///
/// An MLS key package's init key is consumed by the first peer who uses it,
/// so a package standing in a published record must not also be handed to a
/// peer over the push path: the second user of it builds a Welcome that can
/// never be processed. Reserved packages are therefore invisible to both
/// entry points that hand packages out —
/// [`MlsManager::take_push_key_package`](crate::MlsManager::take_push_key_package)
/// (the push path) and
/// [`MlsManager::get_or_create_key_package`](crate::MlsManager::get_or_create_key_package)
/// (the peer-less one).
///
/// Additive and defaulted, so packages written before this field existed
/// deserialize as unreserved — which is what they are.
#[serde(default)]
pub reserved_for_publication: bool,
/// The peer this package has been handed to over the push path, if any.
///
/// This is what keeps the push path from advertising one init key to
/// everybody: a package is claimed by the first peer it is pushed to and
/// afterwards only ever re-handed to *that* peer, so a repeat push costs no
/// new key material while two peers never share one. RFC 9420 §16.8 asks
/// for a key package to be rotated as soon as possible after use; the
/// rotation trigger is consumption, which
/// [`MlsManager::key_package_by_id`](crate::MlsManager::key_package_by_id)
/// already reports, and a consumed package's successor is minted on the
/// next push to that peer.
///
/// `None` means unclaimed — either minted outside the push path (the
/// peer-less FFI entry point) or written before this field existed. Those
/// are claimable, so upgrading does not strand the package already in
/// storage.
///
/// Local bookkeeping only: never serialized onto the wire, and never part
/// of the FFI record.
#[serde(default)]
pub assigned_peer: Option<String>,
/// The TLS-serialized OpenMLS hash reference this package's private init
/// key is stored under in the provider, stamped at mint time.
///
/// A cache: deriving the reference from `key_package_data` costs a TLS
/// parse plus a signature validation, and the push path's pool scan checks
/// every stored package's usability on every push — without this it pays
/// that per package per push. Records written before the field existed
/// deserialize as `None` and are backfilled on their first load.
///
/// Local bookkeeping only, like [`Self::assigned_peer`]: never on the
/// wire, never in the FFI record.
#[serde(default)]
pub provider_hash_ref: Option<Vec<u8>>,
}
impl KeyPackageBundle {
/// Creates a new key package bundle.
pub fn new(
package_id: String,
user_id: String,
key_package_data: Vec<u8>,
lifetime_secs: u64,
) -> Self {
let now_ms = chrono::Utc::now().timestamp_millis() as u64;
Self {
package_id,
user_id,
key_package_data,
created_at_ms: now_ms,
expires_at_ms: now_ms + (lifetime_secs * 1000),
synced: false,
reserved_for_publication: false,
assigned_peer: None,
provider_hash_ref: None,
}
}
/// Checks if the key package has expired (local device's own packages only).
///
/// This compares against the local clock and is valid because `created_at_ms`
/// and `expires_at_ms` were set on this same device.
pub fn is_expired(&self) -> bool {
let now_ms = chrono::Utc::now().timestamp_millis() as u64;
now_ms >= self.expires_at_ms
}
/// Whether the package expired more than `grace_secs` ago.
///
/// Expiry and the destruction of the private init key are deliberately two
/// different moments. An expired package is no longer advertised, but a peer
/// holding a copy handed out just before expiry may still Welcome us — and
/// that Welcome is only processable while the init key is in provider
/// storage. The grace window is how long that stays true; past it the key
/// material is destroyed rather than left resident for the life of the
/// install.
pub fn expired_past_grace(&self, grace_secs: u64) -> bool {
let now_ms = chrono::Utc::now().timestamp_millis() as u64;
now_ms
>= self
.expires_at_ms
.saturating_add(grace_secs.saturating_mul(1000))
}
/// Returns the remaining valid lifetime in milliseconds.
///
/// Used when transmitting key packages to peers: the receiver applies
/// this duration relative to their own clock, eliminating cross-device
/// clock skew from expiry calculations.
pub fn remaining_lifetime_ms(&self) -> u64 {
let now_ms = chrono::Utc::now().timestamp_millis() as u64;
self.expires_at_ms.saturating_sub(now_ms)
}
/// Creates a bundle from received transfer data, computing local expiry
/// from the sender-provided remaining lifetime.
pub fn from_transfer(
package_id: String,
user_id: String,
key_package_data: Vec<u8>,
remaining_lifetime_ms: u64,
) -> Self {
let now_ms = chrono::Utc::now().timestamp_millis() as u64;
Self {
package_id,
user_id,
key_package_data,
created_at_ms: now_ms,
expires_at_ms: now_ms.saturating_add(remaining_lifetime_ms),
synced: false,
// A peer's package, never one of our publication slots.
reserved_for_publication: false,
// Nor one of ours to hand out — the push-path assignment is about
// packages this device minted.
assigned_peer: None,
// Provider refs describe our own private material; a peer's
// package has none here.
provider_hash_ref: None,
}
}
}
/// Information about an MLS group.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupInfo {
/// Unique group identifier.
pub group_id: GroupId,
/// Human-readable group name (for multi-party groups).
pub name: Option<String>,
/// List of member user IDs.
pub members: Vec<String>,
/// Count of members in the group.
pub members_count: u32,
/// Current epoch number.
pub epoch: u64,
/// Whether this is a 1:1 session (2-person group).
pub is_session: bool,
/// Timestamp when the group was created.
pub created_at_ms: u64,
/// Timestamp of the last activity.
pub last_activity_ms: u64,
/// How many leaves the roster read *skipped* because they do not carry the
/// address their own signature key derives to.
///
/// Normally zero: the Welcome and commit gates refuse such a leaf before it
/// can enter local group state, so a non-zero count means the state was
/// written behind the SDK's back — a direct write to the install-scoped
/// provider store, or a group joined by a build predating those gates.
///
/// A count, not the identities. The claimed credentials are attacker-chosen
/// strings, and the whole reason [`crate::group::GroupManager::get_group_info`]
/// filters them out is that the roster must not carry an identity nobody
/// proved; handing the same string back through a second field would return
/// it by another door. It is also not what an app should act on: the leaf
/// holds live group secrets and reads everything sent to the group, so the
/// remedy is to abandon the group, not to evict one member of it.
///
/// Additive with `#[serde(default)]` so records written before this field
/// existed still load.
#[serde(default)]
pub unproven_members: u32,
}
/// Type of MLS message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MlsMessageType {
/// Application message (encrypted content).
Application,
/// Welcome message for new group members.
Welcome,
/// Commit message for group state changes.
Commit,
/// Proposal message.
Proposal,
}
impl MlsMessageType {
/// Returns a stable string representation for serialization/FFI.
pub fn as_str(&self) -> &'static str {
match self {
Self::Application => "Application",
Self::Welcome => "Welcome",
Self::Commit => "Commit",
Self::Proposal => "Proposal",
}
}
/// Parses a string into an MlsMessageType, returning None for unknown values.
pub fn from_str_opt(s: &str) -> Option<Self> {
match s {
"Application" => Some(Self::Application),
"Welcome" => Some(Self::Welcome),
"Commit" => Some(Self::Commit),
"Proposal" => Some(Self::Proposal),
_ => None,
}
}
/// Returns a stable single-byte tag for the compact binary wire format.
pub fn as_u8(&self) -> u8 {
match self {
Self::Application => 0,
Self::Welcome => 1,
Self::Commit => 2,
Self::Proposal => 3,
}
}
/// Parses a wire-format tag, returning None for unknown values.
pub fn from_u8(tag: u8) -> Option<Self> {
match tag {
0 => Some(Self::Application),
1 => Some(Self::Welcome),
2 => Some(Self::Commit),
3 => Some(Self::Proposal),
_ => None,
}
}
}
impl std::fmt::Display for MlsMessageType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// An encrypted MLS message ready for transport.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedMessage {
/// The group ID this message belongs to.
pub group_id: GroupId,
/// Type of MLS message.
pub message_type: MlsMessageType,
/// Current epoch when the message was created.
pub epoch: u64,
/// Serialized MLS message bytes.
pub ciphertext: Vec<u8>,
/// Sender's user ID.
pub sender_id: String,
/// Timestamp when the message was created.
pub timestamp_ms: u64,
}
impl EncryptedMessage {
/// Encodes the encrypted message to base64 for transport.
pub fn to_base64(&self) -> Result<String, crate::MlsError> {
let json =
serde_json::to_vec(self).map_err(|e| crate::MlsError::Serialization(e.to_string()))?;
Ok(base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
&json,
))
}
/// Decodes an encrypted message from base64.
pub fn from_base64(encoded: &str) -> Result<Self, crate::MlsError> {
let json = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, encoded)
.map_err(|e| crate::MlsError::Deserialization(e.to_string()))?;
serde_json::from_slice(&json).map_err(|e| crate::MlsError::Deserialization(e.to_string()))
}
/// Maximum allowed length for a string field (group_id, sender_id) in the
/// compact binary wire format. Prevents allocation bombs from crafted payloads.
const MAX_STRING_FIELD_LEN: usize = 4096;
/// Maximum allowed ciphertext length in the compact binary wire format.
const MAX_CIPHERTEXT_LEN: usize = 128 * 1024 * 1024; // 128 MB
/// Serializes to a compact binary format, avoiding base64/JSON overhead.
///
/// JSON renders `ciphertext` as an integer array (~3.7x inflation), which
/// is unacceptable for large payloads such as encrypted file chunks.
///
/// Wire format (all multi-byte integers are little-endian):
/// ```text
/// [group_id_len:4][group_id][sender_len:4][sender_id]
/// [message_type:1][epoch:8][timestamp_ms:8]
/// [ciphertext_len:4][ciphertext]
/// ```
pub fn to_bytes(&self) -> Vec<u8> {
let group_id = self.group_id.as_str().as_bytes();
let sender_id = self.sender_id.as_bytes();
let capacity =
4 + group_id.len() + 4 + sender_id.len() + 1 + 8 + 8 + 4 + self.ciphertext.len();
let mut buf = Vec::with_capacity(capacity);
buf.extend_from_slice(&(group_id.len() as u32).to_le_bytes());
buf.extend_from_slice(group_id);
buf.extend_from_slice(&(sender_id.len() as u32).to_le_bytes());
buf.extend_from_slice(sender_id);
buf.push(self.message_type.as_u8());
buf.extend_from_slice(&self.epoch.to_le_bytes());
buf.extend_from_slice(&self.timestamp_ms.to_le_bytes());
buf.extend_from_slice(&(self.ciphertext.len() as u32).to_le_bytes());
buf.extend_from_slice(&self.ciphertext);
buf
}
/// Deserializes from the compact binary format produced by `to_bytes`.
pub fn from_bytes(data: &[u8]) -> Result<Self, crate::MlsError> {
let err = |msg: String| crate::MlsError::Deserialization(msg);
let mut pos = 0;
let read_u32 = |pos: &mut usize| -> Result<u32, crate::MlsError> {
if *pos + 4 > data.len() {
return Err(err("unexpected end of data reading u32".to_string()));
}
let mut bytes = [0u8; 4];
bytes.copy_from_slice(&data[*pos..*pos + 4]);
let val = u32::from_le_bytes(bytes);
*pos += 4;
Ok(val)
};
let read_u64 = |pos: &mut usize| -> Result<u64, crate::MlsError> {
if *pos + 8 > data.len() {
return Err(err("unexpected end of data reading u64".to_string()));
}
let mut bytes = [0u8; 8];
bytes.copy_from_slice(&data[*pos..*pos + 8]);
let val = u64::from_le_bytes(bytes);
*pos += 8;
Ok(val)
};
let read_bytes = |pos: &mut usize, len: usize| -> Result<Vec<u8>, crate::MlsError> {
if *pos + len > data.len() {
return Err(err("unexpected end of data reading bytes".to_string()));
}
let val = data[*pos..*pos + len].to_vec();
*pos += len;
Ok(val)
};
let group_id_len = read_u32(&mut pos)? as usize;
if group_id_len > Self::MAX_STRING_FIELD_LEN {
return Err(err(format!(
"group_id_len {} exceeds maximum {}",
group_id_len,
Self::MAX_STRING_FIELD_LEN
)));
}
let group_id = String::from_utf8(read_bytes(&mut pos, group_id_len)?)
.map_err(|e| err(format!("invalid group_id UTF-8: {}", e)))?;
let sender_len = read_u32(&mut pos)? as usize;
if sender_len > Self::MAX_STRING_FIELD_LEN {
return Err(err(format!(
"sender_len {} exceeds maximum {}",
sender_len,
Self::MAX_STRING_FIELD_LEN
)));
}
let sender_id = String::from_utf8(read_bytes(&mut pos, sender_len)?)
.map_err(|e| err(format!("invalid sender_id UTF-8: {}", e)))?;
if pos + 1 > data.len() {
return Err(err(
"unexpected end of data reading message_type".to_string()
));
}
let message_type = MlsMessageType::from_u8(data[pos])
.ok_or_else(|| err(format!("unknown message_type tag {}", data[pos])))?;
pos += 1;
let epoch = read_u64(&mut pos)?;
let timestamp_ms = read_u64(&mut pos)?;
let ciphertext_len = read_u32(&mut pos)? as usize;
if ciphertext_len > Self::MAX_CIPHERTEXT_LEN {
return Err(err(format!(
"ciphertext_len {} exceeds maximum {}",
ciphertext_len,
Self::MAX_CIPHERTEXT_LEN
)));
}
let ciphertext = read_bytes(&mut pos, ciphertext_len)?;
Ok(Self {
group_id: GroupId::new(group_id)?,
message_type,
epoch,
ciphertext,
sender_id,
timestamp_ms,
})
}
}
/// A Welcome message for inviting users to a group.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WelcomeMessage {
/// The group ID the user is being invited to.
pub group_id: GroupId,
/// Serialized MLS Welcome message bytes.
pub welcome_data: Vec<u8>,
/// The inviter's user ID.
pub inviter_id: String,
/// Optional group name for display.
pub group_name: Option<String>,
/// Timestamp when the welcome was created.
pub timestamp_ms: u64,
}
impl WelcomeMessage {
/// Encodes the welcome message to base64 for transport.
pub fn to_base64(&self) -> Result<String, crate::MlsError> {
let json =
serde_json::to_vec(self).map_err(|e| crate::MlsError::Serialization(e.to_string()))?;
Ok(base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
&json,
))
}
/// Decodes a welcome message from base64.
pub fn from_base64(encoded: &str) -> Result<Self, crate::MlsError> {
let json = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, encoded)
.map_err(|e| crate::MlsError::Deserialization(e.to_string()))?;
serde_json::from_slice(&json).map_err(|e| crate::MlsError::Deserialization(e.to_string()))
}
}
/// Metadata about an MLS group (stored separately from MLS state).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupMetadata {
/// Human-readable group name.
pub name: Option<String>,
/// Timestamp when the group was created (milliseconds since epoch).
pub created_at_ms: u64,
/// Timestamp of the last activity (milliseconds since epoch).
pub last_activity_ms: u64,
/// Custom application-specific metadata.
#[serde(default)]
pub custom: std::collections::HashMap<String, String>,
/// User ID of the group creator.
#[serde(default)]
pub created_by: Option<String>,
/// Per-member role assignments.
/// Deserialization falls back to migrating legacy `"role:*"` keys from `custom`.
#[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
pub roles: std::collections::HashMap<String, GroupRole>,
}
impl GroupMetadata {
/// Prefix previously used for role entries in the `custom` map (legacy).
pub const LEGACY_ROLE_KEY_PREFIX: &'static str = "role:";
/// Creates new group metadata with the given name and creator.
pub fn new(name: Option<String>) -> Self {
let now_ms = chrono::Utc::now().timestamp_millis() as u64;
Self {
name,
created_at_ms: now_ms,
last_activity_ms: now_ms,
custom: std::collections::HashMap::new(),
created_by: None,
roles: std::collections::HashMap::new(),
}
}
/// Creates new group metadata with a creator.
pub fn new_with_creator(name: Option<String>, creator_id: &str) -> Self {
let mut meta = Self::new(name);
meta.created_by = Some(creator_id.to_string());
meta.set_role(creator_id, GroupRole::Admin);
meta
}
/// Migrates any legacy `"role:*"` keys from the `custom` map into the
/// dedicated `roles` field. Call after deserialization for
/// backwards-compatibility with older group metadata.
pub fn migrate_legacy_roles(&mut self) {
let legacy_keys: Vec<String> = self
.custom
.keys()
.filter(|k| k.starts_with(Self::LEGACY_ROLE_KEY_PREFIX))
.cloned()
.collect();
for key in legacy_keys {
if let Some(uid) = key.strip_prefix(Self::LEGACY_ROLE_KEY_PREFIX) {
if !self.roles.contains_key(uid) {
let role = self
.custom
.get(&key)
.and_then(|v| v.parse().ok())
.unwrap_or_default();
self.roles.insert(uid.to_string(), role);
}
}
self.custom.remove(&key);
}
}
/// Updates the last activity timestamp to now.
pub fn touch(&mut self) {
self.last_activity_ms = chrono::Utc::now().timestamp_millis() as u64;
}
/// Gets the role for a user, defaulting to [`GroupRole::Member`] if not set.
pub fn get_role(&self, user_id: &str) -> GroupRole {
self.roles.get(user_id).copied().unwrap_or_default()
}
/// Sets the role for a user.
pub fn set_role(&mut self, user_id: &str, role: GroupRole) {
self.roles.insert(user_id.to_string(), role);
}
/// Removes role metadata for a user (on removal from group).
pub fn remove_role(&mut self, user_id: &str) {
self.roles.remove(user_id);
}
/// Returns true if any admin role is stored in this metadata.
pub fn has_any_admin(&self) -> bool {
self.roles.values().any(|r| *r == GroupRole::Admin)
}
/// Returns all `user_id -> role` mappings.
pub fn get_all_roles(&self) -> std::collections::HashMap<String, GroupRole> {
self.roles.clone()
}
}
/// Storage key types for organizing MLS data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StorageKeyType {
/// Identity/signature key pair.
Identity,
/// Key packages for receiving Welcome messages.
KeyPackage,
/// MLS group state.
GroupState,
/// Epoch secrets for a group.
EpochSecrets,
/// Credential data.
Credential,
/// Contact's key packages.
ContactKeyPackage,
/// Group metadata (name, timestamps).
GroupMetadata,
/// Pending welcome messages awaiting delivery.
PendingWelcome,
}
impl StorageKeyType {
/// Returns the string representation for storage.
pub fn as_str(&self) -> &'static str {
match self {
Self::Identity => "identity",
Self::KeyPackage => "key_package",
Self::GroupState => "group_state",
Self::EpochSecrets => "epoch_secrets",
Self::Credential => "credential",
Self::ContactKeyPackage => "contact_key_package",
Self::GroupMetadata => "group_metadata",
Self::PendingWelcome => "pending_welcome",
}
}
}
impl std::fmt::Display for StorageKeyType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
use offline_protocol_core::Address;
/// Two addresses whose hash-byte order is the reverse of their rendered
/// string order.
///
/// Hand-constructed rather than searched for, so the disagreement is
/// checkable by eye: the data part's second character encodes the version
/// byte's low three bits (`0b001`) followed by the hash's top two bits, so
/// `hash[0] = 0x00` yields charset value 4 → `y` (0x79) and
/// `hash[0] = 0x40` yields value 5 → `9` (0x39). Byte order puts the
/// `0x00` address first; ASCII order puts it second.
fn disagreeing_addresses() -> (Address, Address) {
let mut low_bytes = [0u8; Address::HASH_LEN];
low_bytes[0] = 0x00;
let mut high_bytes = [0u8; Address::HASH_LEN];
high_bytes[0] = 0x40;
(
Address::from_hash_bytes(low_bytes),
Address::from_hash_bytes(high_bytes),
)
}
#[test]
fn session_id_orders_addresses_by_hash_not_by_string() {
let (low, high) = disagreeing_addresses();
// The premise: the two orders genuinely disagree for this pair.
assert!(low < high, "hash-byte order");
assert!(
low.to_string() > high.to_string(),
"rendered-string order must be the opposite, or this test proves nothing"
);
let expected = format!("session:{}:{}", low, high);
assert_eq!(
GroupId::for_session(&low.to_string(), &high.to_string())
.unwrap()
.as_str(),
expected,
"address slots must follow Address order, not string order"
);
}
#[test]
fn session_id_is_symmetric_for_addresses() {
let (low, high) = disagreeing_addresses();
let (a, b) = (low.to_string(), high.to_string());
assert_eq!(
GroupId::for_session(&a, &b).unwrap(),
GroupId::for_session(&b, &a).unwrap(),
"both peers must derive the same slot regardless of argument order"
);
}
/// A pair that is not two addresses has no hash order to use, so it keeps
/// the string ordering it has always had.
#[test]
fn session_id_falls_back_to_string_order_for_non_addresses() {
assert_eq!(
GroupId::for_session("bob", "alice").unwrap().as_str(),
"session:alice:bob"
);
let (address, _) = disagreeing_addresses();
let mixed = GroupId::for_session("alice", &address.to_string()).unwrap();
let mixed_reversed = GroupId::for_session(&address.to_string(), "alice").unwrap();
assert_eq!(mixed, mixed_reversed, "mixed pairs must stay symmetric");
}
fn sample_encrypted_message() -> EncryptedMessage {
EncryptedMessage {
group_id: GroupId::for_session("alice", "bob").unwrap(),
message_type: MlsMessageType::Application,
epoch: 42,
ciphertext: vec![0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01],
sender_id: "alice".to_string(),
timestamp_ms: 1_700_000_000_123,
}
}
#[test]
fn test_encrypted_message_bytes_roundtrip() {
let msg = sample_encrypted_message();
let bytes = msg.to_bytes();
let decoded = EncryptedMessage::from_bytes(&bytes).unwrap();
assert_eq!(decoded.group_id, msg.group_id);
assert_eq!(decoded.message_type, msg.message_type);
assert_eq!(decoded.epoch, msg.epoch);
assert_eq!(decoded.ciphertext, msg.ciphertext);
assert_eq!(decoded.sender_id, msg.sender_id);
assert_eq!(decoded.timestamp_ms, msg.timestamp_ms);
}
#[test]
fn test_encrypted_message_bytes_roundtrip_empty_ciphertext() {
let mut msg = sample_encrypted_message();
msg.ciphertext = Vec::new();
let decoded = EncryptedMessage::from_bytes(&msg.to_bytes()).unwrap();
assert!(decoded.ciphertext.is_empty());
}
#[test]
fn test_encrypted_message_from_bytes_truncated() {
let bytes = sample_encrypted_message().to_bytes();
// Every strict prefix must fail cleanly, never panic.
for len in 0..bytes.len() {
assert!(
EncryptedMessage::from_bytes(&bytes[..len]).is_err(),
"truncation at {} unexpectedly succeeded",
len
);
}
}
#[test]
fn test_encrypted_message_from_bytes_oversized_group_id_rejected() {
// Claim a group_id length far beyond the cap without supplying data.
let mut bytes = Vec::new();
bytes.extend_from_slice(&(u32::MAX).to_le_bytes());
let err = EncryptedMessage::from_bytes(&bytes).unwrap_err();
assert!(err.to_string().contains("group_id_len"));
}
#[test]
fn test_encrypted_message_from_bytes_oversized_ciphertext_rejected() {
let mut msg = sample_encrypted_message();
msg.ciphertext = vec![0u8; 4];
let mut bytes = msg.to_bytes();
// Overwrite the ciphertext length prefix (last 4 + 4 bytes from the end).
let ct_len_offset = bytes.len() - 4 - 4;
bytes[ct_len_offset..ct_len_offset + 4].copy_from_slice(&(u32::MAX).to_le_bytes());
let err = EncryptedMessage::from_bytes(&bytes).unwrap_err();
assert!(err.to_string().contains("ciphertext_len"));
}
#[test]
fn test_encrypted_message_from_bytes_unknown_message_type_rejected() {
let msg = sample_encrypted_message();
let mut bytes = msg.to_bytes();
let tag_offset = 4 + msg.group_id.as_str().len() + 4 + msg.sender_id.len();
bytes[tag_offset] = 0xFF;
let err = EncryptedMessage::from_bytes(&bytes).unwrap_err();
assert!(err.to_string().contains("message_type"));
}
#[test]
fn test_group_id_accepts_legitimate_formats() {
assert!(GroupId::new("group:0bd6e5f2-3a70-4a4e-9c3f-1c1f2a3b4c5d").is_ok());
assert!(GroupId::new("session:alice:bob").is_ok());
assert!(GroupId::new("plain-segment_1.x@y").is_ok());
}
#[test]
fn test_group_id_rejects_storage_hostile_chars() {
assert!(GroupId::new("").is_err());
assert!(GroupId::new("group/evil").is_err());
assert!(GroupId::new("group\\evil").is_err());
assert!(GroupId::new("group\0evil").is_err());
assert!(GroupId::new("group\nevil").is_err());
assert!(GroupId::new("group\x7Fevil").is_err()); // DEL
assert!(GroupId::new(".").is_err());
assert!(GroupId::new("..").is_err());
// Path traversal hidden inside a segment
assert!(GroupId::new("session:..:bob").is_err());
assert!(GroupId::new("group:../../etc").is_err());
// Empty segments (leading/trailing/doubled colons)
assert!(GroupId::new("session:").is_err());
assert!(GroupId::new(":session").is_err());
assert!(GroupId::new("a::b").is_err());
}
#[test]
fn test_group_id_length_cap() {
assert!(GroupId::new("a".repeat(GroupId::MAX_LEN)).is_ok());
assert!(GroupId::new("a".repeat(GroupId::MAX_LEN + 1)).is_err());
}
#[test]
fn test_group_id_deserialize_rejects_hostile() {
assert!(serde_json::from_str::<GroupId>(r#""evil/path""#).is_err());
assert!(serde_json::from_str::<GroupId>(r#""..""#).is_err());
assert!(serde_json::from_str::<GroupId>(r#""session:alice:bob""#).is_ok());
}
#[test]
fn test_encrypted_message_from_bytes_rejects_hostile_group_id() {
// Hand-craft wire bytes: the typed constructor can no longer produce
// an invalid group id, but a malicious peer can still send one.
let mut bytes = Vec::new();
let hostile = b"evil/../path";
bytes.extend_from_slice(&(hostile.len() as u32).to_le_bytes());
bytes.extend_from_slice(hostile);
let sender = b"alice";
bytes.extend_from_slice(&(sender.len() as u32).to_le_bytes());
bytes.extend_from_slice(sender);
bytes.push(0); // Application
bytes.extend_from_slice(&42u64.to_le_bytes()); // epoch
bytes.extend_from_slice(&1u64.to_le_bytes()); // timestamp_ms
bytes.extend_from_slice(&0u32.to_le_bytes()); // empty ciphertext
let err = EncryptedMessage::from_bytes(&bytes).unwrap_err();
assert!(matches!(err, crate::MlsError::InvalidGroupId(_)));
}
#[test]
fn test_mls_message_type_u8_roundtrip() {
for msg_type in [
MlsMessageType::Application,
MlsMessageType::Welcome,
MlsMessageType::Commit,
MlsMessageType::Proposal,
] {
assert_eq!(MlsMessageType::from_u8(msg_type.as_u8()), Some(msg_type));
}
assert_eq!(MlsMessageType::from_u8(4), None);
}
}