File: state.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 (416 lines) | stat: -rw-r--r-- 13,385 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
// Copyright (c) 2024 Mozilla Corporation and contributors.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

use std::{
    collections::HashMap,
    path::Path,
    sync::{Arc, Mutex},
};

use mls_rs::{
    client_builder::MlsConfig,
    crypto::{SignaturePublicKey, SignatureSecretKey},
    error::IntoAnyError,
    identity::{Credential, SigningIdentity},
    mls_rules::{CommitOptions, DefaultMlsRules},
    storage_provider::KeyPackageData,
    CipherSuite, Client, ProtocolVersion,
};

use crate::ClientConfig;

use mls_rs_provider_sqlite::{
    connection_strategy::{
        CipheredConnectionStrategy, ConnectionStrategy, FileConnectionStrategy, SqlCipherConfig,
        SqlCipherKey,
    },
    SqLiteDataStorageEngine,
};

use crate::{Identity, PlatformError};

#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct GroupData {
    state_data: Vec<u8>,
    epoch_data: HashMap<u64, Vec<u8>>,
}

#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct PlatformState {
    pub db_path: String,
    pub db_key: [u8; 32],
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Default)]
pub struct TemporaryState {
    pub groups: Arc<Mutex<HashMap<Vec<u8>, GroupData>>>,
    /// signing identity => key data
    pub sigkeys: HashMap<Vec<u8>, SignatureData>,
    pub key_packages: Arc<Mutex<HashMap<Vec<u8>, KeyPackageData>>>,
}

#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct SignatureData {
    #[serde(with = "hex::serde")]
    pub public_key: Vec<u8>,
    pub cs: u16,
    #[serde(with = "hex::serde")]
    pub secret_key: Vec<u8>,
    pub credential: Option<Credential>,
}

impl PlatformState {
    pub fn new(db_path: &str, db_key: &[u8; 32]) -> Result<Self, PlatformError> {
        let state = Self {
            db_path: db_path.to_string(),
            db_key: *db_key,
        };

        // This will create an empty database if it doesn't exist.
        state
            .get_sqlite_engine()?
            .application_data_storage()
            .map_err(|e| (PlatformError::StorageError(e.into_any_error())))?;

        Ok(state)
    }

    pub fn get_signing_identities(&self) -> Result<Vec<Identity>, PlatformError> {
        todo!();
    }

    pub fn client(
        &self,
        myself_identifier: &[u8],
        myself_credential: Option<Credential>,
        version: ProtocolVersion,
        config: &ClientConfig,
    ) -> Result<Client<impl MlsConfig>, PlatformError> {
        let crypto_provider = mls_rs_crypto_nss::NssCryptoProvider::default();

        let engine = self
            .get_sqlite_engine()?
            .with_context(myself_identifier.to_vec());

        let mut myself_sig_data = self
            .get_sig_data(myself_identifier)?
            .ok_or(PlatformError::UnavailableSecret)?;

        let myself_credential = if let Some(cred) = myself_credential {
            myself_sig_data.credential = Some(cred.clone());
            self.store_sigdata(myself_identifier, &myself_sig_data)?;

            cred
        } else if let Some(cred) = myself_sig_data.credential {
            cred
        } else {
            return Err(PlatformError::UndefinedIdentity);
        };

        let myself_signing_identity =
            SigningIdentity::new(myself_credential, myself_sig_data.public_key.into());

        let mut builder = mls_rs::client_builder::ClientBuilder::new_sqlite(engine)
            .map_err(|e| PlatformError::StorageError(e.into_any_error()))?
            .crypto_provider(crypto_provider)
            .identity_provider(mls_rs::identity::basic::BasicIdentityProvider)
            .signing_identity(
                myself_signing_identity,
                myself_sig_data.secret_key.into(),
                myself_sig_data.cs.into(),
            )
            .protocol_version(version);

        if let Some(key_package_lifetime_s) = config.key_package_lifetime_s {
            builder = builder.key_package_lifetime(key_package_lifetime_s);
        }

        let mls_rules = DefaultMlsRules::new().with_commit_options(
            CommitOptions::default().with_allow_external_commit(config.allow_external_commits),
        );

        builder = builder.mls_rules(mls_rules);

        Ok(builder.build())
    }

    pub fn client_default(
        &self,
        myself_identifier: &[u8],
    ) -> Result<Client<impl MlsConfig>, PlatformError> {
        self.client(
            myself_identifier,
            None,
            ProtocolVersion::MLS_10,
            &Default::default(),
        )
    }

