Skip to content

[PM-19479] POC state traits #213

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
21 changes: 21 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ bitwarden-cli = { path = "crates/bitwarden-cli", version = "=1.0.0" }
bitwarden-core = { path = "crates/bitwarden-core", version = "=1.0.0" }
bitwarden-crypto = { path = "crates/bitwarden-crypto", version = "=1.0.0" }
bitwarden-exporters = { path = "crates/bitwarden-exporters", version = "=1.0.0" }
bitwarden-ffi-macros = { path = "crates/bitwarden-ffi-macros", version = "=1.0.0" }
bitwarden-fido = { path = "crates/bitwarden-fido", version = "=1.0.0" }
bitwarden-generators = { path = "crates/bitwarden-generators", version = "=1.0.0" }
bitwarden-ipc = { path = "crates/bitwarden-ipc", version = "=1.0.0" }
Expand Down
1 change: 1 addition & 0 deletions crates/bitwarden-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ wasm = [
] # WASM support

[dependencies]
async-trait = ">=0.1.80, <0.2"
base64 = ">=0.22.1, <0.23"
bitwarden-api-api = { workspace = true }
bitwarden-api-identity = { workspace = true }
Expand Down
3 changes: 3 additions & 0 deletions crates/bitwarden-core/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use super::internal::InternalClient;
use crate::client::flags::Flags;
use crate::client::{
client_settings::ClientSettings,
data_store::DataStoreMap,
internal::{ApiConfigurations, Tokens},
};

Expand Down Expand Up @@ -86,6 +87,8 @@ impl Client {
})),
external_client,
key_store: KeyStore::default(),
#[cfg(feature = "internal")]
data_store_map: RwLock::new(DataStoreMap::default()),
}),
}
}
Expand Down
113 changes: 113 additions & 0 deletions crates/bitwarden-core/src/client/data_store.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use std::{
any::{Any, TypeId},
collections::HashMap,
sync::Arc,
};

#[async_trait::async_trait]
pub trait DataStore<T>: Send + Sync {
async fn get(&self, key: String) -> Option<T>;
async fn list(&self) -> Vec<T>;
async fn set(&self, key: String, value: T);
async fn remove(&self, key: String);
}

#[derive(Default)]
pub struct DataStoreMap {
stores: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl std::fmt::Debug for DataStoreMap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DataStoreMap")
.field("stores", &self.stores.keys())
.finish()
}

Check warning on line 25 in crates/bitwarden-core/src/client/data_store.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-core/src/client/data_store.rs#L21-L25

Added lines #L21 - L25 were not covered by tests
}

impl DataStoreMap {
pub fn new() -> Self {
DataStoreMap {
stores: HashMap::new(),
}
}

pub fn insert<T: 'static>(&mut self, value: Arc<dyn DataStore<T>>) {
self.stores.insert(TypeId::of::<T>(), Box::new(value));
}

pub fn get<T: 'static>(&self) -> Option<Arc<dyn DataStore<T>>> {
self.stores
.get(&TypeId::of::<T>())
.and_then(|boxed| boxed.downcast_ref::<Arc<dyn DataStore<T>>>())
.map(Arc::clone)
}
}

#[cfg(test)]
mod tests {
use super::*;

macro_rules! impl_data_store {
($name:ident, $ty:ty) => {
#[async_trait::async_trait]
impl DataStore<$ty> for $name {
async fn get(&self, _key: String) -> Option<$ty> {
Some(self.0.clone())
}
async fn list(&self) -> Vec<$ty> {
unimplemented!()
}
async fn set(&self, _key: String, _value: $ty) {
unimplemented!()
}
async fn remove(&self, _key: String) {
unimplemented!()
}

Check warning on line 66 in crates/bitwarden-core/src/client/data_store.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-core/src/client/data_store.rs#L58-L66

Added lines #L58 - L66 were not covered by tests
}
};
}

#[derive(PartialEq, Eq, Debug)]
struct TestA(usize);
#[derive(PartialEq, Eq, Debug)]
struct TestB(String);
#[derive(PartialEq, Eq, Debug)]
struct TestC(Vec<u8>);

impl_data_store!(TestA, usize);
impl_data_store!(TestB, String);
impl_data_store!(TestC, Vec<u8>);

#[tokio::test]
async fn test_data_store_map() {
let a = Arc::new(TestA(145832));
let b = Arc::new(TestB("test".to_string()));
let c = Arc::new(TestC(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]));

let mut map = DataStoreMap::new();

async fn get<T: 'static>(map: &DataStoreMap) -> Option<T> {
map.get::<T>().unwrap().get(String::new()).await
}

