File: lib.rs

package info (click to toggle)
firefox 148.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,719,656 kB
  • sloc: cpp: 7,618,171; javascript: 6,701,506; ansic: 3,781,787; python: 1,418,364; xml: 638,647; asm: 438,962; java: 186,285; sh: 62,885; makefile: 19,010; objc: 13,092; perl: 12,763; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (1193 lines) | stat: -rw-r--r-- 37,405 bytes parent folder | download | duplicates (19)
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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
// Copyright (c) 2024 Mozilla Corporation and contributors.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

mod state;

use mls_rs::error::{AnyError, IntoAnyError};
use mls_rs::group::proposal::{CustomProposal, ProposalType};
use mls_rs::group::{Capabilities, CommitEffect, ExportedTree, ReceivedMessage};
use mls_rs::identity::SigningIdentity;
use mls_rs::mls_rs_codec::{MlsDecode, MlsEncode};
use mls_rs::{CipherSuiteProvider, CryptoProvider, Extension, ExtensionList};

use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub use state::{PlatformState, TemporaryState};
use std::fmt;

pub type DefaultCryptoProvider = mls_rs_crypto_nss::NssCryptoProvider;
pub type DefaultIdentityProvider = mls_rs::identity::basic::BasicIdentityProvider;

// Re-export the mls_rs types
pub use mls_rs::CipherSuite;
pub use mls_rs::MlsMessage;
pub use mls_rs::ProtocolVersion;

// Define new types
pub type GroupState = Vec<u8>;

pub type MlsGroupId = Vec<u8>;
pub type MlsGroupIdArg<'a> = &'a [u8];

pub type MlsGroupEpoch = u64;

pub type MlsCredential = Vec<u8>;
pub type MlsCredentialArg<'a> = &'a [u8];

pub type Identity = Vec<u8>;
pub type IdentityArg<'a> = &'a [u8];

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum MessageOrAck {
    Ack(MlsGroupId),
    MlsMessage(MlsMessage),
}

