Skip to content

Commit

Permalink
Cleanup and fix compile
Browse files Browse the repository at this point in the history
  • Loading branch information
Hinton committed Aug 13, 2024
1 parent 3d24452 commit e59263d
Show file tree
Hide file tree
Showing 16 changed files with 50 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ xcuserdata/

# Databases
*.sqlite
crates/bitwarden-db-tests/pkg

node_modules/
clients/python/env/
Expand Down
1 change: 1 addition & 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 crates/bitwarden-core/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const MIGRATIONS: &[Migration] = &[
];

impl Client {
#[allow(clippy::unused_async)]
pub async fn new(settings_input: Option<ClientSettings>) -> Self {
let settings = settings_input.unwrap_or_default();

Expand Down
5 changes: 3 additions & 2 deletions crates/bitwarden-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,9 @@
//! ## Crate features
//!
//! - `no-memory-hardening` - Disables memory hardening which ensures that allocated memory is
//! zeroed on drop. This feature primarily exists in case you do not want to use the standard
//! allocator, and we advise to still define a `global_allocator` using the [`ZeroizingAllocator`].
//! zeroed on drop. This feature primarily exists in case you do not want to use the standard
//! allocator, and we advise to still define a `global_allocator` using the
//! [`ZeroizingAllocator`].
#[cfg(not(feature = "no-memory-hardening"))]
#[global_allocator]
Expand Down
6 changes: 0 additions & 6 deletions crates/bitwarden-db-tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,17 @@ class SqliteDatabase {
}

async execute_batch(sql) {
console.log(sql);
// localStorage.setItem("sql", sql);
await sqlite3.exec(this.db, sql);
}

async execute(sql, params) {
console.log(sql, params);
for await (const stmt of sqlite3.statements(this.db, sql)) {
let rc = sqlite3.bind_collection(stmt, params);

while ((rc = await sqlite3.step(stmt)) !== SQLite.SQLITE_DONE) {
console.log(rc);
}
}

// localStorage.setItem("sql", sql);
// await sqlite3.exec(this.db, sql);
}

async query_map(sql) {
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden-db-tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub async fn test_create_select(db: &Database) {
}

let rows = db
.query_map("SELECT * FROM test", |row| {
.query_map("SELECT * FROM test", [], |row| {
Ok(Test {
id: row.get(0)?,
name: row.get(1)?,

Check warning on line 52 in crates/bitwarden-db-tests/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-db-tests/src/lib.rs#L48-L52

Added lines #L48 - L52 were not covered by tests
Expand Down
7 changes: 0 additions & 7 deletions crates/bitwarden-db-tests/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");

module.exports = {
Expand All @@ -14,12 +13,6 @@ module.exports = {
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, "."),
}),
// Have this example work in Edge which doesn't ship `TextEncoder` or
// `TextDecoder` at this time.
new webpack.ProvidePlugin({
TextDecoder: ["text-encoding", "TextDecoder"],
TextEncoder: ["text-encoding", "TextEncoder"],
}),
],
optimization: {
splitChunks: {
Expand Down
2 changes: 0 additions & 2 deletions crates/bitwarden-db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ license-file.workspace = true
log = ">=0.4.18, <0.5"
thiserror = ">=1.0.40, <2.0"
uuid = { version = ">=1.3.3, <2.0" }

[dev-dependencies]
tokio = { workspace = true }

[target.'cfg(not(target_arch="wasm32"))'.dependencies]
Expand Down
34 changes: 25 additions & 9 deletions crates/bitwarden-db/src/sqlite.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use rusqlite::Connection;
pub use rusqlite::{named_params, params, Params, Row};
use tokio::sync::Mutex;

use super::{DatabaseError, DatabaseTrait};

#[derive(Debug)]
pub struct SqliteDatabase {
conn: Connection,
conn: Mutex<Connection>,
}

impl SqliteDatabase {
Expand All @@ -21,43 +22,54 @@ impl SqliteDatabase {
let conn =
Connection::open_in_memory().expect("Failed to open in-memory sqlite connection");

SqliteDatabase { conn }
SqliteDatabase {
conn: Mutex::new(conn),
}
}

/// Create a new SqliteDatabase with the given connection.
async fn new_conn(conn: Connection) -> Result<Self, DatabaseError> {
let db = SqliteDatabase { conn };
let db = SqliteDatabase {
conn: Mutex::new(conn),
};

Ok(db)
}
}

impl DatabaseTrait for SqliteDatabase {
async fn get_version(&self) -> Result<usize, DatabaseError> {
let version: usize = self
.conn
let guard = self.conn.lock().await;

let version: usize = guard
.query_row("PRAGMA user_version", [], |row| row.get(0))
.map_err(|_| DatabaseError::UnableToGetVersion)?;

Ok(version)
}

async fn set_version(&self, version: usize) -> Result<(), DatabaseError> {
self.conn
let guard = self.conn.lock().await;

guard
.pragma_update(None, "user_version", version)
.map_err(|_| DatabaseError::UnableToSetVersion)?;

Ok(())
}

async fn execute_batch(&self, sql: &str) -> Result<(), DatabaseError> {
self.conn.execute_batch(sql)?;
let guard = self.conn.lock().await;

guard.execute_batch(sql)?;

Ok(())
}

async fn execute<P: Params>(&self, sql: &str, params: P) -> Result<usize, DatabaseError> {
self.conn.execute(sql, params)?;
let guard = self.conn.lock().await;

guard.execute(sql, params)?;

Ok(0)
}
Expand All @@ -71,7 +83,9 @@ impl DatabaseTrait for SqliteDatabase {
where
F: Fn(&Row) -> Result<T, DatabaseError>,
{
let mut stmt = self.conn.prepare(query)?;
let guard = self.conn.lock().await;

let mut stmt = guard.prepare(query)?;
let rows: Result<Vec<T>, rusqlite::Error> = stmt
.query_map(params, |row| row_to_type(row).map_err(|err| err.into()))?
.collect();
Expand Down Expand Up @@ -118,12 +132,14 @@ mod tests {
.await
.unwrap();

/*
let count: i64 = db
.conn
.query_row("SELECT COUNT(*) FROM test", [], |row| row.get(0))
.unwrap();
assert_eq!(count, 1);
*/
}

#[tokio::test]
Expand Down
12 changes: 9 additions & 3 deletions crates/bitwarden-db/src/wasm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ extern "C" {
async fn execute(this: &SqliteDatabase, sql: &str, params: JsValue);

#[wasm_bindgen(method)]
async fn query_map(this: &SqliteDatabase, sql: &str) -> JsValue;
async fn query_map(this: &SqliteDatabase, sql: &str, params: JsValue) -> JsValue;
}

impl core::fmt::Debug for SqliteDatabase {
Expand Down Expand Up @@ -80,11 +80,17 @@ impl DatabaseTrait for WasmDatabase {
Ok(0)
}

async fn query_map<T, F>(&self, sql: &str, row_to_type: F) -> Result<Vec<T>, DatabaseError>
async fn query_map<P, T, F>(
&self,
sql: &str,
params: P,
row_to_type: F,
) -> Result<Vec<T>, DatabaseError>
where
P: Params,
F: Fn(&Row) -> Result<T, DatabaseError>,
{
let result = self.db.query_map(sql).await;
let result = self.db.query_map(sql, params.to_sql()).await;

let rows = js_sys::Array::from(&result)
.iter()
Expand Down
6 changes: 3 additions & 3 deletions crates/bitwarden-generators/src/client_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl<'a> ClientGenerator<'a> {
/// length: 20,
/// ..Default::default()
/// };
/// let password = Client::new(None).generator().password(input).unwrap();
/// let password = Client::new(None).await.generator().password(input).unwrap();
/// println!("{}", password);
/// Ok(())
/// }
Expand All @@ -59,7 +59,7 @@ impl<'a> ClientGenerator<'a> {
/// num_words: 4,
/// ..Default::default()
/// };
/// let passphrase = Client::new(None).generator().passphrase(input).unwrap();
/// let passphrase = Client::new(None).await.generator().passphrase(input).unwrap();
/// println!("{}", passphrase);
/// Ok(())
/// }
Expand All @@ -84,7 +84,7 @@ impl<'a> ClientGenerator<'a> {
/// capitalize: true,
/// include_number: true,
/// };
/// let username = Client::new(None).generator().username(input).await.unwrap();
/// let username = Client::new(None).await.generator().username(input).await.unwrap();
/// println!("{}", username);
/// Ok(())
/// }
Expand Down
1 change: 1 addition & 0 deletions crates/bitwarden-uniffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ schemars = { version = ">=0.8, <0.9", optional = true }
thiserror = ">=1.0.40, <2.0"
uniffi = "=0.28.0"
uuid = ">=1.3.3, <2"
tokio = { workspace = true }

[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.14"
Expand Down
4 changes: 2 additions & 2 deletions crates/bitwarden-uniffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ pub struct Client(bitwarden::Client);
#[uniffi::export]
impl Client {
/// Initialize a new instance of the SDK client
#[uniffi::constructor]
pub async fn new(settings: Option<ClientSettings>) -> Arc<Self> {
#[uniffi::constructor(async_runtime = "tokio")]
pub async fn factory(settings: Option<ClientSettings>) -> Arc<Self> {

Check warning on line 32 in crates/bitwarden-uniffi/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-uniffi/src/lib.rs#L32

Added line #L32 was not covered by tests
init_logger();
Arc::new(Self(bitwarden::Client::new(settings).await))

Check warning on line 34 in crates/bitwarden-uniffi/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-uniffi/src/lib.rs#L34

Added line #L34 was not covered by tests
}
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden-vault/src/cipher/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl CipherRepository {
guard.execute("DELETE FROM ciphers", []).await?;

for cipher in ciphers {
let id = cipher.id.unwrap();
let id = require!(cipher.id);
let serialized = serde_json::to_string(&cipher)?;

guard
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async fn test() -> Result<()> {
user_agent: "Bitwarden Rust-SDK".to_string(),
device_type: DeviceType::SDK,
};
let mut client = Client::new(Some(settings));
let mut client = Client::new(Some(settings)).await;

// Before we operate, we need to authenticate with a token
let token = AccessTokenLoginRequest {
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
//! user_agent: "Bitwarden Rust-SDK".to_string(),
//! device_type: DeviceType::SDK,
//! };
//! let mut client = Client::new(Some(settings));
//! let mut client = Client::new(Some(settings)).await;
//!
//! // Before we operate, we need to authenticate with a token
//! let token = AccessTokenLoginRequest {
Expand Down

0 comments on commit e59263d

Please sign in to comment.