| 1 |
// Copyright (c) 2024 Mozilla Corporation and contributors. |
| 2 |
// SPDX-License-Identifier: (Apache-2.0 OR MIT) |
| 3 |
|
| 4 |
use std::{ |
| 5 |
collections::HashMap, |
| 6 |
path::Path, |
| 7 |
sync::{Arc, Mutex}, |
| 8 |
}; |
| 9 |
|
| 10 |
use mls_rs::{ |
| 11 |
client_builder::MlsConfig, |
| 12 |
crypto::{SignaturePublicKey, SignatureSecretKey}, |
| 13 |
error::IntoAnyError, |
| 14 |
identity::{Credential, SigningIdentity}, |
| 15 |
mls_rules::{CommitOptions, DefaultMlsRules}, |
| 16 |
storage_provider::KeyPackageData, |
| 17 |
CipherSuite, Client, ProtocolVersion, |
| 18 |
}; |
| 19 |
|
| 20 |
use crate::ClientConfig; |
| 21 |
|
| 22 |
use mls_rs_provider_sqlite::{ |
| 23 |
connection_strategy::{ |
| 24 |
CipheredConnectionStrategy, ConnectionStrategy, FileConnectionStrategy, SqlCipherConfig, |
| 25 |
SqlCipherKey, |
| 26 |
}, |
| 27 |
SqLiteDataStorageEngine, |
| 28 |
}; |
| 29 |
|
| 30 |
use crate::{Identity, PlatformError}; |
| 31 |
|
| 32 |
#[derive(serde::Serialize, serde::Deserialize, Clone)] |
| 33 |
pub struct GroupData { |
| 34 |
state_data: Vec<u8>, |
| 35 |
epoch_data: HashMap<u64, Vec<u8>>, |
| 36 |
} |
| 37 |
|
| 38 |
#[derive(serde::Serialize, serde::Deserialize, Clone)] |
| 39 |
pub struct PlatformState { |
| 40 |
pub db_path: String, |
| 41 |
pub db_key: [u8; 32], |
| 42 |
} |
| 43 |
|
| 44 |
#[derive(serde::Serialize, serde::Deserialize, Clone, Default)] |
| 45 |
pub struct TemporaryState { |
| 46 |
pub groups: Arc<Mutex<HashMap<Vec<u8>, GroupData>>>, |
| 47 |
/// signing identity => key data |
| 48 |
pub sigkeys: HashMap<Vec<u8>, SignatureData>, |
| 49 |
pub key_packages: Arc<Mutex<HashMap<Vec<u8>, KeyPackageData>>>, |
| 50 |
} |
| 51 |
|
| 52 |
#[derive(serde::Serialize, serde::Deserialize, Clone)] |
| 53 |
pub struct SignatureData { |
| 54 |
#[serde(with = "hex::serde")] |
| 55 |
pub public_key: Vec<u8>, |
| 56 |
pub cs: u16, |
| 57 |
#[serde(with = "hex::serde")] |
| 58 |
pub secret_key: Vec<u8>, |
| 59 |
pub credential: Option<Credential>, |
| 60 |
} |
| 61 |
|
| 62 |
impl PlatformState { |
| 63 |
pub fn new(db_path: &str, db_key: &[u8; 32]) -> Result<Self, PlatformError> { |
| 64 |
let state = Self { |
| 65 |
db_path: db_path.to_string(), |
| 66 |
db_key: *db_key, |
| 67 |
}; |
| 68 |
|
| 69 |
// This will create an empty database if it doesn't exist. |
| 70 |
state |
| 71 |
.get_sqlite_engine()? |
| 72 |
.application_data_storage() |
| 73 |
.map_err(|e| (PlatformError::StorageError(e.into_any_error())))?; |
| 74 |
|
| 75 |
Ok(state) |
| 76 |
} |
| 77 |
|
| 78 |
pub fn get_signing_identities(&self) -> Result<Vec<Identity>, PlatformError> { |
| 79 |
todo!(); |
| 80 |
} |
| 81 |
|
| 82 |
pub fn client( |
| 83 |
&self, |
| 84 |
myself_identifier: &[u8], |
| 85 |
myself_credential: Option<Credential>, |
| 86 |
version: ProtocolVersion, |
| 87 |
config: &ClientConfig, |
| 88 |
) -> Result<Client<impl MlsConfig>, PlatformError> { |
| 89 |
let crypto_provider = mls_rs_crypto_nss::NssCryptoProvider::default(); |
| 90 |
|
| 91 |
let engine = self |
| 92 |
.get_sqlite_engine()? |
| 93 |
.with_context(myself_identifier.to_vec()); |
| 94 |
|
| 95 |
let mut myself_sig_data = self |
| 96 |
.get_sig_data(myself_identifier)? |
| 97 |
.ok_or(PlatformError::UnavailableSecret)?; |
| 98 |
|
| 99 |
let myself_credential = if let Some(cred) = myself_credential { |
| 100 |
myself_sig_data.credential = Some(cred.clone()); |
| 101 |
self.store_sigdata(myself_identifier, &myself_sig_data)?; |
| 102 |
|
| 103 |
cred |
| 104 |
} else if let Some(cred) = myself_sig_data.credential { |
| 105 |
cred |
| 106 |
} else { |
| 107 |
return Err(PlatformError::UndefinedIdentity); |
| 108 |
}; |
| 109 |
|
| 110 |
let myself_signing_identity = |
| 111 |
SigningIdentity::new(myself_credential, myself_sig_data.public_key.into()); |
| 112 |
|
| 113 |
let mut builder = mls_rs::client_builder::ClientBuilder::new_sqlite(engine) |
| 114 |
.map_err(|e| PlatformError::StorageError(e.into_any_error()))? |
| 115 |
.crypto_provider(crypto_provider) |
| 116 |
.identity_provider(mls_rs::identity::basic::BasicIdentityProvider) |
| 117 |
.signing_identity( |
| 118 |
myself_signing_identity, |
| 119 |
myself_sig_data.secret_key.into(), |
| 120 |
myself_sig_data.cs.into(), |
| 121 |
) |
| 122 |
.protocol_version(version); |
| 123 |
|
| 124 |
if let Some(key_package_lifetime_s) = config.key_package_lifetime_s { |
| 125 |
builder = builder.key_package_lifetime(key_package_lifetime_s); |
| 126 |
} |
| 127 |
|
| 128 |
let mls_rules = DefaultMlsRules::new().with_commit_options( |
| 129 |
CommitOptions::default().with_allow_external_commit(config.allow_external_commits), |
| 130 |
); |
| 131 |
|
| 132 |
builder = builder.mls_rules(mls_rules); |
| 133 |
|
| 134 |
Ok(builder.build()) |
| 135 |
} |
| 136 |
|
| 137 |
pub fn client_default( |
| 138 |
&self, |
| 139 |
myself_identifier: &[u8], |
| 140 |
) -> Result<Client<impl MlsConfig>, PlatformError> { |
| 141 |
self.client( |
| 142 |
myself_identifier, |
| 143 |
None, |
| 144 |
ProtocolVersion::MLS_10, |
| 145 |
&Default::default(), |
| 146 |
) |
| 147 |
} |
| 148 |
|
| 149 |
pub fn insert_sigkey( |
| 150 |
&self, |
| 151 |
myself_sigkey: &SignatureSecretKey, |
| 152 |
myself_pubkey: &SignaturePublicKey, |
| 153 |
cs: CipherSuite, |
| 154 |
identifier: &[u8], |
| 155 |
) -> Result<(), PlatformError> { |
| 156 |
let signature_data = SignatureData { |
| 157 |
public_key: myself_pubkey.to_vec(), |
| 158 |
cs: *cs, |
| 159 |
secret_key: myself_sigkey.to_vec(), |
| 160 |
credential: None, |
| 161 |
}; |
| 162 |
|
| 163 |
self.store_sigdata(identifier, &signature_data)?; |
| 164 |
|
| 165 |
Ok(()) |
| 166 |
} |
| 167 |
|
| 168 |
fn store_sigdata(&self, identifier: &[u8], data: &SignatureData) -> Result<(), PlatformError> { |
| 169 |
let data = bincode::serialize(&data)?; |
| 170 |
let engine = self.get_sqlite_engine()?; |
| 171 |
|
| 172 |
let storage = engine |
| 173 |
.application_data_storage() |
| 174 |
.map_err(|e| PlatformError::StorageError(e.into_any_error()))?; |
| 175 |
|
| 176 |
storage |
| 177 |
.insert(&hex::encode(identifier), &data) |
| 178 |
.map_err(|e| PlatformError::StorageError(e.into_any_error()))?; |
| 179 |
Ok(()) |
| 180 |
} |
| 181 |
|
| 182 |
pub fn get_sig_data( |
| 183 |
&self, |
| 184 |
myself_identifier: &[u8], |
| 185 |
) -> Result<Option<SignatureData>, PlatformError> { |
| 186 |
// TODO: Not clear if the option is needed here, the underlying function needs it. |
| 187 |
let key = myself_identifier.to_vec(); |
| 188 |
let engine = self.get_sqlite_engine()?; |
| 189 |
let storage = engine |
| 190 |
.application_data_storage() |
| 191 |
.map_err(|e| PlatformError::StorageError(e.into_any_error()))?; |
| 192 |
|
| 193 |
storage |
| 194 |
.get(&hex::encode(key)) |
| 195 |
.map_err(|e| PlatformError::StorageError(e.into_any_error()))? |
| 196 |
.map_or_else( |
| 197 |
|| Ok(None), |
| 198 |
|data| bincode::deserialize(&data).map(Some).map_err(Into::into), |
| 199 |
) |
| 200 |
} |
| 201 |
|
| 202 |
pub fn get_sqlite_engine( |
| 203 |
&self, |
| 204 |
) -> Result<SqLiteDataStorageEngine<impl ConnectionStrategy>, PlatformError> { |
| 205 |
let path = Path::new(&self.db_path); |
| 206 |
let file_conn = FileConnectionStrategy::new(path); |
| 207 |
|
| 208 |
let cipher_config = SqlCipherConfig::new(SqlCipherKey::RawKey(self.db_key)); |
| 209 |
let cipher_conn = CipheredConnectionStrategy::new(file_conn, cipher_config); |
| 210 |
|
| 211 |
SqLiteDataStorageEngine::new(cipher_conn) |
| 212 |
.map_err(|e| PlatformError::StorageError(e.into_any_error())) |
| 213 |
} |
| 214 |
|
| 215 |
pub fn delete_group(&self, gid: &[u8], identifier: &[u8]) -> Result<(), PlatformError> { |
| 216 |
let storage = self |
| 217 |
.get_sqlite_engine()? |
| 218 |
.with_context(identifier.to_vec()) |
| 219 |
.group_state_storage() |
| 220 |
.map_err(|_| PlatformError::InternalError)?; |
| 221 |
|
| 222 |
// Delete the group |
| 223 |
storage |
| 224 |
.delete_group(gid) |
| 225 |
.map_err(|_| PlatformError::InternalError) |
| 226 |
} |
| 227 |
|
| 228 |
pub fn delete(db_path: &str) -> Result<(), PlatformError> { |
| 229 |
let path = Path::new(db_path); |
| 230 |
|
| 231 |
if path.exists() { |
| 232 |
std::fs::remove_file(path)?; |
| 233 |
} |
| 234 |
|
| 235 |
Ok(()) |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
// Dependencies for implementation of InMemoryState |
| 240 |
|
| 241 |
// use crate::GroupConfig; |
| 242 |
// use mls_rs::mls_rs_codec::{MlsDecode, MlsEncode}; |
| 243 |
// use mls_rs::{GroupStateStorage, KeyPackageStorage}; |
| 244 |
// use mls_rs_core::group::{EpochRecord, GroupState}; |
| 245 |
// use std::{collections::hash_map::Entry, convert::Infallible}; |
| 246 |
|
| 247 |
// impl InMemoryState { |
| 248 |
// pub fn new() -> Self { |
| 249 |
// Default::default() |
| 250 |
// } |
| 251 |
|
| 252 |
// pub fn to_bytes(&self) -> Result<Vec<u8>, PlatformError> { |
| 253 |
// bincode::serialize(self).map_err(Into::into) |
| 254 |
// } |
| 255 |
|
| 256 |
// pub fn from_bytes(bytes: &[u8]) -> Result<Self, PlatformError> { |
| 257 |
// bincode::deserialize(bytes).map_err(Into::into) |
| 258 |
// } |
| 259 |
|
| 260 |
// pub fn client( |
| 261 |
// &self, |
| 262 |
// myself: SigningIdentity, |
| 263 |
// group_config: Option<GroupConfig>, |
| 264 |
// ) -> Result<Client<impl MlsConfig>, PlatformError> { |
| 265 |
// let crypto_provider = mls_rs_crypto_nss::NssCryptoProvider::default(); |
| 266 |
// let myself_sigkey = self.get_sigkey(&myself)?; |
| 267 |
|
| 268 |
// let mut builder = mls_rs::client_builder::ClientBuilder::new() |
| 269 |
// .key_package_repo(self.clone()) |
| 270 |
// .group_state_storage(self.clone()) |
| 271 |
// .crypto_provider(crypto_provider) |
| 272 |
// .identity_provider(mls_rs::identity::basic::BasicIdentityProvider) |
| 273 |
// .signing_identity( |
| 274 |
// myself, |
| 275 |
// myself_sigkey.secret_key.into(), |
| 276 |
// myself_sigkey.cs.into(), |
| 277 |
// ); |
| 278 |
|
| 279 |
// if let Some(config) = group_config { |
| 280 |
// builder = builder |
| 281 |
// .key_package_extensions(config.options) |
| 282 |
// .protocol_version(config.version); |
| 283 |
// } |
| 284 |
|
| 285 |
// Ok(builder.build()) |
| 286 |
// } |
| 287 |
|
| 288 |
// pub fn insert_sigkey( |
| 289 |
// &mut self, |
| 290 |
// myself_sigkey: &SignatureSecretKey, |
| 291 |
// myself_pubkey: &SignaturePublicKey, |
| 292 |
// cs: CipherSuite, |
| 293 |
// identifier: Identity, |
| 294 |
// ) -> Result<(), PlatformError> { |
| 295 |
// let signature_data = SignatureData { |
| 296 |
// public_key: myself_pubkey.to_vec(), |
| 297 |
// cs: *cs, |
| 298 |
// secret_key: myself_sigkey.to_vec(), |
| 299 |
// credential: None, |
| 300 |
// }; |
| 301 |
|
| 302 |
// self.sigkeys.insert(identifier, signature_data); |
| 303 |
// // TODO: We could return the value to indicate if the key |
| 304 |
// // existed (see the definition of insert). |
| 305 |
// Ok(()) |
| 306 |
// } |
| 307 |
|
| 308 |
// pub fn get_sigkey(&self, myself: &SigningIdentity) -> Result<SignatureData, PlatformError> { |
| 309 |
// let key = myself.mls_encode_to_vec()?; |
| 310 |
|
| 311 |
// self.sigkeys |
| 312 |
// .get(&key) |
| 313 |
// .cloned() |
| 314 |
// .ok_or(PlatformError::UnavailableSecret) |
| 315 |
// } |
| 316 |
// } |
| 317 |
|
| 318 |
// impl GroupStateStorage for TemporaryState { |
| 319 |
// type Error = mls_rs::mls_rs_codec::Error; |
| 320 |
|
| 321 |
// fn max_epoch_id(&self, group_id: &[u8]) -> Result<Option<u64>, Self::Error> { |
| 322 |
// let group_locked = self.groups.lock().unwrap(); |
| 323 |
|
| 324 |
// Ok(group_locked |
| 325 |
// .get(group_id) |
| 326 |
// .and_then(|group_data| group_data.epoch_data.keys().max().copied())) |
| 327 |
// } |
| 328 |
|
| 329 |
// fn state<T>(&self, group_id: &[u8]) -> Result<Option<T>, Self::Error> |
| 330 |
// where |
| 331 |
// T: GroupState + MlsDecode, |
| 332 |
// { |
| 333 |
// self.groups |
| 334 |
// .lock() |
| 335 |
// .unwrap() |
| 336 |
// .get(group_id) |
| 337 |
// .map(|v| T::mls_decode(&mut v.state_data.as_slice())) |
| 338 |
// .transpose() |
| 339 |
// .map_err(Into::into) |
| 340 |
// } |
| 341 |
|
| 342 |
// fn epoch<T>(&self, group_id: &[u8], epoch_id: u64) -> Result<Option<T>, Self::Error> |
| 343 |
// where |
| 344 |
// T: EpochRecord + MlsEncode + MlsDecode, |
| 345 |
// { |
| 346 |
// self.groups |
| 347 |
// .lock() |
| 348 |
// .unwrap() |
| 349 |
// .get(group_id) |
| 350 |
// .and_then(|group_data| group_data.epoch_data.get(&epoch_id)) |
| 351 |
// .map(|v| T::mls_decode(&mut &v[..])) |
| 352 |
// .transpose() |
| 353 |
// .map_err(Into::into) |
| 354 |
// } |
| 355 |
|
| 356 |
// fn write<ST, ET>( |
| 357 |
// &mut self, |
| 358 |
// state: ST, |
| 359 |
// epoch_inserts: Vec<ET>, |
| 360 |
// epoch_updates: Vec<ET>, |
| 361 |
// ) -> Result<(), Self::Error> |
| 362 |
// where |
| 363 |
// ST: GroupState + MlsEncode + MlsDecode + Send + Sync, |
| 364 |
// ET: EpochRecord + MlsEncode + MlsDecode + Send + Sync, |
| 365 |
// { |
| 366 |
// let state_data = state.mls_encode_to_vec()?; |
| 367 |
// let mut states = self.groups.lock().unwrap(); |
| 368 |
|
| 369 |
// let group_data = match states.entry(state.id()) { |
| 370 |
// Entry::Occupied(entry) => { |
| 371 |
// let data = entry.into_mut(); |
| 372 |
// data.state_data = state_data; |
| 373 |
// data |
| 374 |
// } |
| 375 |
// Entry::Vacant(entry) => entry.insert(GroupData { |
| 376 |
// state_data, |
| 377 |
// epoch_data: Default::default(), |
| 378 |
// }), |
| 379 |
// }; |
| 380 |
|
| 381 |
// epoch_inserts.into_iter().try_for_each(|e| { |
| 382 |
// group_data.epoch_data.insert(e.id(), e.mls_encode_to_vec()?); |
| 383 |
// Ok::<_, Self::Error>(()) |
| 384 |
// })?; |
| 385 |
|
| 386 |
// epoch_updates.into_iter().try_for_each(|e| { |
| 387 |
// if let Some(data) = group_data.epoch_data.get_mut(&e.id()) { |
| 388 |
// *data = e.mls_encode_to_vec()?; |
| 389 |
// }; |
| 390 |
|
| 391 |
// Ok::<_, Self::Error>(()) |
| 392 |
// })?; |
| 393 |
|
| 394 |
// Ok(()) |
| 395 |
// } |
| 396 |
// } |
| 397 |
|
| 398 |
// impl KeyPackageStorage for TemporaryState { |
| 399 |
// type Error = Infallible; |
| 400 |
|
| 401 |
// fn insert(&mut self, id: Vec<u8>, pkg: KeyPackageData) -> Result<(), Self::Error> { |
| 402 |
// let mut states = self.key_packages.lock().unwrap(); |
| 403 |
// states.insert(id, pkg); |
| 404 |
// Ok(()) |
| 405 |
// } |
| 406 |
|
| 407 |
// fn get(&self, id: &[u8]) -> Result<Option<KeyPackageData>, Self::Error> { |
| 408 |
// Ok(self.key_packages.lock().unwrap().get(id).cloned()) |
| 409 |
// } |
| 410 |
|
| 411 |
// fn delete(&mut self, id: &[u8]) -> Result<(), Self::Error> { |
| 412 |
// let mut states = self.key_packages.lock().unwrap(); |
| 413 |
// states.remove(id); |
| 414 |
// Ok(()) |
| 415 |
// } |
| 416 |
// } |