///
/// Errors
///
#[derive(Debug, thiserror::Error)]
pub enum PlatformError {
    #[error("CoreError")]
    CoreError,
    #[error(transparent)]
    LibraryError(#[from] mls_rs::error::MlsError),
    #[error("InternalError")]
    InternalError,
    #[error("IdentityError")]
    IdentityError(AnyError),
    #[error("CryptoError")]
    CryptoError(AnyError),
    #[error("UnsupportedCiphersuite")]
    UnsupportedCiphersuite,
    #[error("UnsupportedGroupConfig")]
    UnsupportedGroupConfig,
    #[error("UnsupportedMessage")]
    UnsupportedMessage,
    #[error("UndefinedIdentity")]
    UndefinedIdentity,
    #[error("StorageError")]
    StorageError(AnyError),
    #[error("UnavailableSecret")]
    UnavailableSecret,
    #[error("MutexError")]
    MutexError,
    #[error("JsonConversionError")]
    JsonConversionError,
    #[error(transparent)]
    CodecError(#[from] mls_rs::mls_rs_codec::Error),
    #[error(transparent)]
    BincodeError(#[from] bincode::Error),
    #[error(transparent)]
    IOError(#[from] std::io::Error),
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GroupIdEpoch {
    pub group_id: MlsGroupId,
    pub group_epoch: MlsGroupEpoch,
}

///
/// Generate or Retrieve a PlatformState.
///
pub fn state_access(name: &str, key: &[u8; 32]) -> Result<PlatformState, PlatformError> {
    PlatformState::new(name, key)
}

///
/// Delete a PlatformState.
///
pub fn state_delete(name: &str) -> Result<(), PlatformError> {
    PlatformState::delete(name)
}

///
/// Delete a specific group in the PlatformState.
///
pub fn state_delete_group(
    state: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<GroupIdEpoch, PlatformError> {
    state.delete_group(gid, myself)?;

    // Return the group id and 0xFF..FF epoch to signal the group is closed
    Ok(GroupIdEpoch {
        group_id: gid.to_vec(),
        group_epoch: 0xFFFFFFFFFFFFFFFF,
    })
}

///
/// Configurations
///

// Possibly temporary, allows to add an option to the config without changing every
// call to client() function
#[derive(Clone, Debug, Default)]
pub struct ClientConfig {
    pub key_package_extensions: Option<ExtensionList>,
    pub leaf_node_extensions: Option<ExtensionList>,
    pub leaf_node_capabilities: Option<Capabilities>,
    pub key_package_lifetime_s: Option<u64>,
    pub allow_external_commits: bool,
}

// Assuming GroupConfig is a struct
#[derive(Debug, Clone)]
pub struct GroupConfig {
    pub ciphersuite: CipherSuite,
    pub version: ProtocolVersion,
    pub options: ExtensionList,
}

impl Default for GroupConfig {
    fn default() -> Self {
        GroupConfig {
            // Set default ciphersuite.
            ciphersuite: CipherSuite::CURVE25519_AES128,
            // Set default protocol version.
            version: ProtocolVersion::MLS_10,
            // Set default options.
            options: ExtensionList::new(),
        }
    }
}

///
/// Generate a credential.
///
pub fn mls_generate_credential_basic(content: &[u8]) -> Result<MlsCredential, PlatformError> {
    let credential =
        mls_rs::identity::basic::BasicCredential::new(content.to_vec()).into_credential();
    let credential_bytes = credential.mls_encode_to_vec()?;
    Ok(credential_bytes)
}

///
/// Generate a Signature Keypair
///
pub fn mls_generate_identity(
    state: &PlatformState,
    cs: CipherSuite,
    // _randomness: Option<Vec<u8>>,
) -> Result<Vec<u8>, PlatformError> {
    let crypto_provider = DefaultCryptoProvider::default();
    let cipher_suite = crypto_provider
        .cipher_suite_provider(cs)
        .ok_or(PlatformError::UnsupportedCiphersuite)?;

    // Generate a signature key pair.
    let (signature_key, signature_pubkey) = cipher_suite
        .signature_key_generate()
        .map_err(|_| PlatformError::UnsupportedCiphersuite)?;

    let cipher_suite_provider = crypto_provider
        .cipher_suite_provider(cs)
        .ok_or(PlatformError::UnsupportedCiphersuite)?;

    let identifier = cipher_suite_provider
        .hash(&signature_pubkey)
        .map_err(|e| PlatformError::CryptoError(e.into_any_error()))?;

    // Store the signature key pair.
    state.insert_sigkey(&signature_key, &signature_pubkey, cs, &identifier)?;

    Ok(identifier)
}

///
/// Generate a KeyPackage.
///
pub fn mls_generate_key_package(
    state: &PlatformState,
    myself: IdentityArg,
    credential: MlsCredentialArg,
    config: &ClientConfig,
    // _randomness: Option<Vec<u8>>,
) -> Result<MlsMessage, PlatformError> {
    // Decode the Credential
    let mut credential_slice: &[u8] = credential;
    let decoded_cred = mls_rs::identity::Credential::mls_decode(&mut credential_slice)?;

    // Create a client for that state
    let client = state.client(myself, Some(decoded_cred), ProtocolVersion::MLS_10, config)?;

    // Generate a KeyPackage from that client_default
    let key_package_extensions = config.key_package_extensions.clone().unwrap_or_default();
    let leaf_node_extensions = config.leaf_node_extensions.clone().unwrap_or_default();

    let key_package =
        client.generate_key_package_message(key_package_extensions, leaf_node_extensions)?;

    // Result
    Ok(key_package)
}

///
/// Get group members.
///

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct ClientIdentifiers {
    pub identity: Identity,
    pub credential: MlsCredential,
    // TODO: identities: Vec<(Identity, Credential, ExtensionList, Capabilities)>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GroupDetails {
    pub group_id: MlsGroupId,
    pub group_epoch: u64,
    pub group_members: Vec<ClientIdentifiers>,
}

// Note: The identity is needed because it is allowed to have multiple
//       identities in a group.
pub fn mls_group_details(
    state: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<GroupDetails, PlatformError> {
    let crypto_provider = DefaultCryptoProvider::default();

    let group = state.client_default(myself)?.load_group(gid)?;
    let epoch = group.current_epoch();

    let cipher_suite_provider = crypto_provider
        .cipher_suite_provider(group.cipher_suite())
        .ok_or(PlatformError::UnsupportedCiphersuite)?;

    // Return Vec<(Identity, Credential)>
    let members = group
        .roster()
        .member_identities_iter()
        .map(|identity| {
            Ok(ClientIdentifiers {
                identity: cipher_suite_provider
                    .hash(&identity.signature_key)
                    .map_err(|e| PlatformError::CryptoError(e.into_any_error()))?,
                credential: identity.credential.mls_encode_to_vec()?,
            })
        })
        .collect::<Result<Vec<_>, PlatformError>>()?;

    let group_details = GroupDetails {
        group_id: gid.to_vec(),
        group_epoch: epoch,
        group_members: members,
    };

    Ok(group_details)
}

///
/// Group management: Create a Group
///

// Note: We internally set the protocol version to avoid issues with compat
pub fn mls_group_create(
    pstate: &mut PlatformState,
    myself: IdentityArg,
    credential: MlsCredentialArg,
    gid: Option<MlsGroupIdArg>,
    group_context_extensions: Option<ExtensionList>,
    config: &ClientConfig,
) -> Result<GroupIdEpoch, PlatformError> {
    // Build the client
    let mut credential_slice: &[u8] = credential;
    let decoded_cred = mls_rs::identity::Credential::mls_decode(&mut credential_slice)?;

    let client = pstate.client(myself, Some(decoded_cred), ProtocolVersion::MLS_10, config)?;

    // Generate a GroupId if none is provided
    let mut group = match gid {
        Some(gid) => client.create_group_with_id(
            gid.to_vec(),
            group_context_extensions.unwrap_or_default().clone(),
            config.leaf_node_extensions.clone().unwrap_or_default(),
        )?,
        None => client.create_group(
            group_context_extensions.unwrap_or_default().clone(),
            config.leaf_node_extensions.clone().unwrap_or_default(),
        )?,
    };

    // The state needs to be returned or stored somewhere
    group.write_to_storage()?;
    let gid = group.group_id().to_vec();
    let epoch = group.current_epoch();

    // Return
    Ok(GroupIdEpoch {
        group_id: gid,
        group_epoch: epoch,
    })
}

///
/// Group management: Adding a user.
///

#[derive(Clone, Debug, PartialEq)]
pub struct MlsCommitOutput {
    pub commit: MlsMessage,
    pub welcome: Vec<MlsMessage>,
    pub group_info: Option<MlsMessage>,
    pub ratchet_tree: Option<Vec<u8>>,
    // pub unused_proposals: Vec<crate::mls_rules::ProposalInfo<Proposal>>, from mls_rs
    pub identity: Option<Identity>,
}

impl Serialize for MlsCommitOutput {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("MlsCommitOutput", 4)?;

        // Handle serialization for `commit`
        let commit_bytes = self
            .commit
            .mls_encode_to_vec()
            .map_err(serde::ser::Error::custom)?;
        state.serialize_field("commit", &commit_bytes)?;

        // Handle serialization for `welcome`. Collect into a Result to handle potential errors.
        let welcome_bytes: Result<Vec<_>, _> = self
            .welcome
            .iter()
            .map(|msg| msg.mls_encode_to_vec().map_err(serde::ser::Error::custom))
            .collect();
        // Unwrap the Result here, after all potential errors have been handled.
        state.serialize_field("welcome", &welcome_bytes?)?;

        // Handle serialization for `group_info`
        let group_info_bytes = match self.group_info.as_ref().map(|gi| gi.mls_encode_to_vec()) {
            Some(Ok(bytes)) => Some(bytes),
            Some(Err(e)) => return Err(serde::ser::Error::custom(e)),
            None => None,
        };
        state.serialize_field("group_info", &group_info_bytes)?;

        // Directly serialize `ratchet_tree` as it is already an Option<Vec<u8>>
        state.serialize_field("ratchet_tree", &self.ratchet_tree)?;

        state.end()
    }
}

impl<'de> Deserialize<'de> for MlsCommitOutput {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct MlsCommitOutputVisitor;

        impl<'de> Visitor<'de> for MlsCommitOutputVisitor {
            type Value = MlsCommitOutput;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct MlsCommitOutput")
            }

            fn visit_map<V>(self, mut map: V) -> Result<MlsCommitOutput, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut commit = None;
                let mut welcome = None;
                let mut group_info = None;
                let mut ratchet_tree = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "commit" => {
                            let value: Vec<u8> = map.next_value()?;
                            commit = Some(
                                MlsMessage::mls_decode(&mut &value[..])
                                    .map_err(de::Error::custom)?,
                            );
                        }
                        "welcome" => {
                            let values: Vec<Vec<u8>> = map.next_value()?;
                            welcome = Some(
                                values
                                    .into_iter()
                                    .map(|v| {
                                        MlsMessage::mls_decode(&mut &v[..])
                                            .map_err(de::Error::custom)
                                    })
                                    .collect::<Result<_, _>>()?,
                            );
                        }
                        "group_info" => {
                            if let Some(value) = map.next_value::<Option<Vec<u8>>>()? {
                                group_info = Some(
                                    MlsMessage::mls_decode(&mut &value[..])
                                        .map_err(de::Error::custom)?,
                                );
                            }
                        }
                        "ratchet_tree" => {
                            ratchet_tree = map.next_value()?;
                        }
                        _ => { /* Ignore unknown fields */ }
                    }
                }

                Ok(MlsCommitOutput {
                    commit: commit.ok_or_else(|| de::Error::missing_field("commit"))?,
                    welcome: welcome.ok_or_else(|| de::Error::missing_field("welcome"))?,
                    group_info,
                    ratchet_tree,
                    identity: None,
                })
            }
        }

        const FIELDS: &[&str] = &["commit", "welcome", "group_info", "ratchet_tree"];
        deserializer.deserialize_struct("MlsCommitOutput", FIELDS, MlsCommitOutputVisitor)
    }
}

pub fn mls_group_add(
    pstate: &mut PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    new_members: Vec<MlsMessage>,
) -> Result<MlsCommitOutput, PlatformError> {
    // Get the group from the state
    let client = pstate.client_default(myself)?;
    let mut group = client.load_group(gid)?;

    let commit_output = new_members
        .into_iter()
        .try_fold(group.commit_builder(), |commit_builder, user| {
            commit_builder.add_member(user)
        })?
        .build()?;

    // We use the default mode which returns only one welcome message
    let welcomes = commit_output.welcome_messages; //.remove(0);

    let commit_output = MlsCommitOutput {
        commit: commit_output.commit_message.clone(),
        welcome: welcomes,
        group_info: commit_output.external_commit_group_info,
        ratchet_tree: None, // TODO: Handle this !
        identity: None,
    };

    // Write the group to the storage
    group.write_to_storage()?;

    Ok(commit_output)
}

pub fn mls_group_propose_add(
    pstate: &mut PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    new_member: MlsMessage,
) -> Result<MlsMessage, PlatformError> {
    let client = pstate.client_default(myself)?;
    let mut group = client.load_group(gid)?;

    let proposal = group.propose_add(new_member, vec![])?;
    group.write_to_storage()?;

    Ok(proposal.clone())
}

// Variant 1: Vec<MlsMessage>
// pub fn mls_group_propose_add(
//     pstate: &mut PlatformState,
//     gid: &MlsGroupId,
//     myself: &Identity,
//     new_members: Vec<MlsMessage>,
// ) -> Result<MlsMessage, PlatformError> {
//     let client = pstate.client_default(myself)?;
//     let mut group = client.load_group(gid)?;

//     let proposals: Result<Vec<_>, _> = new_members
//         .into_iter()
//         .map(|member| group.propose_add(member, vec![]))
//         .collect();
//     let proposals = proposals?;

//     let proposal = proposals.first().unwrap();
//     group.write_to_storage()?;

//     Ok(proposal.clone())
// }

///
/// Group management: Removing a user.
///
pub fn mls_group_remove(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    removed: IdentityArg, // TODO: Make this Vec<Identities>?
) -> Result<MlsCommitOutput, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(gid)?;

