From 7ae040c545fc1e57121a92ae0d4d6ffd19faf12c Mon Sep 17 00:00:00 2001 From: Hinton Date: Thu, 10 Oct 2024 09:23:56 +0200 Subject: [PATCH 1/5] Change uniffi to depend directly on the individual bitwarden crates --- Cargo.lock | 1 - crates/bitwarden-uniffi/Cargo.toml | 4 +- crates/bitwarden-uniffi/src/auth/mod.rs | 2 +- crates/bitwarden-uniffi/src/crypto.rs | 2 +- crates/bitwarden-uniffi/src/docs.rs | 49 ------------- crates/bitwarden-uniffi/src/error.rs | 61 ++++++++-------- crates/bitwarden-uniffi/src/lib.rs | 13 ++-- crates/bitwarden-uniffi/src/platform/fido2.rs | 69 +++++++------------ crates/bitwarden-uniffi/src/platform/mod.rs | 2 +- crates/bitwarden-uniffi/src/tool/mod.rs | 41 +++-------- crates/bitwarden-uniffi/src/tool/sends.rs | 2 +- crates/bitwarden-uniffi/src/uniffi_support.rs | 8 ++- .../bitwarden-uniffi/src/vault/attachments.rs | 2 +- crates/bitwarden-uniffi/src/vault/ciphers.rs | 9 +-- .../bitwarden-uniffi/src/vault/collections.rs | 2 +- crates/bitwarden-uniffi/src/vault/folders.rs | 2 +- crates/bitwarden-uniffi/src/vault/mod.rs | 20 +----- .../src/vault/password_history.rs | 2 +- crates/sdk-schemas/Cargo.toml | 6 +- crates/sdk-schemas/src/main.rs | 3 - 20 files changed, 93 insertions(+), 207 deletions(-) delete mode 100644 crates/bitwarden-uniffi/src/docs.rs diff --git a/Cargo.lock b/Cargo.lock index 4e0d14119..375188c55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -623,7 +623,6 @@ version = "0.1.0" dependencies = [ "android_logger", "async-trait", - "bitwarden", "bitwarden-core", "bitwarden-crypto", "bitwarden-exporters", diff --git a/crates/bitwarden-uniffi/Cargo.toml b/crates/bitwarden-uniffi/Cargo.toml index 822ed0d38..2e57e23b5 100644 --- a/crates/bitwarden-uniffi/Cargo.toml +++ b/crates/bitwarden-uniffi/Cargo.toml @@ -11,7 +11,6 @@ repository.workspace = true license-file.workspace = true [features] -docs = ["dep:schemars"] # Docs [lib] crate-type = ["lib", "staticlib", "cdylib"] @@ -19,7 +18,6 @@ bench = false [dependencies] async-trait = "0.1.80" -bitwarden = { workspace = true, features = ["internal", "uniffi"] } bitwarden-core = { workspace = true, features = ["uniffi"] } bitwarden-crypto = { workspace = true, features = ["uniffi"] } bitwarden-exporters = { workspace = true, features = ["uniffi"] } @@ -28,8 +26,8 @@ bitwarden-generators = { workspace = true, features = ["uniffi"] } bitwarden-send = { workspace = true, features = ["uniffi"] } bitwarden-vault = { workspace = true, features = ["uniffi"] } chrono = { workspace = true, features = ["std"] } -log = { workspace = true } env_logger = "0.11.1" +log = { workspace = true } schemars = { workspace = true, optional = true } thiserror = { workspace = true } uniffi = { workspace = true } diff --git a/crates/bitwarden-uniffi/src/auth/mod.rs b/crates/bitwarden-uniffi/src/auth/mod.rs index d036991e3..43496080a 100644 --- a/crates/bitwarden-uniffi/src/auth/mod.rs +++ b/crates/bitwarden-uniffi/src/auth/mod.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bitwarden::{ +use bitwarden_core::{ auth::{ password::MasterPasswordPolicyOptions, AuthRequestResponse, KeyConnectorResponse, RegisterKeyResponse, RegisterTdeKeyResponse, diff --git a/crates/bitwarden-uniffi/src/crypto.rs b/crates/bitwarden-uniffi/src/crypto.rs index 608698fc6..6404d62f6 100644 --- a/crates/bitwarden-uniffi/src/crypto.rs +++ b/crates/bitwarden-uniffi/src/crypto.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bitwarden::{ +use bitwarden_core::{ mobile::crypto::{ DeriveKeyConnectorRequest, DerivePinKeyResponse, InitOrgCryptoRequest, InitUserCryptoRequest, UpdatePasswordResponse, diff --git a/crates/bitwarden-uniffi/src/docs.rs b/crates/bitwarden-uniffi/src/docs.rs deleted file mode 100644 index 5edbc7144..000000000 --- a/crates/bitwarden-uniffi/src/docs.rs +++ /dev/null @@ -1,49 +0,0 @@ -use bitwarden::{ - auth::password::MasterPasswordPolicyOptions, - exporters::ExportFormat, - generators::{PassphraseGeneratorRequest, PasswordGeneratorRequest}, - mobile::crypto::{InitOrgCryptoRequest, InitUserCryptoRequest}, - platform::FingerprintRequest, - send::{Send, SendListView, SendView}, - vault::{Cipher, CipherView, Collection, Folder, FolderView, TotpResponse}, -}; -use bitwarden_crypto::{HashPurpose, Kdf}; -use schemars::JsonSchema; - -#[derive(JsonSchema)] -#[allow(clippy::large_enum_variant)] -pub enum DocRef { - // Vault - Cipher(Cipher), - CipherView(CipherView), - Collection(Collection), - Folder(Folder), - FolderView(FolderView), - Send(Send), - SendView(SendView), - SendListView(SendListView), - - // Crypto - InitUserCryptoRequest(InitUserCryptoRequest), - InitOrgCryptoRequest(InitOrgCryptoRequest), - HashPurpose(HashPurpose), - - // Generators - PasswordGeneratorRequest(PasswordGeneratorRequest), - PassphraseGeneratorRequest(PassphraseGeneratorRequest), - - // Exporters - ExportFormat(ExportFormat), - - // Platform - FingerprintRequest(FingerprintRequest), - - // Auth - MasterPasswordPolicyOptions(MasterPasswordPolicyOptions), - - // Kdf - Kdf(Kdf), - - /// TOTP - TotpResponse(TotpResponse), -} diff --git a/crates/bitwarden-uniffi/src/error.rs b/crates/bitwarden-uniffi/src/error.rs index 5a1dfe43a..abcd4a4f5 100644 --- a/crates/bitwarden-uniffi/src/error.rs +++ b/crates/bitwarden-uniffi/src/error.rs @@ -1,39 +1,46 @@ -use std::fmt::{Display, Formatter}; +use bitwarden_exporters::ExportError; +use bitwarden_generators::{PassphraseError, PasswordError, UsernameError}; // Name is converted from *Error to *Exception, so we can't just name the enum Error because // Exception already exists -#[derive(uniffi::Error, Debug)] +#[derive(uniffi::Error, thiserror::Error, Debug)] #[uniffi(flat_error)] pub enum BitwardenError { - E(bitwarden::error::Error), -} + #[error(transparent)] + Core(#[from] bitwarden_core::Error), -impl From for BitwardenError { - fn from(e: bitwarden::Error) -> Self { - Self::E(e.into()) - } -} + // Generators + #[error(transparent)] + UsernameError(#[from] UsernameError), + #[error(transparent)] + PassphraseError(#[from] PassphraseError), + #[error(transparent)] + PasswordError(#[from] PasswordError), -impl From for BitwardenError { - fn from(e: bitwarden::error::Error) -> Self { - Self::E(e) - } -} + // Vault + #[error(transparent)] + Cipher(#[from] bitwarden_vault::CipherError), + #[error(transparent)] + Totp(#[from] bitwarden_vault::TotpError), -impl Display for BitwardenError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - Self::E(e) => Display::fmt(e, f), - } - } -} + #[error(transparent)] + ExportError(#[from] ExportError), -impl std::error::Error for BitwardenError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - BitwardenError::E(e) => Some(e), - } - } + // Fido + #[error(transparent)] + MakeCredential(#[from] bitwarden_fido::MakeCredentialError), + #[error(transparent)] + GetAssertion(#[from] bitwarden_fido::GetAssertionError), + #[error(transparent)] + SilentlyDiscoverCredentials(#[from] bitwarden_fido::SilentlyDiscoverCredentialsError), + #[error(transparent)] + CredentialsForAutofillError(#[from] bitwarden_fido::CredentialsForAutofillError), + #[error(transparent)] + DecryptFido2AutofillCredentialsError( + #[from] bitwarden_fido::DecryptFido2AutofillCredentialsError, + ), + #[error(transparent)] + Fido2Client(#[from] bitwarden_fido::Fido2ClientError), } pub type Result = std::result::Result; diff --git a/crates/bitwarden-uniffi/src/lib.rs b/crates/bitwarden-uniffi/src/lib.rs index 0d89ffdb8..aae35c37a 100644 --- a/crates/bitwarden-uniffi/src/lib.rs +++ b/crates/bitwarden-uniffi/src/lib.rs @@ -3,7 +3,7 @@ uniffi::setup_scaffolding!(); use std::sync::Arc; use auth::ClientAuth; -use bitwarden::ClientSettings; +use bitwarden_core::ClientSettings; pub mod auth; pub mod crypto; @@ -13,9 +13,6 @@ pub mod tool; mod uniffi_support; pub mod vault; -#[cfg(feature = "docs")] -pub mod docs; - #[cfg(target_os = "android")] mod android_support; @@ -26,7 +23,7 @@ use tool::{ClientExporters, ClientGenerators, ClientSends}; use vault::ClientVault; #[derive(uniffi::Object)] -pub struct Client(bitwarden::Client); +pub struct Client(bitwarden_core::Client); #[uniffi::export(async_runtime = "tokio")] impl Client { @@ -38,7 +35,7 @@ impl Client { #[cfg(target_os = "android")] android_support::init(); - Arc::new(Self(bitwarden::Client::new(settings))) + Arc::new(Self(bitwarden_core::Client::new(settings))) } /// Crypto operations @@ -87,9 +84,9 @@ impl Client { .get(&url) .send() .await - .map_err(bitwarden::Error::Reqwest)?; + .map_err(bitwarden_core::Error::Reqwest)?; - Ok(res.text().await.map_err(bitwarden::Error::Reqwest)?) + Ok(res.text().await.map_err(bitwarden_core::Error::Reqwest)?) } } diff --git a/crates/bitwarden-uniffi/src/platform/fido2.rs b/crates/bitwarden-uniffi/src/platform/fido2.rs index f483ff346..e484f5f2e 100644 --- a/crates/bitwarden-uniffi/src/platform/fido2.rs +++ b/crates/bitwarden-uniffi/src/platform/fido2.rs @@ -1,17 +1,13 @@ use std::sync::Arc; -use bitwarden::{ - error::Error, - fido::{ - CheckUserOptions, ClientData, ClientFido2Ext, Fido2CallbackError as BitFido2CallbackError, - GetAssertionRequest, GetAssertionResult, MakeCredentialRequest, MakeCredentialResult, - PublicKeyCredentialAuthenticatorAssertionResponse, - PublicKeyCredentialAuthenticatorAttestationResponse, PublicKeyCredentialRpEntity, - PublicKeyCredentialUserEntity, - }, - vault::{Cipher, CipherView, Fido2CredentialNewView}, +use bitwarden_fido::{ + CheckUserOptions, ClientData, ClientFido2Ext, Fido2CallbackError as BitFido2CallbackError, + Fido2CredentialAutofillView, GetAssertionRequest, GetAssertionResult, MakeCredentialRequest, + MakeCredentialResult, Origin, PublicKeyCredentialAuthenticatorAssertionResponse, + PublicKeyCredentialAuthenticatorAttestationResponse, PublicKeyCredentialRpEntity, + PublicKeyCredentialUserEntity, }; -use bitwarden_fido::{Fido2CredentialAutofillView, Origin}; +use bitwarden_vault::{Cipher, CipherView, Fido2CredentialNewView}; use crate::{error::Result, Client}; @@ -52,8 +48,7 @@ impl ClientFido2 { .0 .0 .fido2() - .decrypt_fido2_autofill_credentials(cipher_view) - .map_err(Error::DecryptFido2AutofillCredentialsError)?; + .decrypt_fido2_autofill_credentials(cipher_view)?; Ok(result) } @@ -77,10 +72,7 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth - .make_credential(request) - .await - .map_err(Error::MakeCredential)?; + let result = auth.make_credential(request).await?; Ok(result) } @@ -90,10 +82,7 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth - .get_assertion(request) - .await - .map_err(Error::GetAssertion)?; + let result = auth.get_assertion(request).await?; Ok(result) } @@ -107,10 +96,7 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth - .silently_discover_credentials(rp_id) - .await - .map_err(Error::SilentlyDiscoverCredentials)?; + let result = auth.silently_discover_credentials(rp_id).await?; Ok(result) } @@ -120,10 +106,7 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth - .credentials_for_autofill() - .await - .map_err(Error::CredentialsForAutofillError)?; + let result = auth.credentials_for_autofill().await?; Ok(result) } } @@ -144,10 +127,7 @@ impl ClientFido2Client { let cs = UniffiTraitBridge(self.0 .2.as_ref()); let mut client = fido2.create_client(&ui, &cs); - let result = client - .register(origin, request, client_data) - .await - .map_err(Error::Fido2Client)?; + let result = client.register(origin, request, client_data).await?; Ok(result) } @@ -162,10 +142,7 @@ impl ClientFido2Client { let cs = UniffiTraitBridge(self.0 .2.as_ref()); let mut client = fido2.create_client(&ui, &cs); - let result = client - .authenticate(origin, request, client_data) - .await - .map_err(Error::Fido2Client)?; + let result = client.authenticate(origin, request, client_data).await?; Ok(result) } } @@ -180,7 +157,7 @@ pub struct CheckUserResult { user_verified: bool, } -impl From for bitwarden::fido::CheckUserResult { +impl From for bitwarden_fido::CheckUserResult { fn from(val: CheckUserResult) -> Self { Self { user_present: val.user_present, @@ -268,7 +245,7 @@ pub trait Fido2CredentialStore: Send + Sync { struct UniffiTraitBridge(T); #[async_trait::async_trait] -impl bitwarden::fido::Fido2CredentialStore for UniffiTraitBridge<&dyn Fido2CredentialStore> { +impl bitwarden_fido::Fido2CredentialStore for UniffiTraitBridge<&dyn Fido2CredentialStore> { async fn find_credentials( &self, ids: Option>>, @@ -306,9 +283,9 @@ pub enum UIHint { RequestExistingCredential(CipherView), } -impl From> for UIHint { - fn from(hint: bitwarden::fido::UIHint<'_, CipherView>) -> Self { - use bitwarden::fido::UIHint as BWUIHint; +impl From> for UIHint { + fn from(hint: bitwarden_fido::UIHint<'_, CipherView>) -> Self { + use bitwarden_fido::UIHint as BWUIHint; match hint { BWUIHint::InformExcludedCredentialFound(cipher) => { UIHint::InformExcludedCredentialFound(cipher.clone()) @@ -333,12 +310,12 @@ impl From> for UIHint { } #[async_trait::async_trait] -impl bitwarden::fido::Fido2UserInterface for UniffiTraitBridge<&dyn Fido2UserInterface> { +impl bitwarden_fido::Fido2UserInterface for UniffiTraitBridge<&dyn Fido2UserInterface> { async fn check_user<'a>( &self, options: CheckUserOptions, - hint: bitwarden::fido::UIHint<'a, CipherView>, - ) -> Result { + hint: bitwarden_fido::UIHint<'a, CipherView>, + ) -> Result { self.0 .check_user(options.clone(), hint.into()) .await @@ -359,7 +336,7 @@ impl bitwarden::fido::Fido2UserInterface for UniffiTraitBridge<&dyn Fido2UserInt &self, options: CheckUserOptions, new_credential: Fido2CredentialNewView, - ) -> Result<(CipherView, bitwarden::fido::CheckUserResult), BitFido2CallbackError> { + ) -> Result<(CipherView, bitwarden_fido::CheckUserResult), BitFido2CallbackError> { self.0 .check_user_and_pick_credential_for_creation(options, new_credential) .await diff --git a/crates/bitwarden-uniffi/src/platform/mod.rs b/crates/bitwarden-uniffi/src/platform/mod.rs index 63ff6e183..b5d944152 100644 --- a/crates/bitwarden-uniffi/src/platform/mod.rs +++ b/crates/bitwarden-uniffi/src/platform/mod.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bitwarden::platform::FingerprintRequest; +use bitwarden_core::platform::FingerprintRequest; use crate::{error::Result, Client}; diff --git a/crates/bitwarden-uniffi/src/tool/mod.rs b/crates/bitwarden-uniffi/src/tool/mod.rs index 1fd439a4f..4b96c37d1 100644 --- a/crates/bitwarden-uniffi/src/tool/mod.rs +++ b/crates/bitwarden-uniffi/src/tool/mod.rs @@ -1,14 +1,11 @@ use std::sync::Arc; -use bitwarden::{ - error::Error, - exporters::{ClientExportersExt, ExportFormat}, - generators::{ - ClientGeneratorExt, PassphraseGeneratorRequest, PasswordGeneratorRequest, - UsernameGeneratorRequest, - }, - vault::{Cipher, Collection, Folder}, +use bitwarden_exporters::{ClientExportersExt, ExportFormat}; +use bitwarden_generators::{ + ClientGeneratorExt, PassphraseGeneratorRequest, PasswordGeneratorRequest, + UsernameGeneratorRequest, }; +use bitwarden_vault::{Cipher, Collection, Folder}; use crate::{error::Result, Client}; @@ -22,33 +19,17 @@ pub struct ClientGenerators(pub(crate) Arc); impl ClientGenerators { /// **API Draft:** Generate Password pub fn password(&self, settings: PasswordGeneratorRequest) -> Result { - Ok(self - .0 - .0 - .generator() - .password(settings) - .map_err(Error::PasswordError)?) + Ok(self.0 .0.generator().password(settings)?) } /// **API Draft:** Generate Passphrase pub fn passphrase(&self, settings: PassphraseGeneratorRequest) -> Result { - Ok(self - .0 - .0 - .generator() - .passphrase(settings) - .map_err(Error::PassphraseError)?) + Ok(self.0 .0.generator().passphrase(settings)?) } /// **API Draft:** Generate Username pub async fn username(&self, settings: UsernameGeneratorRequest) -> Result { - Ok(self - .0 - .0 - .generator() - .username(settings) - .await - .map_err(Error::UsernameError)?) + Ok(self.0 .0.generator().username(settings).await?) } } @@ -68,8 +49,7 @@ impl ClientExporters { .0 .0 .exporters() - .export_vault(folders, ciphers, format) - .map_err(Error::ExportError)?) + .export_vault(folders, ciphers, format)?) } /// **API Draft:** Export organization vault @@ -83,7 +63,6 @@ impl ClientExporters { .0 .0 .exporters() - .export_organization_vault(collections, ciphers, format) - .map_err(Error::ExportError)?) + .export_organization_vault(collections, ciphers, format)?) } } diff --git a/crates/bitwarden-uniffi/src/tool/sends.rs b/crates/bitwarden-uniffi/src/tool/sends.rs index 1d5a056a3..18732f57c 100644 --- a/crates/bitwarden-uniffi/src/tool/sends.rs +++ b/crates/bitwarden-uniffi/src/tool/sends.rs @@ -1,6 +1,6 @@ use std::{path::Path, sync::Arc}; -use bitwarden::send::{ClientSendsExt, Send, SendListView, SendView}; +use bitwarden_send::{ClientSendsExt, Send, SendListView, SendView}; use crate::{Client, Result}; diff --git a/crates/bitwarden-uniffi/src/uniffi_support.rs b/crates/bitwarden-uniffi/src/uniffi_support.rs index 74f484869..282b03460 100644 --- a/crates/bitwarden-uniffi/src/uniffi_support.rs +++ b/crates/bitwarden-uniffi/src/uniffi_support.rs @@ -4,6 +4,10 @@ use uuid::Uuid; // Forward the type definitions to the main bitwarden crate type DateTime = chrono::DateTime; uniffi::ffi_converter_forward!(DateTime, bitwarden_core::UniFfiTag, crate::UniFfiTag); -uniffi::ffi_converter_forward!(EncString, bitwarden::UniFfiTag, crate::UniFfiTag); -uniffi::ffi_converter_forward!(AsymmetricEncString, bitwarden::UniFfiTag, crate::UniFfiTag); +uniffi::ffi_converter_forward!(EncString, bitwarden_core::UniFfiTag, crate::UniFfiTag); +uniffi::ffi_converter_forward!( + AsymmetricEncString, + bitwarden_core::UniFfiTag, + crate::UniFfiTag +); uniffi::ffi_converter_forward!(Uuid, bitwarden_core::UniFfiTag, crate::UniFfiTag); diff --git a/crates/bitwarden-uniffi/src/vault/attachments.rs b/crates/bitwarden-uniffi/src/vault/attachments.rs index e8bddd124..cb2a011a0 100644 --- a/crates/bitwarden-uniffi/src/vault/attachments.rs +++ b/crates/bitwarden-uniffi/src/vault/attachments.rs @@ -1,6 +1,6 @@ use std::{path::Path, sync::Arc}; -use bitwarden::vault::{ +use bitwarden_vault::{ Attachment, AttachmentEncryptResult, AttachmentView, Cipher, ClientVaultExt, }; diff --git a/crates/bitwarden-uniffi/src/vault/ciphers.rs b/crates/bitwarden-uniffi/src/vault/ciphers.rs index 1195cf81a..fa108af11 100644 --- a/crates/bitwarden-uniffi/src/vault/ciphers.rs +++ b/crates/bitwarden-uniffi/src/vault/ciphers.rs @@ -1,10 +1,6 @@ use std::sync::Arc; -use bitwarden::{ - error::Error, - vault::{Cipher, CipherListView, CipherView, ClientVaultExt}, -}; -use bitwarden_vault::Fido2CredentialView; +use bitwarden_vault::{Cipher, CipherListView, CipherView, ClientVaultExt, Fido2CredentialView}; use uuid::Uuid; use crate::{Client, Result}; @@ -52,7 +48,6 @@ impl ClientCiphers { .0 .vault() .ciphers() - .move_to_organization(cipher, organization_id) - .map_err(Error::Cipher)?) + .move_to_organization(cipher, organization_id)?) } } diff --git a/crates/bitwarden-uniffi/src/vault/collections.rs b/crates/bitwarden-uniffi/src/vault/collections.rs index 84d928e64..250588e8d 100644 --- a/crates/bitwarden-uniffi/src/vault/collections.rs +++ b/crates/bitwarden-uniffi/src/vault/collections.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bitwarden::vault::{ClientVaultExt, Collection, CollectionView}; +use bitwarden_vault::{ClientVaultExt, Collection, CollectionView}; use crate::{Client, Result}; diff --git a/crates/bitwarden-uniffi/src/vault/folders.rs b/crates/bitwarden-uniffi/src/vault/folders.rs index 2efeb1f11..758d09173 100644 --- a/crates/bitwarden-uniffi/src/vault/folders.rs +++ b/crates/bitwarden-uniffi/src/vault/folders.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bitwarden::vault::{ClientVaultExt, Folder, FolderView}; +use bitwarden_vault::{ClientVaultExt, Folder, FolderView}; use crate::{Client, Result}; diff --git a/crates/bitwarden-uniffi/src/vault/mod.rs b/crates/bitwarden-uniffi/src/vault/mod.rs index 4cf840868..c65177ac3 100644 --- a/crates/bitwarden-uniffi/src/vault/mod.rs +++ b/crates/bitwarden-uniffi/src/vault/mod.rs @@ -1,10 +1,6 @@ use std::sync::Arc; -use bitwarden::{ - error::Error, - vault::{ClientVaultExt, TotpResponse}, -}; -use bitwarden_vault::CipherListView; +use bitwarden_vault::{CipherListView, ClientVaultExt, TotpResponse}; use chrono::{DateTime, Utc}; use crate::{error::Result, Client}; @@ -52,12 +48,7 @@ impl ClientVault { /// - OTP Auth URI /// - Steam URI pub fn generate_totp(&self, key: String, time: Option>) -> Result { - Ok(self - .0 - .0 - .vault() - .generate_totp(key, time) - .map_err(Error::Totp)?) + Ok(self.0 .0.vault().generate_totp(key, time)?) } /// Generate a TOTP code from a provided cipher list view. @@ -66,11 +57,6 @@ impl ClientVault { view: CipherListView, time: Option>, ) -> Result { - Ok(self - .0 - .0 - .vault() - .generate_totp_cipher_view(view, time) - .map_err(Error::Totp)?) + Ok(self.0 .0.vault().generate_totp_cipher_view(view, time)?) } } diff --git a/crates/bitwarden-uniffi/src/vault/password_history.rs b/crates/bitwarden-uniffi/src/vault/password_history.rs index 3fa0fd3bc..330e91214 100644 --- a/crates/bitwarden-uniffi/src/vault/password_history.rs +++ b/crates/bitwarden-uniffi/src/vault/password_history.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bitwarden::vault::{ClientVaultExt, PasswordHistory, PasswordHistoryView}; +use bitwarden_vault::{ClientVaultExt, PasswordHistory, PasswordHistoryView}; use crate::{Client, Result}; diff --git a/crates/sdk-schemas/Cargo.toml b/crates/sdk-schemas/Cargo.toml index 8d48cd691..b4dd496a4 100644 --- a/crates/sdk-schemas/Cargo.toml +++ b/crates/sdk-schemas/Cargo.toml @@ -12,11 +12,7 @@ license-file.workspace = true keywords.workspace = true [features] -internal = [ - "bitwarden/internal", - "bitwarden-json/internal", - "bitwarden-uniffi/docs", -] +internal = ["bitwarden/internal", "bitwarden-json/internal"] [dependencies] anyhow = "1.0.82" diff --git a/crates/sdk-schemas/src/main.rs b/crates/sdk-schemas/src/main.rs index 94959fa69..66683256b 100644 --- a/crates/sdk-schemas/src/main.rs +++ b/crates/sdk-schemas/src/main.rs @@ -121,8 +121,5 @@ struct SchemaTypes { fn main() -> Result<()> { write_schema_for!("schema_types", SchemaTypes); - #[cfg(feature = "internal")] - write_schema_for!(bitwarden_uniffi::docs::DocRef); - Ok(()) } From c2a4c85049b1ef22c60423609b7a21388839abe0 Mon Sep 17 00:00:00 2001 From: Hinton Date: Thu, 10 Oct 2024 09:26:55 +0200 Subject: [PATCH 2/5] Stop depending on bitwarden for internal crates --- Cargo.lock | 8 ++-- crates/bitwarden-json/Cargo.toml | 3 +- crates/bitwarden-json/src/client.rs | 14 ------- crates/bitwarden-json/src/command.rs | 46 --------------------- crates/bitwarden-wasm-internal/Cargo.toml | 2 +- crates/bitwarden-wasm/Cargo.toml | 5 +-- crates/bitwarden/Cargo.toml | 20 --------- crates/bitwarden/src/error.rs | 49 ----------------------- crates/bitwarden/src/lib.rs | 29 +------------- crates/bw/Cargo.toml | 4 +- crates/bw/src/auth/login.rs | 6 +-- crates/bw/src/main.rs | 15 ++++--- crates/sdk-schemas/Cargo.toml | 1 - crates/sdk-schemas/src/main.rs | 7 ---- 14 files changed, 20 insertions(+), 189 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 375188c55..d720ced22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -366,12 +366,8 @@ dependencies = [ "bitwarden-api-identity", "bitwarden-core", "bitwarden-crypto", - "bitwarden-exporters", - "bitwarden-fido", "bitwarden-generators", - "bitwarden-send", "bitwarden-sm", - "bitwarden-vault", "thiserror", "uuid", ] @@ -745,9 +741,11 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" name = "bw" version = "0.0.2" dependencies = [ - "bitwarden", "bitwarden-cli", + "bitwarden-core", "bitwarden-crypto", + "bitwarden-generators", + "bitwarden-vault", "clap", "color-eyre", "env_logger", diff --git a/crates/bitwarden-json/Cargo.toml b/crates/bitwarden-json/Cargo.toml index ed1b39580..b5b8052b0 100644 --- a/crates/bitwarden-json/Cargo.toml +++ b/crates/bitwarden-json/Cargo.toml @@ -16,8 +16,7 @@ repository.workspace = true license-file.workspace = true [features] -internal = ["bitwarden/internal"] # Internal testing methods -secrets = ["bitwarden/secrets"] # Secrets manager API +secrets = ["bitwarden/secrets"] # Secrets manager API [dependencies] bitwarden = { workspace = true } diff --git a/crates/bitwarden-json/src/client.rs b/crates/bitwarden-json/src/client.rs index dc84c559d..8da635a29 100644 --- a/crates/bitwarden-json/src/client.rs +++ b/crates/bitwarden-json/src/client.rs @@ -1,5 +1,3 @@ -#[cfg(feature = "internal")] -use bitwarden::vault::ClientVaultExt; use bitwarden::ClientSettings; #[cfg(feature = "secrets")] use bitwarden::{ @@ -54,22 +52,10 @@ impl Client { let client = &self.0; match cmd { - #[cfg(feature = "internal")] - Command::PasswordLogin(req) => client.auth().login_password(&req).await.into_string(), #[cfg(feature = "secrets")] Command::LoginAccessToken(req) => { client.auth().login_access_token(&req).await.into_string() } - #[cfg(feature = "internal")] - Command::GetUserApiKey(req) => { - client.platform().get_user_api_key(req).await.into_string() - } - #[cfg(feature = "internal")] - Command::ApiKeyLogin(req) => client.auth().login_api_key(&req).await.into_string(), - #[cfg(feature = "internal")] - Command::Sync(req) => client.vault().sync(&req).await.into_string(), - #[cfg(feature = "internal")] - Command::Fingerprint(req) => client.platform().fingerprint(&req).into_string(), #[cfg(feature = "secrets")] Command::Secrets(cmd) => match cmd { diff --git a/crates/bitwarden-json/src/command.rs b/crates/bitwarden-json/src/command.rs index 7483b90cf..faaa81776 100644 --- a/crates/bitwarden-json/src/command.rs +++ b/crates/bitwarden-json/src/command.rs @@ -13,38 +13,12 @@ use bitwarden::{ }, }, }; -#[cfg(feature = "internal")] -use bitwarden::{ - auth::login::{ApiKeyLoginRequest, PasswordLoginRequest}, - platform::{FingerprintRequest, SecretVerificationRequest}, - vault::SyncRequest, -}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, JsonSchema, Debug)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub enum Command { - #[cfg(feature = "internal")] - /// Login with username and password - /// - /// This command is for initiating an authentication handshake with Bitwarden. - /// Authorization may fail due to requiring 2fa or captcha challenge completion - /// despite accurate credentials. - /// - /// This command is not capable of handling authentication requiring 2fa or captcha. - /// - /// Returns: [PasswordLoginResponse](bitwarden::auth::login::PasswordLoginResponse) - PasswordLogin(PasswordLoginRequest), - - #[cfg(feature = "internal")] - /// Login with API Key - /// - /// This command is for initiating an authentication handshake with Bitwarden. - /// - /// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) - ApiKeyLogin(ApiKeyLoginRequest), - #[cfg(feature = "secrets")] /// Login with Secrets Manager Access Token /// @@ -53,26 +27,6 @@ pub enum Command { /// Returns: [ApiKeyLoginResponse](bitwarden::auth::login::ApiKeyLoginResponse) LoginAccessToken(AccessTokenLoginRequest), - #[cfg(feature = "internal")] - /// > Requires Authentication - /// Get the API key of the currently authenticated user - /// - /// Returns: [UserApiKeyResponse](bitwarden::platform::UserApiKeyResponse) - GetUserApiKey(SecretVerificationRequest), - - #[cfg(feature = "internal")] - /// Get the user's passphrase - /// - /// Returns: String - Fingerprint(FingerprintRequest), - - #[cfg(feature = "internal")] - /// > Requires Authentication - /// Retrieve all user data, ciphers and organizations the user is a part of - /// - /// Returns: [SyncResponse](bitwarden::vault::SyncResponse) - Sync(SyncRequest), - #[cfg(feature = "secrets")] Secrets(SecretsCommand), #[cfg(feature = "secrets")] diff --git a/crates/bitwarden-wasm-internal/Cargo.toml b/crates/bitwarden-wasm-internal/Cargo.toml index df69015cf..4f68c08d6 100644 --- a/crates/bitwarden-wasm-internal/Cargo.toml +++ b/crates/bitwarden-wasm-internal/Cargo.toml @@ -15,7 +15,7 @@ keywords.workspace = true crate-type = ["cdylib"] [dependencies] -bitwarden = { workspace = true, features = ["internal", "wasm"] } +bitwarden = { workspace = true, features = ["wasm"] } console_error_panic_hook = "0.1.7" console_log = { version = "1.0.0", features = ["color"] } js-sys = "0.3.68" diff --git a/crates/bitwarden-wasm/Cargo.toml b/crates/bitwarden-wasm/Cargo.toml index c4be614d3..fd3c278f8 100644 --- a/crates/bitwarden-wasm/Cargo.toml +++ b/crates/bitwarden-wasm/Cargo.toml @@ -19,10 +19,7 @@ argon2 = { version = ">=0.5.0, <0.6", features = [ "alloc", "zeroize", ], default-features = false } -bitwarden-json = { path = "../bitwarden-json", features = [ - "secrets", - "internal", -] } +bitwarden-json = { path = "../bitwarden-json", features = ["secrets"] } console_error_panic_hook = "0.1.7" console_log = { version = "1.0.0", features = ["color"] } js-sys = "0.3.68" diff --git a/crates/bitwarden/Cargo.toml b/crates/bitwarden/Cargo.toml index 1d09377cf..ba1cdee19 100644 --- a/crates/bitwarden/Cargo.toml +++ b/crates/bitwarden/Cargo.toml @@ -16,25 +16,9 @@ license-file.workspace = true [features] default = ["secrets"] -internal = [ - "bitwarden-core/internal", - "dep:bitwarden-exporters", - "dep:bitwarden-generators", - "dep:bitwarden-send", - "dep:bitwarden-vault", -] # Internal testing methods no-memory-hardening = [ "bitwarden-core/no-memory-hardening", ] # Disable memory hardening features -uniffi = [ - "bitwarden-core/uniffi", - "bitwarden-crypto/uniffi", - "bitwarden-exporters/uniffi", - "bitwarden-fido/uniffi", - "bitwarden-generators/uniffi", - "bitwarden-send/uniffi", - "bitwarden-vault/uniffi", -] # Uniffi bindings secrets = [ "bitwarden-core/secrets", "dep:bitwarden-sm", @@ -47,12 +31,8 @@ bitwarden-api-api = { workspace = true } bitwarden-api-identity = { workspace = true } bitwarden-core = { workspace = true } bitwarden-crypto = { workspace = true } -bitwarden-exporters = { workspace = true, optional = true } -bitwarden-fido = { workspace = true, optional = true } bitwarden-generators = { workspace = true, optional = true } -bitwarden-send = { workspace = true, optional = true } bitwarden-sm = { workspace = true, optional = true } -bitwarden-vault = { workspace = true, optional = true } thiserror = { workspace = true } [dev-dependencies] diff --git a/crates/bitwarden/src/error.rs b/crates/bitwarden/src/error.rs index 06ef09648..87251c4dc 100644 --- a/crates/bitwarden/src/error.rs +++ b/crates/bitwarden/src/error.rs @@ -2,10 +2,6 @@ use std::{borrow::Cow, fmt::Debug}; -#[cfg(feature = "internal")] -use bitwarden_exporters::ExportError; -#[cfg(feature = "internal")] -use bitwarden_generators::{PassphraseError, PasswordError, UsernameError}; use thiserror::Error; #[derive(Debug, Error)] @@ -13,51 +9,6 @@ pub enum Error { #[error(transparent)] Core(#[from] bitwarden_core::Error), - // Generators - #[cfg(feature = "internal")] - #[error(transparent)] - UsernameError(#[from] UsernameError), - #[cfg(feature = "internal")] - #[error(transparent)] - PassphraseError(#[from] PassphraseError), - #[cfg(feature = "internal")] - #[error(transparent)] - PasswordError(#[from] PasswordError), - - // Vault - #[cfg(feature = "internal")] - #[error(transparent)] - Cipher(#[from] bitwarden_vault::CipherError), - #[cfg(feature = "internal")] - #[error(transparent)] - Totp(#[from] bitwarden_vault::TotpError), - - #[cfg(feature = "internal")] - #[error(transparent)] - ExportError(#[from] ExportError), - - // Fido - #[cfg(all(feature = "uniffi", feature = "internal"))] - #[error(transparent)] - MakeCredential(#[from] bitwarden_fido::MakeCredentialError), - #[cfg(all(feature = "uniffi", feature = "internal"))] - #[error(transparent)] - GetAssertion(#[from] bitwarden_fido::GetAssertionError), - #[cfg(all(feature = "uniffi", feature = "internal"))] - #[error(transparent)] - SilentlyDiscoverCredentials(#[from] bitwarden_fido::SilentlyDiscoverCredentialsError), - #[cfg(all(feature = "uniffi", feature = "internal"))] - #[error(transparent)] - CredentialsForAutofillError(#[from] bitwarden_fido::CredentialsForAutofillError), - #[cfg(all(feature = "uniffi", feature = "internal"))] - #[error(transparent)] - DecryptFido2AutofillCredentialsError( - #[from] bitwarden_fido::DecryptFido2AutofillCredentialsError, - ), - #[cfg(all(feature = "uniffi", feature = "internal"))] - #[error(transparent)] - Fido2Client(#[from] bitwarden_fido::Fido2ClientError), - #[error("Internal error: {0}")] Internal(Cow<'static, str>), } diff --git a/crates/bitwarden/src/lib.rs b/crates/bitwarden/src/lib.rs index c87693ce7..77a063f52 100644 --- a/crates/bitwarden/src/lib.rs +++ b/crates/bitwarden/src/lib.rs @@ -61,34 +61,7 @@ mod readme {} pub use bitwarden_core::*; pub mod error; -#[cfg(feature = "internal")] -pub mod internal { - pub mod generators { - pub use bitwarden_generators::*; - } - - pub mod exporters { - pub use bitwarden_exporters::*; - } - - pub mod send { - pub use bitwarden_send::*; - } - - pub mod vault { - pub use bitwarden_vault::*; - } - - #[cfg(feature = "uniffi")] - pub mod fido { - pub use bitwarden_fido::*; - } -} -#[cfg(feature = "internal")] -pub use internal::*; - -// Re-export generators used for secrets-manager, internal flag already exports all generators -#[cfg(all(feature = "secrets", not(feature = "internal")))] +#[cfg(feature = "secrets")] pub mod generators { pub use bitwarden_generators::{ClientGeneratorExt, PasswordError, PasswordGeneratorRequest}; } diff --git a/crates/bw/Cargo.toml b/crates/bw/Cargo.toml index cb8e02ba1..a2ba807c3 100644 --- a/crates/bw/Cargo.toml +++ b/crates/bw/Cargo.toml @@ -14,9 +14,11 @@ repository.workspace = true license-file.workspace = true [dependencies] -bitwarden = { workspace = true, features = ["internal"] } bitwarden-cli = { workspace = true } +bitwarden-core = { workspace = true } bitwarden-crypto = { workspace = true } +bitwarden-generators = { workspace = true } +bitwarden-vault = { workspace = true } clap = { version = "4.5.4", features = ["derive", "env"] } color-eyre = "0.6.3" env_logger = "0.11.1" diff --git a/crates/bw/src/auth/login.rs b/crates/bw/src/auth/login.rs index 51fe64a39..131d39f02 100644 --- a/crates/bw/src/auth/login.rs +++ b/crates/bw/src/auth/login.rs @@ -1,12 +1,12 @@ -use bitwarden::{ +use bitwarden_cli::text_prompt_when_none; +use bitwarden_core::{ auth::login::{ ApiKeyLoginRequest, PasswordLoginRequest, TwoFactorEmailRequest, TwoFactorProvider, TwoFactorRequest, }, - vault::{ClientVaultExt, SyncRequest}, Client, }; -use bitwarden_cli::text_prompt_when_none; +use bitwarden_vault::{ClientVaultExt, SyncRequest}; use color_eyre::eyre::{bail, Result}; use inquire::{Password, Text}; use log::{debug, error, info}; diff --git a/crates/bw/src/main.rs b/crates/bw/src/main.rs index a9a7eeea2..06d5d0bd5 100644 --- a/crates/bw/src/main.rs +++ b/crates/bw/src/main.rs @@ -1,9 +1,8 @@ -use bitwarden::{ - auth::RegisterRequest, - generators::{ClientGeneratorExt, PassphraseGeneratorRequest, PasswordGeneratorRequest}, - ClientSettings, -}; use bitwarden_cli::{install_color_eyre, text_prompt_when_none, Color}; +use bitwarden_core::{auth::RegisterRequest, ClientSettings}; +use bitwarden_generators::{ + ClientGeneratorExt, PassphraseGeneratorRequest, PasswordGeneratorRequest, +}; use clap::{command, Args, CommandFactory, Parser, Subcommand}; use color_eyre::eyre::Result; use inquire::Password; @@ -157,7 +156,7 @@ async fn process_commands() -> Result<()> { identity_url: format!("{}/identity", server), ..Default::default() }); - let client = bitwarden::Client::new(settings); + let client = bitwarden_core::Client::new(settings); match args.command { // FIXME: Rust CLI will not support password login! @@ -188,7 +187,7 @@ async fn process_commands() -> Result<()> { identity_url: format!("{}/identity", server), ..Default::default() }); - let client = bitwarden::Client::new(settings); + let client = bitwarden_core::Client::new(settings); let email = text_prompt_when_none("Email", email)?; let password = Password::new("Password").prompt()?; @@ -207,7 +206,7 @@ async fn process_commands() -> Result<()> { } // Not login, assuming we have a config - let client = bitwarden::Client::new(None); + let client = bitwarden_core::Client::new(None); // And finally we process all the commands which require authentication match command { diff --git a/crates/sdk-schemas/Cargo.toml b/crates/sdk-schemas/Cargo.toml index b4dd496a4..13a664873 100644 --- a/crates/sdk-schemas/Cargo.toml +++ b/crates/sdk-schemas/Cargo.toml @@ -12,7 +12,6 @@ license-file.workspace = true keywords.workspace = true [features] -internal = ["bitwarden/internal", "bitwarden-json/internal"] [dependencies] anyhow = "1.0.82" diff --git a/crates/sdk-schemas/src/main.rs b/crates/sdk-schemas/src/main.rs index 66683256b..2db3ce5fe 100644 --- a/crates/sdk-schemas/src/main.rs +++ b/crates/sdk-schemas/src/main.rs @@ -109,13 +109,6 @@ struct SchemaTypes { projects: Response, projects_delete: Response, password: Response, - - #[cfg(feature = "internal")] - fingerprint: Response, - #[cfg(feature = "internal")] - sync: Response, - #[cfg(feature = "internal")] - user_api_key: Response, } fn main() -> Result<()> { From ae414ea30446c777c01fa431f08a384f50416ccc Mon Sep 17 00:00:00 2001 From: Hinton Date: Thu, 10 Oct 2024 09:45:32 +0200 Subject: [PATCH 3/5] Cleanup unused code in bitwarden crate --- Cargo.lock | 3 --- crates/bitwarden/Cargo.toml | 3 --- crates/bitwarden/src/error.rs | 17 +---------------- 3 files changed, 1 insertion(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d720ced22..b30e3dbd5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -362,10 +362,7 @@ checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" name = "bitwarden" version = "1.0.0" dependencies = [ - "bitwarden-api-api", - "bitwarden-api-identity", "bitwarden-core", - "bitwarden-crypto", "bitwarden-generators", "bitwarden-sm", "thiserror", diff --git a/crates/bitwarden/Cargo.toml b/crates/bitwarden/Cargo.toml index ba1cdee19..3626f9d11 100644 --- a/crates/bitwarden/Cargo.toml +++ b/crates/bitwarden/Cargo.toml @@ -27,10 +27,7 @@ secrets = [ wasm = ["bitwarden-core/wasm"] # WASM support [dependencies] -bitwarden-api-api = { workspace = true } -bitwarden-api-identity = { workspace = true } bitwarden-core = { workspace = true } -bitwarden-crypto = { workspace = true } bitwarden-generators = { workspace = true, optional = true } bitwarden-sm = { workspace = true, optional = true } thiserror = { workspace = true } diff --git a/crates/bitwarden/src/error.rs b/crates/bitwarden/src/error.rs index 87251c4dc..163ccc208 100644 --- a/crates/bitwarden/src/error.rs +++ b/crates/bitwarden/src/error.rs @@ -1,6 +1,6 @@ //! Errors that can occur when using this SDK -use std::{borrow::Cow, fmt::Debug}; +use std::fmt::Debug; use thiserror::Error; @@ -8,21 +8,6 @@ use thiserror::Error; pub enum Error { #[error(transparent)] Core(#[from] bitwarden_core::Error), - - #[error("Internal error: {0}")] - Internal(Cow<'static, str>), -} - -impl From for Error { - fn from(s: String) -> Self { - Self::Internal(s.into()) - } -} - -impl From<&'static str> for Error { - fn from(s: &'static str) -> Self { - Self::Internal(s.into()) - } } // Ensure that the error messages implement Send and Sync From 1285a456903b4947eb53ae281d53c370dca8f93d Mon Sep 17 00:00:00 2001 From: Hinton Date: Thu, 10 Oct 2024 11:38:58 +0200 Subject: [PATCH 4/5] Avoid building internal for bitwarden crate --- .github/workflows/build-rust-crates.yml | 6 - support/docs/docs.ts | 139 ------------------------ support/docs/rustdoc.ts | 12 -- support/docs/template.hbs | 91 ---------------- support/scripts/schemas.ts | 12 -- 5 files changed, 260 deletions(-) delete mode 100644 support/docs/docs.ts delete mode 100644 support/docs/rustdoc.ts delete mode 100644 support/docs/template.hbs diff --git a/.github/workflows/build-rust-crates.yml b/.github/workflows/build-rust-crates.yml index d4116bcf9..8400fcbf6 100644 --- a/.github/workflows/build-rust-crates.yml +++ b/.github/workflows/build-rust-crates.yml @@ -49,12 +49,6 @@ jobs: env: RUSTFLAGS: "-D warnings" - - name: Build Internal - if: ${{ matrix.package == 'bitwarden' }} - run: cargo build -p ${{ matrix.package }} --features internal --release - env: - RUSTFLAGS: "-D warnings" - release-dry-run: name: Release dry-run runs-on: ubuntu-latest diff --git a/support/docs/docs.ts b/support/docs/docs.ts deleted file mode 100644 index 067ff0827..000000000 --- a/support/docs/docs.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Quick script that parses the rustdoc json output and generates a basic markdown documentation. -// -// Do note that this script follows no best practices and will not handle anything many edge cases. - -import fs from "fs"; -import path from "path"; -import Handlebars from "handlebars"; - -import { Input, InputType } from "./rustdoc"; - -const doc = JSON.parse(fs.readFileSync("./target/doc/bitwarden_uniffi.json", "utf8")); -const command = JSON.parse( - fs.readFileSync("./support/schemas/bitwarden_uniffi/DocRef.json", "utf8"), -); - -const template = Handlebars.compile( - fs.readFileSync(path.resolve(__dirname, "template.hbs"), "utf8"), -); - -// Modify this to include more root elements -const rootElements = [ - "Client", - "ClientAuth", - "ClientAttachments", - "ClientCiphers", - "ClientCollections", - "ClientCrypto", - "ClientExporters", - "ClientFolders", - "ClientGenerators", - "ClientPasswordHistory", - "ClientPlatform", - "ClientSends", - "ClientVault", -]; - -const localIndexArray = Object.values(doc.index).filter((entry: any) => entry.crate_id == 0); -const localIndex = localIndexArray.reduce((map: any, obj: any) => { - map[obj.id] = obj; - return map; -}, {}) as Record; - -let usedDefinitions: any[] = []; - -const out = rootElements.map((rootElement) => { - const root: any = localIndexArray.find((entry: any) => entry.name == rootElement); - const impls = root.inner.struct.impls; - - const elements = impls - .flatMap((e: any) => localIndex[e]) - .flatMap((e: any) => e.inner.impl.items) - .map((e: any) => localIndex[e]) - .filter((e: any) => e?.docs != null); - - return { - name: rootElement, - elements: elements.map((e: any) => { - return { - name: e.name, - docs: e.docs, - args: e.inner.function.decl.inputs.map((e: any) => map_input(e)), - output: map_type(e.inner.function.decl.output), - }; - }), - }; -}); - -function stripDef(str: string) { - return str.replace(/#\/definitions\//g, ""); -} - -Handlebars.registerHelper("stripDef", (str: string) => { - return stripDef(str); -}); - -// Add references -for (let i = 0; i < usedDefinitions.length; i++) { - const key = usedDefinitions[i]; - const cmd = command.definitions[key]; - if (cmd == null) { - continue; - } - - Object.entries(cmd.properties ?? {}).forEach((prop: any) => { - prop[1].allOf?.forEach((e: any) => { - usedDefinitions.push(stripDef(e["$ref"] as string)); - }); - }); -} - -const filteredDefinitions = [...new Set(usedDefinitions)] - .sort() - .map((key) => [key, command.definitions[key]]) - .filter((e) => e[1] != null) - .reduce((obj, cur) => ({ ...obj, [cur[0]]: cur[1] }), {}); - -console.log(template({ sections: out, commands: filteredDefinitions })); - -/// -/// Implementation details below. -/// - -// Format -function map_input(input: Input) { - return { - name: input[0], - type: map_type(input[1]), - }; -} - -function map_type(t: InputType) { - const args = t.resolved_path?.args; - const name = t.resolved_path?.name; - - let out = ""; - - if (name) { - usedDefinitions.push(name); - - if (command.definitions[name] != null) { - out += `[${name}](#${name.toLowerCase()})`; - } else { - out += name; - } - } - - if (args != null && args.angle_bracketed.args.length > 0) { - out += "<"; - out += args.angle_bracketed.args.map((t: any) => { - if (t.type.generic) { - return t.type.generic; - } else if (t.type.resolved_path) { - return t.type.resolved_path.name; - } - }); - out += ">"; - } - return out; -} diff --git a/support/docs/rustdoc.ts b/support/docs/rustdoc.ts deleted file mode 100644 index 2622b711e..000000000 --- a/support/docs/rustdoc.ts +++ /dev/null @@ -1,12 +0,0 @@ -export type Input = [string, InputType]; - -export type InputType = { - resolved_path?: { - name: string; - args: { - angle_bracketed: { - args: any[]; - }; - }; - }; -}; diff --git a/support/docs/template.hbs b/support/docs/template.hbs deleted file mode 100644 index bd78d138a..000000000 --- a/support/docs/template.hbs +++ /dev/null @@ -1,91 +0,0 @@ -# Bitwarden Mobile SDK - -Auto generated documentation for the Bitwarden Mobile SDK. For more information please refer to -the rust crates `bitwarden` and `bitwarden-uniffi`. For code samples check the -`languages/kotlin/app` and `languages/swift/app` directories. - -{{#each sections}} - -## {{name}} - -{{#each elements}} -### `{{name}}` -{{docs}} - -**Arguments**: -{{#each args}} -- {{name}}: {{{type}}} -{{/each}} - -**Output**: {{{output}}} - -{{/each}} -{{/each}} - -# References - -References are generated from the JSON schemas and should mostly match the kotlin and swift -implementations. - -{{#each commands}} - -## `{{@key}}` - -{{#if oneOf}} - - - - - - -{{#each oneOf}} -{{#each properties}} - - - - - -{{#if properties}} - - - -{{/if}} -{{/each}} -{{/each}} -
KeyTypeDescription
{{@key}}{{type}}
- - - - - - - {{#each properties}} - - - - - - {{/each}} -
KeyTypeDescription
{{@key}}{{type}}{{{description}}}
-
- -{{/if}} - -{{#unless oneOf}} - - - - - - -{{#each properties}} - - - - - -{{/each}} -
KeyTypeDescription
{{@key}}{{type}}{{description}}
-{{/unless}} - -{{/each}} diff --git a/support/scripts/schemas.ts b/support/scripts/schemas.ts index 3eaad1903..873a9de7d 100644 --- a/support/scripts/schemas.ts +++ b/support/scripts/schemas.ts @@ -7,18 +7,6 @@ import { } from "quicktype-core"; import fs from "fs"; -import path from "path"; - -async function* walk(dir: string): AsyncIterable { - for await (const d of await fs.promises.opendir(dir)) { - const entry = path.join(dir, d.name); - if (d.isDirectory()) { - yield* walk(entry); - } else if (d.isFile()) { - yield entry; - } - } -} async function main() { const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore()); From f4393d6ab6b88a5f69546345fd5edc3f55f33d51 Mon Sep 17 00:00:00 2001 From: Hinton Date: Fri, 11 Oct 2024 10:31:20 +0200 Subject: [PATCH 5/5] Revert error structure --- crates/bitwarden-uniffi/src/error.rs | 41 +++++++++++++++++-- crates/bitwarden-uniffi/src/platform/fido2.rs | 38 +++++++++++++---- crates/bitwarden-uniffi/src/tool/mod.rs | 33 ++++++++++++--- crates/bitwarden-uniffi/src/vault/ciphers.rs | 5 ++- crates/bitwarden-uniffi/src/vault/mod.rs | 19 +++++++-- 5 files changed, 114 insertions(+), 22 deletions(-) diff --git a/crates/bitwarden-uniffi/src/error.rs b/crates/bitwarden-uniffi/src/error.rs index abcd4a4f5..889e3c7fb 100644 --- a/crates/bitwarden-uniffi/src/error.rs +++ b/crates/bitwarden-uniffi/src/error.rs @@ -1,11 +1,48 @@ +use std::fmt::{Display, Formatter}; + use bitwarden_exporters::ExportError; use bitwarden_generators::{PassphraseError, PasswordError, UsernameError}; // Name is converted from *Error to *Exception, so we can't just name the enum Error because // Exception already exists -#[derive(uniffi::Error, thiserror::Error, Debug)] +#[derive(uniffi::Error, Debug)] #[uniffi(flat_error)] pub enum BitwardenError { + E(Error), +} + +impl From for BitwardenError { + fn from(e: bitwarden_core::Error) -> Self { + Self::E(e.into()) + } +} + +impl From for BitwardenError { + fn from(e: Error) -> Self { + Self::E(e) + } +} + +impl Display for BitwardenError { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + Self::E(e) => Display::fmt(e, f), + } + } +} + +impl std::error::Error for BitwardenError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + BitwardenError::E(e) => Some(e), + } + } +} + +pub type Result = std::result::Result; + +#[derive(thiserror::Error, Debug)] +pub enum Error { #[error(transparent)] Core(#[from] bitwarden_core::Error), @@ -42,5 +79,3 @@ pub enum BitwardenError { #[error(transparent)] Fido2Client(#[from] bitwarden_fido::Fido2ClientError), } - -pub type Result = std::result::Result; diff --git a/crates/bitwarden-uniffi/src/platform/fido2.rs b/crates/bitwarden-uniffi/src/platform/fido2.rs index e484f5f2e..99c998648 100644 --- a/crates/bitwarden-uniffi/src/platform/fido2.rs +++ b/crates/bitwarden-uniffi/src/platform/fido2.rs @@ -9,7 +9,10 @@ use bitwarden_fido::{ }; use bitwarden_vault::{Cipher, CipherView, Fido2CredentialNewView}; -use crate::{error::Result, Client}; +use crate::{ + error::{Error, Result}, + Client, +}; #[derive(uniffi::Object)] pub struct ClientFido2(pub(crate) Arc); @@ -48,7 +51,8 @@ impl ClientFido2 { .0 .0 .fido2() - .decrypt_fido2_autofill_credentials(cipher_view)?; + .decrypt_fido2_autofill_credentials(cipher_view) + .map_err(Error::DecryptFido2AutofillCredentialsError)?; Ok(result) } @@ -72,7 +76,10 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth.make_credential(request).await?; + let result = auth + .make_credential(request) + .await + .map_err(Error::MakeCredential)?; Ok(result) } @@ -82,7 +89,10 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth.get_assertion(request).await?; + let result = auth + .get_assertion(request) + .await + .map_err(Error::GetAssertion)?; Ok(result) } @@ -96,7 +106,10 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth.silently_discover_credentials(rp_id).await?; + let result = auth + .silently_discover_credentials(rp_id) + .await + .map_err(Error::SilentlyDiscoverCredentials)?; Ok(result) } @@ -106,7 +119,10 @@ impl ClientFido2Authenticator { let cs = UniffiTraitBridge(self.2.as_ref()); let mut auth = fido2.create_authenticator(&ui, &cs); - let result = auth.credentials_for_autofill().await?; + let result = auth + .credentials_for_autofill() + .await + .map_err(Error::CredentialsForAutofillError)?; Ok(result) } } @@ -127,7 +143,10 @@ impl ClientFido2Client { let cs = UniffiTraitBridge(self.0 .2.as_ref()); let mut client = fido2.create_client(&ui, &cs); - let result = client.register(origin, request, client_data).await?; + let result = client + .register(origin, request, client_data) + .await + .map_err(Error::Fido2Client)?; Ok(result) } @@ -142,7 +161,10 @@ impl ClientFido2Client { let cs = UniffiTraitBridge(self.0 .2.as_ref()); let mut client = fido2.create_client(&ui, &cs); - let result = client.authenticate(origin, request, client_data).await?; + let result = client + .authenticate(origin, request, client_data) + .await + .map_err(Error::Fido2Client)?; Ok(result) } } diff --git a/crates/bitwarden-uniffi/src/tool/mod.rs b/crates/bitwarden-uniffi/src/tool/mod.rs index 4b96c37d1..498884218 100644 --- a/crates/bitwarden-uniffi/src/tool/mod.rs +++ b/crates/bitwarden-uniffi/src/tool/mod.rs @@ -7,7 +7,10 @@ use bitwarden_generators::{ }; use bitwarden_vault::{Cipher, Collection, Folder}; -use crate::{error::Result, Client}; +use crate::{ + error::{Error, Result}, + Client, +}; mod sends; pub use sends::ClientSends; @@ -19,17 +22,33 @@ pub struct ClientGenerators(pub(crate) Arc); impl ClientGenerators { /// **API Draft:** Generate Password pub fn password(&self, settings: PasswordGeneratorRequest) -> Result { - Ok(self.0 .0.generator().password(settings)?) + Ok(self + .0 + .0 + .generator() + .password(settings) + .map_err(Error::PasswordError)?) } /// **API Draft:** Generate Passphrase pub fn passphrase(&self, settings: PassphraseGeneratorRequest) -> Result { - Ok(self.0 .0.generator().passphrase(settings)?) + Ok(self + .0 + .0 + .generator() + .passphrase(settings) + .map_err(Error::PassphraseError)?) } /// **API Draft:** Generate Username pub async fn username(&self, settings: UsernameGeneratorRequest) -> Result { - Ok(self.0 .0.generator().username(settings).await?) + Ok(self + .0 + .0 + .generator() + .username(settings) + .await + .map_err(Error::UsernameError)?) } } @@ -49,7 +68,8 @@ impl ClientExporters { .0 .0 .exporters() - .export_vault(folders, ciphers, format)?) + .export_vault(folders, ciphers, format) + .map_err(Error::ExportError)?) } /// **API Draft:** Export organization vault @@ -63,6 +83,7 @@ impl ClientExporters { .0 .0 .exporters() - .export_organization_vault(collections, ciphers, format)?) + .export_organization_vault(collections, ciphers, format) + .map_err(Error::ExportError)?) } } diff --git a/crates/bitwarden-uniffi/src/vault/ciphers.rs b/crates/bitwarden-uniffi/src/vault/ciphers.rs index fa108af11..64751b37c 100644 --- a/crates/bitwarden-uniffi/src/vault/ciphers.rs +++ b/crates/bitwarden-uniffi/src/vault/ciphers.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bitwarden_vault::{Cipher, CipherListView, CipherView, ClientVaultExt, Fido2CredentialView}; use uuid::Uuid; -use crate::{Client, Result}; +use crate::{error::Error, Client, Result}; #[derive(uniffi::Object)] pub struct ClientCiphers(pub Arc); @@ -48,6 +48,7 @@ impl ClientCiphers { .0 .vault() .ciphers() - .move_to_organization(cipher, organization_id)?) + .move_to_organization(cipher, organization_id) + .map_err(Error::Cipher)?) } } diff --git a/crates/bitwarden-uniffi/src/vault/mod.rs b/crates/bitwarden-uniffi/src/vault/mod.rs index c65177ac3..cec625e33 100644 --- a/crates/bitwarden-uniffi/src/vault/mod.rs +++ b/crates/bitwarden-uniffi/src/vault/mod.rs @@ -3,7 +3,10 @@ use std::sync::Arc; use bitwarden_vault::{CipherListView, ClientVaultExt, TotpResponse}; use chrono::{DateTime, Utc}; -use crate::{error::Result, Client}; +use crate::{ + error::{Error, Result}, + Client, +}; pub mod attachments; pub mod ciphers; @@ -48,7 +51,12 @@ impl ClientVault { /// - OTP Auth URI /// - Steam URI pub fn generate_totp(&self, key: String, time: Option>) -> Result { - Ok(self.0 .0.vault().generate_totp(key, time)?) + Ok(self + .0 + .0 + .vault() + .generate_totp(key, time) + .map_err(Error::Totp)?) } /// Generate a TOTP code from a provided cipher list view. @@ -57,6 +65,11 @@ impl ClientVault { view: CipherListView, time: Option>, ) -> Result { - Ok(self.0 .0.vault().generate_totp_cipher_view(view, time)?) + Ok(self + .0 + .0 + .vault() + .generate_totp_cipher_view(view, time) + .map_err(Error::Totp)?) } }