    pub fn insert_sigkey(
        &self,
        myself_sigkey: &SignatureSecretKey,
        myself_pubkey: &SignaturePublicKey,
        cs: CipherSuite,
        identifier: &[u8],
    ) -> Result<(), PlatformError> {
        let signature_data = SignatureData {
            public_key: myself_pubkey.to_vec(),
            cs: *cs,
            secret_key: myself_sigkey.to_vec(),
            credential: None,
        };

        self.store_sigdata(identifier, &signature_data)?;

        Ok(())
    }

    fn store_sigdata(&self, identifier: &[u8], data: &SignatureData) -> Result<(), PlatformError> {
        let data = bincode::serialize(&data)?;
        let engine = self.get_sqlite_engine()?;

        let storage = engine
            .application_data_storage()
            .map_err(|e| PlatformError::StorageError(e.into_any_error()))?;

        storage
            .insert(&hex::encode(identifier), &data)
            .map_err(|e| PlatformError::StorageError(e.into_any_error()))?;
        Ok(())
    }

    pub fn get_sig_data(
        &self,
        myself_identifier: &[u8],
    ) -> Result<Option<SignatureData>, PlatformError> {
        // TODO: Not clear if the option is needed here, the underlying function needs it.
        let key = myself_identifier.to_vec();
        let engine = self.get_sqlite_engine()?;
        let storage = engine
            .application_data_storage()
            .map_err(|e| PlatformError::StorageError(e.into_any_error()))?;

        storage
            .get(&hex::encode(key))
            .map_err(|e| PlatformError::StorageError(e.into_any_error()))?
            .map_or_else(
                || Ok(None),
                |data| bincode::deserialize(&data).map(Some).map_err(Into::into),
            )
    }

    pub fn get_sqlite_engine(
        &self,
    ) -> Result<SqLiteDataStorageEngine<impl ConnectionStrategy>, PlatformError> {
        let path = Path::new(&self.db_path);
        let file_conn = FileConnectionStrategy::new(path);

        let cipher_config = SqlCipherConfig::new(SqlCipherKey::RawKey(self.db_key));
        let cipher_conn = CipheredConnectionStrategy::new(file_conn, cipher_config);

        SqLiteDataStorageEngine::new(cipher_conn)
            .map_err(|e| PlatformError::StorageError(e.into_any_error()))
    }

    pub fn delete_group(&self, gid: &[u8], identifier: &[u8]) -> Result<(), PlatformError> {
        let storage = self
            .get_sqlite_engine()?
            .with_context(identifier.to_vec())
            .group_state_storage()
            .map_err(|_| PlatformError::InternalError)?;

        // Delete the group
        storage
            .delete_group(gid)
            .map_err(|_| PlatformError::InternalError)
    }

    pub fn delete(db_path: &str) -> Result<(), PlatformError> {
        let path = Path::new(db_path);

        if path.exists() {
            std::fs::remove_file(path)?;
        }

        Ok(())
    }
}

// Dependencies for implementation of InMemoryState

// use crate::GroupConfig;
// use mls_rs::mls_rs_codec::{MlsDecode, MlsEncode};
// use mls_rs::{GroupStateStorage, KeyPackageStorage};
// use mls_rs_core::group::{EpochRecord, GroupState};
// use std::{collections::hash_map::Entry, convert::Infallible};

// impl InMemoryState {
//     pub fn new() -> Self {
//         Default::default()
//     }

//     pub fn to_bytes(&self) -> Result<Vec<u8>, PlatformError> {
//         bincode::serialize(self).map_err(Into::into)
//     }

//     pub fn from_bytes(bytes: &[u8]) -> Result<Self, PlatformError> {
//         bincode::deserialize(bytes).map_err(Into::into)
//     }

//     pub fn client(
//         &self,
//         myself: SigningIdentity,
//         group_config: Option<GroupConfig>,
//     ) -> Result<Client<impl MlsConfig>, PlatformError> {
//         let crypto_provider = mls_rs_crypto_nss::NssCryptoProvider::default();
//         let myself_sigkey = self.get_sigkey(&myself)?;

//         let mut builder = mls_rs::client_builder::ClientBuilder::new()
//             .key_package_repo(self.clone())
//             .group_state_storage(self.clone())
//             .crypto_provider(crypto_provider)
//             .identity_provider(mls_rs::identity::basic::BasicIdentityProvider)
//             .signing_identity(
//                 myself,
//                 myself_sigkey.secret_key.into(),
//                 myself_sigkey.cs.into(),
//             );