    let crypto_provider = DefaultCryptoProvider::default();

    let cipher_suite_provider = crypto_provider
        .cipher_suite_provider(group.cipher_suite())
        .ok_or(PlatformError::UnsupportedCiphersuite)?;

    let removed = group
        .roster()
        .members_iter()
        .find_map(|m| {
            let h = cipher_suite_provider
                .hash(&m.signing_identity.signature_key)
                .ok()?;
            (h == *removed).then_some(m.index)
        })
        .ok_or(PlatformError::UndefinedIdentity)?;
    // Handle separate error message for inability to remove yourself

    let commit = group.commit_builder().remove_member(removed)?.build()?;

    // Write the group to the storage
    group.write_to_storage()?;

    let commit_output = MlsCommitOutput {
        commit: commit.commit_message,
        welcome: commit.welcome_messages,
        group_info: commit.external_commit_group_info,
        ratchet_tree: commit
            .ratchet_tree
            .map(|tree| tree.to_bytes())
            .transpose()?,
        identity: None,
    };

    Ok(commit_output)
}

pub fn mls_group_propose_remove(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    removed: IdentityArg, // TODO: Make this Vec<Identities>?
) -> Result<MlsMessage, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(gid)?;

    let crypto_provider = DefaultCryptoProvider::default();

    let cipher_suite_provider = crypto_provider
        .cipher_suite_provider(group.cipher_suite())
        .ok_or(PlatformError::UnsupportedCiphersuite)?;

    let removed = group
        .roster()
        .members_iter()
        .find_map(|m| {
            let h = cipher_suite_provider
                .hash(&m.signing_identity.signature_key)
                .ok()?;
            (h == *removed).then_some(m.index)
        })
        .ok_or(PlatformError::UndefinedIdentity)?;

    let proposal = group.propose_remove(removed, vec![])?;

    // Remember the proposal
    group.write_to_storage()?;

    Ok(proposal)
}

