Skip to content

Commit

Permalink
Merge branch 'main' of github.com:bitwarden/sdk into ps/core
Browse files Browse the repository at this point in the history
# Conflicts:
#	crates/bitwarden-core/README.md
#	crates/bitwarden-json/src/client.rs
#	crates/bitwarden-vault/src/cipher/cipher.rs
#	crates/bw/src/main.rs
  • Loading branch information
Hinton committed Jun 17, 2024
2 parents a2928e4 + 331c321 commit a6faee8
Show file tree
Hide file tree
Showing 14 changed files with 122 additions and 27 deletions.
6 changes: 6 additions & 0 deletions crates/bitwarden-cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Bitwarden Cli

This is an internal crate for the Bitwarden SDK do not depend on this directly and use the
[`bitwarden`](https://crates.io/crates/bitwarden) crate instead.

This crate does not follow semantic versioning and the public interface may change at any time.
7 changes: 2 additions & 5 deletions crates/bitwarden-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,8 @@ Rust **1.71** or higher.

```rust
use bitwarden::{
auth::login::AccessTokenLoginRequest,
client::client_settings::{ClientSettings, DeviceType},
error::Result,
secrets_manager::secrets::SecretIdentifiersRequest,
Client,
auth::login::AccessTokenLoginRequest, error::Result,
secrets_manager::secrets::SecretIdentifiersRequest, Client, ClientSettings, DeviceType,
};
use uuid::Uuid;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{
auth::api::response::IdentityTokenResponse,
client::{client_settings::DeviceType, ApiConfigurations},
error::Result,
auth::api::response::IdentityTokenResponse, client::ApiConfigurations, error::Result,
DeviceType,
};

#[derive(Serialize, Deserialize, Debug)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ use crate::{
api::response::IdentityTokenResponse,
login::{TwoFactorProvider, TwoFactorRequest},
},
client::{client_settings::DeviceType, ApiConfigurations},
client::ApiConfigurations,
error::Result,
DeviceType,
};

#[derive(Serialize, Deserialize, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden-core/src/auth/login/password.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ async fn request_identity_tokens(
input: &PasswordLoginRequest,
password_hash: &str,
) -> Result<IdentityTokenResponse> {
use crate::client::client_settings::DeviceType;
use crate::DeviceType;

let config = client.internal.get_api_configurations().await;
PasswordTokenRequest::new(
Expand Down
2 changes: 1 addition & 1 deletion crates/bitwarden-core/src/client/client_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
/// Defaults to
///
/// ```
/// # use bitwarden::client::client_settings::{ClientSettings, DeviceType};
/// # use bitwarden::{ClientSettings, DeviceType};
/// let settings = ClientSettings {
/// identity_url: "https://identity.bitwarden.com".to_string(),
/// api_url: "https://api.bitwarden.com".to_string(),
Expand Down
4 changes: 2 additions & 2 deletions crates/bitwarden-core/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ pub async fn start_mock(mocks: Vec<wiremock::Mock>) -> (wiremock::MockServer, cr
server.register(mock).await;
}

let settings = crate::client::client_settings::ClientSettings {
let settings = crate::ClientSettings {
identity_url: format!("http://{}/identity", server.address()),
api_url: format!("http://{}/api", server.address()),
user_agent: "Bitwarden Rust-SDK [TEST]".into(),
device_type: crate::client::client_settings::DeviceType::SDK,
device_type: crate::DeviceType::SDK,
};

(server, crate::Client::new(Some(settings)))
Expand Down
6 changes: 6 additions & 0 deletions crates/bitwarden-fido/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Bitwarden Fido

This is an internal crate for the Bitwarden SDK do not depend on this directly and use the
[`bitwarden`](https://crates.io/crates/bitwarden) crate instead.

This crate does not follow semantic versioning and the public interface may change at any time.
5 changes: 4 additions & 1 deletion crates/bitwarden-send/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ base64 = ">=0.21.2, <0.23"
bitwarden-api-api = { workspace = true }
bitwarden-core = { workspace = true }
bitwarden-crypto = { workspace = true }
chrono = { version = ">=0.4.26, <0.5", default-features = false }
chrono = { version = ">=0.4.26, <0.5", features = [
"clock",
"serde",
], default-features = false }
schemars = { version = ">=0.8.9, <0.9", features = ["uuid1", "chrono"] }
serde = { version = ">=1.0, <2.0", features = ["derive"] }
serde_repr = ">=0.1.12, <0.2"
Expand Down
5 changes: 4 additions & 1 deletion crates/bitwarden-vault/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ base64 = ">=0.21.2, <0.23"
bitwarden-api-api = { workspace = true }
bitwarden-core = { workspace = true }
bitwarden-crypto = { workspace = true }
chrono = { version = ">=0.4.26, <0.5", default-features = false }
chrono = { version = ">=0.4.26, <0.5", features = [
"clock",
"serde",
], default-features = false }
rand = ">=0.8.5, <0.9"
hmac = ">=0.12.1, <0.13"
reqwest = { version = ">=0.12, <0.13", default-features = false }
Expand Down
6 changes: 6 additions & 0 deletions crates/bitwarden-vault/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Bitwarden Vault

This is an internal crate for the Bitwarden SDK do not depend on this directly and use the
[`bitwarden`](https://crates.io/crates/bitwarden) crate instead.

This crate does not follow semantic versioning and the public interface may change at any time.
87 changes: 84 additions & 3 deletions crates/bitwarden-vault/src/cipher/attachment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,29 @@ impl<'a> KeyEncryptable<SymmetricCryptoKey, AttachmentEncryptResult> for Attachm
let encrypted_contents = self.contents.encrypt_with_key(&attachment_key)?;
attachment.key = Some(attachment_key.to_vec().encrypt_with_key(ciphers_key)?);

let contents = encrypted_contents.to_buffer()?;

// Once we have the encrypted contents, we can set the size of the attachment
attachment.size = Some(contents.len().to_string());
attachment.size_name = Some(size_name(contents.len()));

Ok(AttachmentEncryptResult {
attachment: attachment.encrypt_with_key(ciphers_key)?,
contents: encrypted_contents.to_buffer()?,
contents,
})
}
}

fn size_name(size: usize) -> String {
let units = ["Bytes", "KB", "MB", "GB", "TB"];
let size = size as f64;
let unit = (size.ln() / 1024_f64.ln()).floor() as usize;
let size = size / 1024_f64.powi(unit as i32);

let size_round = (size * 10.0_f64).round() as usize as f64 / 10.0_f64;
format!("{} {}", size_round, units[unit])
}

impl KeyDecryptable<SymmetricCryptoKey, Vec<u8>> for AttachmentFile {
fn decrypt_with_key(&self, key: &SymmetricCryptoKey) -> Result<Vec<u8>, CryptoError> {
let ciphers_key = Cipher::get_cipher_key(key, &self.cipher.key)?;
Expand Down Expand Up @@ -144,13 +160,78 @@ impl TryFrom<bitwarden_api_api::models::AttachmentResponseModel> for Attachment
#[cfg(test)]
mod tests {
use base64::{engine::general_purpose::STANDARD, Engine};
use bitwarden_crypto::{EncString, KeyDecryptable, SymmetricCryptoKey};
use bitwarden_crypto::{EncString, KeyDecryptable, KeyEncryptable, SymmetricCryptoKey};

use crate::{
cipher::cipher::{CipherRepromptType, CipherType},
Attachment, AttachmentFile, Cipher,
Attachment, AttachmentFile, AttachmentFileView, AttachmentView, Cipher,
};

#[test]
fn test_size_name_conversions() {
assert_eq!(super::size_name(0), "0 Bytes");
assert_eq!(super::size_name(19), "19 Bytes");
assert_eq!(super::size_name(1024), "1 KB");
assert_eq!(super::size_name(1570), "1.5 KB");
assert_eq!(super::size_name(1024 * 1024), "1 MB");
assert_eq!(super::size_name(1024 * 18999), "18.6 MB");
assert_eq!(super::size_name(1024 * 1024 * 1024), "1 GB");
assert_eq!(super::size_name(1024 * 1024 * 1024 * 1024), "1 TB");
}

#[test]
fn test_encrypt_attachment() {
let user_key: SymmetricCryptoKey = "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==".to_string().try_into().unwrap();

let attachment = AttachmentView {
id: None,
url: None,
size: Some("100".into()),
size_name: Some("100 Bytes".into()),
file_name: Some("Test.txt".into()),
key: None,
};

let contents = b"This is a test file that we will encrypt. It's 100 bytes long, the encrypted version will be longer!";

let attachment_file = AttachmentFileView {
cipher: Cipher {
id: None,
organization_id: None,
folder_id: None,
collection_ids: Vec::new(),
key: Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".parse().unwrap()),
name: "2.d24xECyEdMZ3MG9s6SrGNw==|XvJlTeu5KJ22M3jKosy6iw==|8xGiQty4X61cDMx6PVqkJfSQ0ZTdA/5L9TpG7QfovoM=".parse().unwrap(),
notes: None,
r#type: CipherType::Login,
login: None,
identity: None,
card: None,
secure_note: None,
favorite: false,
reprompt: CipherRepromptType::None,
organization_use_totp: false,
edit: true,
view_password: true,
local_data: None,
attachments: None,
fields: None,
password_history: None,
creation_date: "2023-07-24T12:05:09.466666700Z".parse().unwrap(),
deleted_date: None,
revision_date: "2023-07-27T19:28:05.240Z".parse().unwrap(),
},
attachment,
contents: contents.as_slice(),
};

let result = attachment_file.encrypt_with_key(&user_key).unwrap();

assert_eq!(result.contents.len(), 161);
assert_eq!(result.attachment.size, Some("161".into()));
assert_eq!(result.attachment.size_name, Some("161 Bytes".into()));
}

#[test]
fn test_attachment_key() {
let user_key: SymmetricCryptoKey = "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==".to_string().try_into().unwrap();
Expand Down
3 changes: 0 additions & 3 deletions crates/bitwarden-vault/src/cipher/cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,6 @@ impl CipherView {
Ok(())
}

#[cfg(feature = "uniffi")]
pub fn decrypt_fido2_credentials(
&self,
enc: &dyn KeyContainer,
Expand Down Expand Up @@ -458,7 +457,6 @@ impl CipherView {
Ok(())
}

#[cfg(feature = "uniffi")]
pub fn set_new_fido2_credentials(
&mut self,
enc: &dyn KeyContainer,
Expand All @@ -475,7 +473,6 @@ impl CipherView {
Ok(())
}

#[cfg(feature = "uniffi")]
pub fn get_fido2_credentials(
&self,
enc: &dyn KeyContainer,
Expand Down
8 changes: 2 additions & 6 deletions crates/bitwarden/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,8 @@ use uuid::Uuid;
#[cfg(feature = "internal")]
use crate::client::flags::Flags;
use crate::{
auth::AccessToken,
client::{
client_settings::{ClientSettings, DeviceType},
encryption_settings::EncryptionSettings,
},
error::Result,
auth::AccessToken, client::encryption_settings::EncryptionSettings, error::Result,
ClientSettings, DeviceType,
};

#[derive(Debug, Clone)]
Expand Down

0 comments on commit a6faee8

Please sign in to comment.