assert!(map.get::<usize>().is_none());
assert!(map.get::<String>().is_none());
assert!(map.get::<Vec<u8>>().is_none());

map.insert(a.clone());
assert_eq!(get(&map).await, Some(a.0));
assert!(map.get::<String>().is_none());
assert!(map.get::<Vec<u8>>().is_none());

map.insert(b.clone());
assert_eq!(get(&map).await, Some(a.0));
assert_eq!(get(&map).await, Some(b.0.clone()));
assert!(map.get::<Vec<u8>>().is_none());

map.insert(c.clone());
assert_eq!(get(&map).await, Some(a.0));
assert_eq!(get(&map).await, Some(b.0.clone()));
assert_eq!(get(&map).await, Some(c.0.clone()));
}
}
20 changes: 20 additions & 0 deletions crates/bitwarden-core/src/client/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
};
#[cfg(feature = "internal")]
use crate::{
client::data_store::{DataStore, DataStoreMap},
client::encryption_settings::EncryptionSettingsError,
client::{flags::Flags, login_method::UserLoginMethod},
error::NotAuthenticatedError,
Expand Down Expand Up @@ -60,6 +61,9 @@
pub(crate) external_client: reqwest::Client,

pub(super) key_store: KeyStore<KeyIds>,

#[cfg(feature = "internal")]
pub(super) data_store_map: RwLock<DataStoreMap>,
}

impl InternalClient {
Expand Down Expand Up @@ -219,4 +223,20 @@
) -> Result<(), EncryptionSettingsError> {
EncryptionSettings::set_org_keys(org_keys, &self.key_store)
}

#[cfg(feature = "internal")]
pub fn register_data_store<T: 'static + DataStore<V>, V: 'static>(&self, store: Arc<T>) {
self.data_store_map
.write()
.expect("RwLock is not poisoned")
.insert(store);
}

Check warning on line 233 in crates/bitwarden-core/src/client/internal.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-core/src/client/internal.rs#L228-L233

Added lines #L228 - L233 were not covered by tests

#[cfg(feature = "internal")]
pub fn get_data_store<T: 'static>(&self) -> Option<Arc<dyn DataStore<T>>> {
self.data_store_map
.read()
.expect("RwLock is not poisoned")
.get()
}

Check warning on line 241 in crates/bitwarden-core/src/client/internal.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-core/src/client/internal.rs#L236-L241

Added lines #L236 - L241 were not covered by tests
}
3 changes: 3 additions & 0 deletions crates/bitwarden-core/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ pub use client_settings::{ClientSettings, DeviceType};

#[cfg(feature = "internal")]
pub mod test_accounts;

#[cfg(feature = "internal")]
pub mod data_store;
37 changes: 37 additions & 0 deletions crates/bitwarden-ffi-macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
[package]
name = "bitwarden-ffi-macros"
description = """
Internal crate for the bitwarden crate. Do not use.
"""

version.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
readme.workspace = true
homepage.workspace = true
repository.workspace = true
license-file.workspace = true
keywords.workspace = true

[features]
wasm = []

[dependencies]
darling = "0.20.10"
proc-macro2 = "1.0.89"
quote = "1.0.37"
syn = "2.0.87"

[lints]
workspace = true

[lib]
proc-macro = true

[dev-dependencies]
js-sys.workspace = true
serde.workspace = true
thiserror.workspace = true
tsify-next.workspace = true
wasm-bindgen.workspace = true
3 changes: 3 additions & 0 deletions crates/bitwarden-ffi-macros/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Bitwarden WASM Macros

Provides utility macros for simplifying FFI with WebAssembly and UniFFI.
Loading
Loading