///
/// Key updates
///

/// TODO: Possibly add a random nonce as an optional parameter.
pub fn mls_group_update(
    pstate: &mut PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    signature_key: Option<&[u8]>,
    credential: Option<MlsCredentialArg>,
    group_context_extensions: Option<ExtensionList>,
    config: &ClientConfig,
) -> Result<MlsCommitOutput, PlatformError> {
    let crypto_provider = DefaultCryptoProvider::default();

    // Propose + Commit
    let decoded_cred = credential
        .as_ref()
        .map(|credential| {
            let mut credential_slice: &[u8] = credential;
            mls_rs::identity::Credential::mls_decode(&mut credential_slice)
        })
        .transpose()?;

    let client = pstate.client(myself, decoded_cred, ProtocolVersion::MLS_10, config)?;
    let mut group = client.load_group(gid)?;

    let cipher_suite_provider = crypto_provider
        .cipher_suite_provider(group.cipher_suite())
        .ok_or(PlatformError::UnsupportedCiphersuite)?;

    let mut commit_builder = group.commit_builder();

    if let Some(group_context_extensions) = group_context_extensions {
        commit_builder = commit_builder.set_group_context_ext(group_context_extensions)?;
    }

    if let Some(leaf_node_extensions) = config.leaf_node_extensions.clone() {
        commit_builder = commit_builder.set_leaf_node_extensions(leaf_node_extensions);
    }

    let identity = if let Some((key, cred)) = signature_key.zip(credential) {
        let signature_secret_key = key.to_vec().into();
        let signature_public_key = cipher_suite_provider
            .signature_key_derive_public(&signature_secret_key)
            .map_err(|e| PlatformError::CryptoError(e.into_any_error()))?;

        let mut credential_slice: &[u8] = cred;
        let decoded_cred = mls_rs::identity::Credential::mls_decode(&mut credential_slice)?;
        let signing_identity = SigningIdentity::new(decoded_cred, signature_public_key);

        // Return the identity
        cipher_suite_provider
            .hash(&signing_identity.signature_key)
            .map_err(|e| PlatformError::CryptoError(e.into_any_error()))?
    } else {
        myself.to_vec().into()
    };

    let commit = commit_builder.build()?;

    group.write_to_storage()?;

    let commit_output = MlsCommitOutput {
        commit: commit.commit_message,
        welcome: commit.welcome_messages,
        group_info: commit.external_commit_group_info,
        ratchet_tree: commit
            .ratchet_tree
            .map(|tree| tree.to_bytes())
            .transpose()?,
        identity: Some(identity),
    };
    // Generate the signature keypair
    // Return the signing Identity
    // Hash the signingIdentity to get the Identifier

    Ok(commit_output)
}

