Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use UniFFI proc-macros for constructors #1830

Merged
merged 4 commits into from
Apr 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ thiserror = "1.0.38"
tokio = { version = "1.24", default-features = false, features = ["sync"] }
tracing = { version = "0.1.36", default-features = false, features = ["std"] }
tracing-core = "0.1.30"
uniffi = { git = "https://github.com/mozilla/uniffi-rs", rev = "aa91307b6ac27aae6d5c7ad971b762df952d2745" }
uniffi_bindgen = { git = "https://github.com/mozilla/uniffi-rs", rev = "aa91307b6ac27aae6d5c7ad971b762df952d2745" }
uniffi = { git = "https://github.com/mozilla/uniffi-rs", rev = "9e01d2281bb4a603fc9ed6409a02ad1854cdc8fb" }
uniffi_bindgen = { git = "https://github.com/mozilla/uniffi-rs", rev = "9e01d2281bb4a603fc9ed6409a02ad1854cdc8fb" }
vodozemac = { git = "https://github.com/matrix-org/vodozemac", rev = "fb609ca1e4df5a7a818490ae86ac694119e41e71" }
zeroize = "1.3.0"

Expand Down
59 changes: 31 additions & 28 deletions bindings/matrix-sdk-crypto-ffi/src/backup_recovery_key.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, iter, ops::DerefMut};
use std::{collections::HashMap, iter, ops::DerefMut, sync::Arc};