//         if let Some(config) = group_config {
//             builder = builder
//                 .key_package_extensions(config.options)
//                 .protocol_version(config.version);
//         }

//         Ok(builder.build())
//     }

//     pub fn insert_sigkey(
//         &mut self,
//         myself_sigkey: &SignatureSecretKey,
//         myself_pubkey: &SignaturePublicKey,
//         cs: CipherSuite,
//         identifier: Identity,
//     ) -> Result<(), PlatformError> {
//         let signature_data = SignatureData {
//             public_key: myself_pubkey.to_vec(),
//             cs: *cs,
//             secret_key: myself_sigkey.to_vec(),
//             credential: None,
//         };

//         self.sigkeys.insert(identifier, signature_data);
//         // TODO: We could return the value to indicate if the key
//         // existed (see the definition of insert).
//         Ok(())
//     }

//     pub fn get_sigkey(&self, myself: &SigningIdentity) -> Result<SignatureData, PlatformError> {
//         let key = myself.mls_encode_to_vec()?;

//         self.sigkeys
//             .get(&key)
//             .cloned()
//             .ok_or(PlatformError::UnavailableSecret)
//     }
// }

// impl GroupStateStorage for TemporaryState {
//     type Error = mls_rs::mls_rs_codec::Error;

//     fn max_epoch_id(&self, group_id: &[u8]) -> Result<Option<u64>, Self::Error> {
//         let group_locked = self.groups.lock().unwrap();

//         Ok(group_locked
//             .get(group_id)
//             .and_then(|group_data| group_data.epoch_data.keys().max().copied()))
//     }

//     fn state<T>(&self, group_id: &[u8]) -> Result<Option<T>, Self::Error>
//     where
//         T: GroupState + MlsDecode,
//     {
//         self.groups
//             .lock()
//             .unwrap()
//             .get(group_id)
//             .map(|v| T::mls_decode(&mut v.state_data.as_slice()))
//             .transpose()
//             .map_err(Into::into)
//     }

//     fn epoch<T>(&self, group_id: &[u8], epoch_id: u64) -> Result<Option<T>, Self::Error>
//     where
//         T: EpochRecord + MlsEncode + MlsDecode,
//     {
//         self.groups
//             .lock()
//             .unwrap()
//             .get(group_id)
//             .and_then(|group_data| group_data.epoch_data.get(&epoch_id))
//             .map(|v| T::mls_decode(&mut &v[..]))
//             .transpose()
//             .map_err(Into::into)
//     }

//     fn write<ST, ET>(
//         &mut self,
//         state: ST,
//         epoch_inserts: Vec<ET>,
//         epoch_updates: Vec<ET>,
//     ) -> Result<(), Self::Error>
//     where
//         ST: GroupState + MlsEncode + MlsDecode + Send + Sync,
//         ET: EpochRecord + MlsEncode + MlsDecode + Send + Sync,
//     {
//         let state_data = state.mls_encode_to_vec()?;
//         let mut states = self.groups.lock().unwrap();

//         let group_data = match states.entry(state.id()) {
//             Entry::Occupied(entry) => {
//                 let data = entry.into_mut();
//                 data.state_data = state_data;
//                 data
//             }
//             Entry::Vacant(entry) => entry.insert(GroupData {
//                 state_data,
//                 epoch_data: Default::default(),
//             }),
//         };

//         epoch_inserts.into_iter().try_for_each(|e| {
//             group_data.epoch_data.insert(e.id(), e.mls_encode_to_vec()?);
//             Ok::<_, Self::Error>(())
//         })?;

//         epoch_updates.into_iter().try_for_each(|e| {
//             if let Some(data) = group_data.epoch_data.get_mut(&e.id()) {
//                 *data = e.mls_encode_to_vec()?;
//             };

//             Ok::<_, Self::Error>(())
//         })?;

//         Ok(())
//     }
// }

// impl KeyPackageStorage for TemporaryState {
//     type Error = Infallible;

//     fn insert(&mut self, id: Vec<u8>, pkg: KeyPackageData) -> Result<(), Self::Error> {
//         let mut states = self.key_packages.lock().unwrap();
//         states.insert(id, pkg);
//         Ok(())
//     }

//     fn get(&self, id: &[u8]) -> Result<Option<KeyPackageData>, Self::Error> {
//         Ok(self.key_packages.lock().unwrap().get(id).cloned())
//     }

//     fn delete(&mut self, id: &[u8]) -> Result<(), Self::Error> {
//         let mut states = self.key_packages.lock().unwrap();
//         states.remove(id);
//         Ok(())
//     }
// }