///
/// Process Welcome message.
///

pub fn mls_group_join(
    pstate: &PlatformState,
    myself: IdentityArg,
    welcome: &MlsMessage,
    ratchet_tree: Option<ExportedTree<'static>>,
) -> Result<GroupIdEpoch, PlatformError> {
    let client = pstate.client_default(myself)?;
    let (mut group, _info) = client.join_group(ratchet_tree, welcome)?;
    let gid = group.group_id().to_vec();
    let epoch = group.current_epoch();

    // Store the state
    group.write_to_storage()?;

    // Return the group identifier
    Ok(GroupIdEpoch {
        group_id: gid,
        group_epoch: epoch,
    })
}

///
/// Close a group by removing all members.
///

// TODO: Define a custom proposal instead.
pub fn mls_group_close(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<MlsCommitOutput, PlatformError> {
    // Remove everyone from the group.
    let mut group = pstate.client_default(myself)?.load_group(gid)?;
    let self_index = group.current_member_index();

    let all_but_me = group
        .roster()
        .members_iter()
        .filter_map(|m| (m.index != self_index).then_some(m.index))
        .collect::<Vec<_>>();

    let commit_output = all_but_me
        .into_iter()
        .try_fold(group.commit_builder(), |builder, index| {
            builder.remove_member(index)
        })?
        .build()?;

    let commit_output = MlsCommitOutput {
        commit: commit_output.commit_message.clone(),
        welcome: vec![],
        group_info: commit_output.external_commit_group_info,
        ratchet_tree: None, // TODO: Handle this !
        identity: None,
    };
    // TODO we should delete state when we receive an ACK. but it's not super clear how to
    // determine on receive that this was a "close" commit. Would be easier if we had a custom
    // proposal

    // Write the group to the storage
    group.write_to_storage()?;

    Ok(commit_output)
}

///
/// Receive a message
///

#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum Received {
    None,
    ApplicationMessage(Vec<u8>),
    GroupIdEpoch(GroupIdEpoch),
    CommitOutput(MlsCommitOutput),
}