use hmac::Hmac;
use matrix_sdk_crypto::{
Expand All @@ -12,6 +12,7 @@ use thiserror::Error;
use zeroize::Zeroize;

/// The private part of the backup key, the one used for recovery.
#[derive(uniffi::Object)]
pub struct BackupRecoveryKey {
pub(crate) inner: RecoveryKey,
pub(crate) passphrase_info: Option<PassphraseInfo>,
Expand Down Expand Up @@ -62,46 +63,40 @@ pub struct MegolmV1BackupKey {
pub backup_algorithm: String,
}

#[uniffi::export]
impl BackupRecoveryKey {
/// Convert the recovery key to a base 58 encoded string.
pub fn to_base58(&self) -> String {
self.inner.to_base58()
}

/// Convert the recovery key to a base 64 encoded string.
pub fn to_base64(&self) -> String {
self.inner.to_base64()
}
}

impl BackupRecoveryKey {
const KEY_SIZE: usize = 32;
const SALT_SIZE: usize = 32;
const PBKDF_ROUNDS: i32 = 500_000;
}

#[uniffi::export]
impl BackupRecoveryKey {
/// Create a new random [`BackupRecoveryKey`].
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
#[uniffi::constructor]
pub fn new() -> Arc<Self> {
Arc::new(Self {
inner: RecoveryKey::new()
.expect("Can't gather enough randomness to create a recovery key"),
passphrase_info: None,
}
})
}

/// Try to create a [`BackupRecoveryKey`] from a base 64 encoded string.
pub fn from_base64(key: String) -> Result<Self, DecodeError> {
Ok(Self { inner: RecoveryKey::from_base64(&key)?, passphrase_info: None })
#[uniffi::constructor]
pub fn from_base64(key: String) -> Result<Arc<Self>, DecodeError> {
Ok(Arc::new(Self { inner: RecoveryKey::from_base64(&key)?, passphrase_info: None }))
}

/// Try to create a [`BackupRecoveryKey`] from a base 58 encoded string.
pub fn from_base58(key: String) -> Result<Self, DecodeError> {
Ok(Self { inner: RecoveryKey::from_base58(&key)?, passphrase_info: None })
#[uniffi::constructor]
pub fn from_base58(key: String) -> Result<Arc<Self>, DecodeError> {
Ok(Arc::new(Self { inner: RecoveryKey::from_base58(&key)?, passphrase_info: None }))
}

/// Create a new [`BackupRecoveryKey`] from the given passphrase.
pub fn new_from_passphrase(passphrase: String) -> Self {
#[uniffi::constructor]
pub fn new_from_passphrase(passphrase: String) -> Arc<Self> {
let mut rng = thread_rng();
let salt: String = iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
Expand All @@ -113,7 +108,8 @@ impl BackupRecoveryKey {
}

/// Restore a [`BackupRecoveryKey`] from the given passphrase.
pub fn from_passphrase(passphrase: String, salt: String, rounds: i32) -> Self {
#[uniffi::constructor]
pub fn from_passphrase(passphrase: String, salt: String, rounds: i32) -> Arc<Self> {
let mut key = Box::new([0u8; Self::KEY_SIZE]);
let rounds = rounds as u32;

Expand All @@ -123,18 +119,25 @@ impl BackupRecoveryKey {

key.zeroize();

Self {
Arc::new(Self {
inner: recovery_key,
passphrase_info: Some(PassphraseInfo {
private_key_salt: salt,
private_key_iterations: rounds as i32,
}),
}
})
}

/// Convert the recovery key to a base 58 encoded string.
pub fn to_base58(&self) -> String {
self.inner.to_base58()
}

/// Convert the recovery key to a base 64 encoded string.
pub fn to_base64(&self) -> String {
self.inner.to_base64()
}
}

#[uniffi::export]
impl BackupRecoveryKey {
/// Get the public part of the backup key.
pub fn megolm_v1_public_key(&self) -> MegolmV1BackupKey {
let public_key = self.inner.megolm_v1_public_key();
Expand Down
3 changes: 2 additions & 1 deletion bindings/matrix-sdk-crypto-ffi/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ pub enum SignatureError {
UnknownUserIdentity(String),
}

#[derive(Debug, thiserror::Error)]
#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi(flat_error)]
pub enum CryptoStoreError {
#[error("Failed to open the store")]
OpenStore(#[from] OpenStoreError),
Expand Down
7 changes: 6 additions & 1 deletion bindings/matrix-sdk-crypto-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -972,7 +972,12 @@ mod test {

migrate(migration_data, path.clone(), None, Box::new(|_, _| {}))?;

let machine = OlmMachine::new("@ganfra146:matrix.org", "DEWRCMENGS", &path, None)?;
let machine = OlmMachine::new(
"@ganfra146:matrix.org".to_owned(),
"DEWRCMENGS".to_owned(),
path,
None,
)?;

assert_eq!(
machine.identity_keys()["ed25519"],
Expand Down
80 changes: 41 additions & 39 deletions bindings/matrix-sdk-crypto-ffi/src/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ use crate::{
};

/// A high level state machine that handles E2EE for Matrix.
#[derive(uniffi::Object)]
pub struct OlmMachine {
pub(crate) inner: ManuallyDrop<InnerMachine>,
pub(crate) runtime: Runtime,
Expand Down Expand Up @@ -128,6 +129,7 @@ impl From<RustSignatureCheckResult> for SignatureVerification {
}
}

#[uniffi::export]
impl OlmMachine {
/// Create a new `OlmMachine`
///
Expand All @@ -142,14 +144,15 @@ impl OlmMachine {
/// * `passphrase` - The passphrase that should be used to encrypt the data
/// at rest in the Sled store. **Warning**, if no passphrase is given, the
/// store and all its data will remain unencrypted.
#[uniffi::constructor]
pub fn new(
user_id: &str,
device_id: &str,
path: &str,
user_id: String,
device_id: String,
path: String,
mut passphrase: Option<String>,
) -> Result<Self, CryptoStoreError> {
let user_id = parse_user_id(user_id)?;
let device_id = device_id.into();
) -> Result<Arc<Self>, CryptoStoreError> {
let user_id = parse_user_id(&user_id)?;
let device_id = device_id.as_str().into();
let runtime = Runtime::new().expect("Couldn't create a tokio runtime");

let store = runtime
Expand All @@ -160,41 +163,9 @@ impl OlmMachine {
let inner =
runtime.block_on(InnerMachine::with_store(&user_id, device_id, Arc::new(store)))?;

Ok(OlmMachine { inner: ManuallyDrop::new(inner), runtime })
}

fn import_room_keys_helper(
&self,
keys: Vec<ExportedRoomKey>,
from_backup: bool,
progress_listener: Box<dyn ProgressListener>,
) -> Result<KeysImportResult, KeyImportError> {
let listener = |progress: usize, total: usize| {
progress_listener.on_progress(progress as i32, total as i32)
};

let result =
self.runtime.block_on(self.inner.import_room_keys(keys, from_backup, listener))?;

Ok(KeysImportResult {
imported: result.imported_count as i64,
total: result.total_count as i64,
keys: result
.keys
.into_iter()
.map(|(r, m)| {
(
r.to_string(),
m.into_iter().map(|(s, k)| (s, k.into_iter().collect())).collect(),
)
})
.collect(),
})
Ok(Arc::new(OlmMachine { inner: ManuallyDrop::new(inner), runtime }))
}
}

#[uniffi::export]
impl OlmMachine {
/// Get the user ID of the owner of this `OlmMachine`.
pub fn user_id(&self) -> String {
self.inner.user_id().to_string()
Expand Down Expand Up @@ -1402,3 +1373,34 @@ impl OlmMachine {
.into())
}
}

impl OlmMachine {
fn import_room_keys_helper(
&self,
keys: Vec<ExportedRoomKey>,
from_backup: bool,
progress_listener: Box<dyn ProgressListener>,
) -> Result<KeysImportResult, KeyImportError> {
let listener = |progress: usize, total: usize| {
progress_listener.on_progress(progress as i32, total as i32)
};

let result =
self.runtime.block_on(self.inner.import_room_keys(keys, from_backup, listener))?;

Ok(KeysImportResult {
imported: result.imported_count as i64,
total: result.total_count as i64,
keys: result
.keys
.into_iter()
.map(|(r, m)| {
(
r.to_string(),
m.into_iter().map(|(s, k)| (s, k.into_iter().collect())).collect(),
)
})
.collect(),
})
}
}
32 changes: 0 additions & 32 deletions bindings/matrix-sdk-crypto-ffi/src/olm.udl
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,6 @@ callback interface ProgressListener {
void on_progress(i32 progress, i32 total);
};

[Error]
enum CryptoStoreError {
"OpenStore",
"CryptoStore",
"OlmError",
"Serialization",
"InvalidUserId",
"Identifier",
};

dictionary CancelInfo {
string cancel_code;
string reason;
Expand Down Expand Up @@ -71,31 +61,9 @@ enum LocalTrust {
"Unset",
};

interface OlmMachine {
[Throws=CryptoStoreError]
constructor(
[ByRef] string user_id,
[ByRef] string device_id,
[ByRef] string path,
string? passphrase
);
};

enum SignatureState {
"Missing",
"Invalid",
"ValidButNotTrusted",
"ValidAndTrusted",
};

interface BackupRecoveryKey {
constructor();
[Name=from_passphrase]
constructor(string passphrase, string salt, i32 rounds);
[Name=new_from_passphrase]
constructor(string passphrase);
[Name=from_base64, Throws=DecodeError]
constructor(string key);
[Name=from_base58, Throws=DecodeError]
constructor(string key);
};
Loading