pub fn mls_receive(
    pstate: &PlatformState,
    myself: IdentityArg,
    message_or_ack: &MessageOrAck,
) -> Result<(Vec<u8>, Received), PlatformError> {
    // Extract the gid from the Message
    let gid = match &message_or_ack {
        MessageOrAck::Ack(gid) => gid,
        MessageOrAck::MlsMessage(message) => match message.group_id() {
            Some(gid) => gid,
            None => return Err(PlatformError::UnsupportedMessage),
        },
    };

    let mut group = pstate.client_default(myself)?.load_group(gid)?;

    let received_message = match &message_or_ack {
        MessageOrAck::Ack(_) => group.apply_pending_commit().map(ReceivedMessage::Commit),
        MessageOrAck::MlsMessage(message) => group.process_incoming_message(message.clone()),
    };

    //
    let result = match received_message? {
        ReceivedMessage::ApplicationMessage(app_data_description) => Ok((
            gid.to_vec(),
            Received::ApplicationMessage(app_data_description.data().to_vec()),
        )),
        ReceivedMessage::Proposal(_proposal) => {
            // TODO: We inconditionally return the commit for the received proposal
            let commit = group.commit(vec![])?;

            group.write_to_storage()?;

            let commit_output = MlsCommitOutput {
                commit: commit.commit_message,
                welcome: commit.welcome_messages,
                group_info: commit.external_commit_group_info,
                ratchet_tree: commit
                    .ratchet_tree
                    .map(|tree| tree.to_bytes())
                    .transpose()?,
                identity: None,
            };
            Ok((gid.to_vec(), Received::CommitOutput(commit_output)))
        }
        ReceivedMessage::Commit(commit) => {
            // Check if the group is active or not after applying the commit
            match commit.effect {
                CommitEffect::Removed { .. } => {
                    // Delete the group from the state of the client
                    pstate.delete_group(gid, myself)?;

                    // Return the group id and 0xFF..FF epoch to signal the group is closed
                    let group_epoch = GroupIdEpoch {
                        group_id: group.group_id().to_vec(),
                        group_epoch: 0xFFFFFFFFFFFFFFFF,
                    };

                    Ok((gid.to_vec(), Received::GroupIdEpoch(group_epoch)))
                }
                _ => {
                    // TODO: Receiving a group_close commit means the sender receiving
                    // is left alone in the group. We should be able delete group automatically.
                    // As of now, the user calling group_close has to delete group manually.

                    // If this is a normal commit, return the affected group and new epoch
                    let group_epoch = GroupIdEpoch {
                        group_id: group.group_id().to_vec(),
                        group_epoch: group.current_epoch(),
                    };

                    Ok((gid.to_vec(), Received::GroupIdEpoch(group_epoch)))
                }
            }
        }
        // TODO: We could make this more user friendly by allowing to
        // pass a Welcome message. KeyPackages should be rejected.
        _ => Err(PlatformError::UnsupportedMessage),
    }?;

    // Write the state to storage
    group.write_to_storage()?;

    Ok(result)
}

pub fn mls_has_pending_proposals(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<bool, PlatformError> {
    let group = pstate.client_default(myself)?.load_group(gid)?;
    let result = group.commit_required();
    Ok(result)
}

pub fn mls_clear_pending_proposals(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<bool, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(gid)?;
    group.clear_proposal_cache();
    group.write_to_storage()?;
    Ok(true)
}

pub fn mls_has_pending_commit(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<bool, PlatformError> {
    let group = pstate.client_default(myself)?.load_group(gid)?;
    let result = group.has_pending_commit();
    Ok(result)
}

pub fn mls_clear_pending_commit(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<bool, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(gid)?;
    group.clear_pending_commit();
    group.write_to_storage()?;
    Ok(true)
}

pub fn mls_apply_pending_commit(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
) -> Result<Received, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(gid)?;

    let received_message = group.apply_pending_commit().map(ReceivedMessage::Commit);

    // Check if the group is active or not after applying the commit
    let result = match received_message? {
        ReceivedMessage::Commit(commit) => {
            // Check if the group is active or not after applying the commit
            match commit.effect {
                CommitEffect::Removed { .. } => {
                    // Delete the group from the state of the client
                    pstate.delete_group(gid, myself)?;

                    // Return the group id and 0xFF..FF epoch to signal the group is closed
                    let group_epoch = GroupIdEpoch {
                        group_id: group.group_id().to_vec(),
                        group_epoch: 0xFFFFFFFFFFFFFFFF,
                    };

                    Ok(Received::GroupIdEpoch(group_epoch))
                }
                _ => {
                    // TODO: Receiving a group_close commit means the sender receiving
                    // is left alone in the group. We should be able delete group automatically.
                    // As of now, the user calling group_close has to delete group manually.

                    // If this is a normal commit, return the affected group and new epoch
                    let group_epoch = GroupIdEpoch {
                        group_id: group.group_id().to_vec(),
                        group_epoch: group.current_epoch(),
                    };

                    Ok(Received::GroupIdEpoch(group_epoch))
                }
            }
        }
        _ => Err(PlatformError::UnsupportedMessage),
    }?;

    // Write the state to storage
    group.write_to_storage()?;

    Ok(result)
}

//
// Encrypt a message.
//

pub fn mls_send(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    message: &[u8],
) -> Result<MlsMessage, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(gid)?;

    let out = group.encrypt_application_message(message, vec![])?;
    group.write_to_storage()?;

    Ok(out)
}

///
/// Propose + Commit a GroupContextExtension
///
pub fn mls_send_group_context_extension(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    new_gce: Vec<Extension>,
) -> Result<mls_rs::MlsMessage, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(&gid)?;

    let commit = group
        .commit_builder()
        .set_group_context_ext(new_gce.into())?
        .build()?;

    Ok(commit.commit_message)
}

///
/// Create and send a custom proposal.
///
pub fn mls_send_custom_proposal(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    proposal_type: ProposalType,
    data: Vec<u8>,
) -> Result<mls_rs::MlsMessage, PlatformError> {
    let mut group = pstate.client_default(myself)?.load_group(&gid)?;
    let custom_proposal = CustomProposal::new(proposal_type, data);
    let proposal = group.propose_custom(custom_proposal, vec![])?;

    Ok(proposal)
}

///
/// Export a group secret.
///

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct ExporterOutput {
    pub group_id: MlsGroupId,
    pub group_epoch: MlsGroupEpoch,
    pub label: Vec<u8>,
    pub context: Vec<u8>,
    pub exporter: Vec<u8>,
}

pub fn mls_derive_exporter(
    pstate: &PlatformState,
    gid: MlsGroupIdArg,
    myself: IdentityArg,
    label: &[u8],
    context: &[u8],
    len: u64,
) -> Result<ExporterOutput, PlatformError> {
    let group = pstate.client_default(myself)?.load_group(gid)?;
    let secret = group
        .export_secret(label, context, len.try_into().unwrap())?
        .to_vec();

    // Construct the output object
    let epoch_and_exporter = ExporterOutput {
        group_id: gid.to_vec(),
        group_epoch: group.current_epoch(),
        label: label.to_vec(),
        context: label.to_vec(),
        exporter: secret,
    };

    Ok(epoch_and_exporter)
}

///
/// Join a group using the external commit mechanism
///

#[derive(Clone, Debug, PartialEq)]
pub struct MlsExternalCommitOutput {
    pub gid: MlsGroupId,
    pub external_commit: MlsMessage,
}

impl Serialize for MlsExternalCommitOutput {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("MlsExternalCommitOutput", 2)?;
        state.serialize_field("gid", &self.gid)?;

        // Handle serialization for `commit`
        let external_commit_bytes = self
            .external_commit
            .mls_encode_to_vec()
            .map_err(serde::ser::Error::custom)?;

        state.serialize_field("external_commit", &external_commit_bytes)?;

        state.end()
    }
}

impl<'de> Deserialize<'de> for MlsExternalCommitOutput {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct MlsExternalCommitOutputVisitor;

        impl<'de> Visitor<'de> for MlsExternalCommitOutputVisitor {
            type Value = MlsExternalCommitOutput;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct MlsExternalCommitOutput")
            }

            fn visit_map<V>(self, mut map: V) -> Result<MlsExternalCommitOutput, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut gid = None;
                let mut external_commit = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "external_commit" => {
                            let value: Vec<u8> = map.next_value()?;
                            external_commit = Some(
                                MlsMessage::mls_decode(&mut &value[..])
                                    .map_err(de::Error::custom)?,
                            );
                        }
                        "gid" => gid = Some(map.next_value()?),
                        _ => { /* Ignore unknown fields */ }
                    }
                }

                Ok(MlsExternalCommitOutput {
                    gid: gid.ok_or_else(|| de::Error::missing_field("gid"))?,
                    external_commit: external_commit
                        .ok_or_else(|| de::Error::missing_field("external_commit"))?,
                })
            }
        }

        const FIELDS: &[&str] = &["gid", "external_commit"];
        deserializer.deserialize_struct(
            "MlsExternalCommitOutput",
            FIELDS,
            MlsExternalCommitOutputVisitor,
        )
    }
}

pub fn mls_group_external_commit(
    pstate: &PlatformState,
    myself: IdentityArg,
    credential: MlsCredentialArg,
    group_info: &MlsMessage,
    ratchet_tree: Option<ExportedTree<'static>>,
) -> Result<MlsExternalCommitOutput, PlatformError> {
    // Clone the credential to avoid mutating the original
    let mut credential_slice: &[u8] = credential;

    // Decode the credential
    let decoded_cred = mls_rs::identity::Credential::mls_decode(&mut credential_slice)?;

    let client = pstate.client(
        myself,
        Some(decoded_cred),
        ProtocolVersion::MLS_10,
        &ClientConfig::default(),
    )?;

    let mut commit_builder = client.external_commit_builder()?;

    if let Some(ratchet_tree) = ratchet_tree {
        commit_builder = commit_builder.with_tree_data(ratchet_tree);
    }

    let (mut group, external_commit) = commit_builder.build(group_info.clone())?;
    let gid = group.group_id().to_vec();

    // Store the state
    group.write_to_storage()?;

    // Encode the output
    let gid_and_message = MlsExternalCommitOutput {
        gid,
        external_commit,
    };

    Ok(gid_and_message)
}

///
/// Utility functions
///

pub fn mls_get_group_id(message_or_ack: &MessageOrAck) -> Result<Vec<u8>, PlatformError> {
    // Extract the gid from the Message
    let gid = match &message_or_ack {
        MessageOrAck::Ack(gid) => gid,
        MessageOrAck::MlsMessage(message) => match message.group_id() {
            Some(gid) => gid,
            None => return Err(PlatformError::UnsupportedMessage),
        },
    };

    Ok(gid.to_vec())
}

pub fn mls_get_group_epoch(message_or_ack: &MessageOrAck) -> Result<u64, PlatformError> {
    let group_epoch: Option<u64> = match &message_or_ack {
        MessageOrAck::MlsMessage(message) => message.epoch(),
        _ => None,
    };

    Ok(group_epoch.expect("Group epoch not found"))
}

// TODO:
// - Is key available for the message ?