Skip to content
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
13 changes: 13 additions & 0 deletions crates/bitwarden-vault/src/cipher/card.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,19 @@ impl TryFrom<CipherCardModel> for Card {
}
}

impl From<Card> for bitwarden_api_api::models::CipherCardModel {
fn from(card: Card) -> Self {
Self {
cardholder_name: card.cardholder_name.map(|n| n.to_string()),
brand: card.brand.map(|b| b.to_string()),
number: card.number.map(|n| n.to_string()),
exp_month: card.exp_month.map(|m| m.to_string()),
exp_year: card.exp_year.map(|y| y.to_string()),
code: card.code.map(|c| c.to_string()),
}
}
}

impl CipherKind for Card {
fn decrypt_subtitle(
&self,
Expand Down
254 changes: 252 additions & 2 deletions crates/bitwarden-vault/src/cipher/cipher.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
use bitwarden_api_api::models::CipherDetailsResponseModel;
use bitwarden_api_api::{
apis::ciphers_api::{PutShareError, PutShareManyError},
models::{
CipherDetailsResponseModel, CipherRequestModel, CipherResponseModel,
CipherWithIdRequestModel,
},
};
use bitwarden_collections::collection::CollectionId;
use bitwarden_core::{
key_management::{KeyIds, SymmetricKeyId},
Expand All @@ -9,8 +15,9 @@ use bitwarden_crypto::{
PrimitiveEncryptable,
};
use bitwarden_error::bitwarden_error;
use bitwarden_state::repository::RepositoryError;
use bitwarden_uuid::uuid_newtype;
use chrono::{DateTime, Utc};
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use thiserror::Error;
Expand Down Expand Up @@ -45,8 +52,20 @@ pub enum CipherError {
Crypto(#[from] CryptoError),
#[error(transparent)]
Encrypt(#[from] EncryptError),
#[error(transparent)]
VaultParse(#[from] VaultParseError),
// #[error(transparent)]
// Api
#[error("This cipher contains attachments without keys. Those attachments will need to be reuploaded to complete the operation")]
AttachmentsWithoutKeys,
#[error("This cipher cannot be moved to the specified organization")]
OrganizationAlreadySet,
#[error(transparent)]
PutShare(#[from] bitwarden_api_api::apis::Error<PutShareError>),
#[error(transparent)]
PutShareMany(#[from] bitwarden_api_api::apis::Error<PutShareManyError>),
#[error(transparent)]
Repository(#[from] RepositoryError),
}

/// Helper trait for operations on cipher types.
Expand Down Expand Up @@ -85,6 +104,15 @@ pub enum CipherRepromptType {
Password = 1,
}

impl From<CipherRepromptType> for bitwarden_api_api::models::CipherRepromptType {
fn from(t: CipherRepromptType) -> Self {
match t {
CipherRepromptType::None => bitwarden_api_api::models::CipherRepromptType::None,
CipherRepromptType::Password => bitwarden_api_api::models::CipherRepromptType::Password,
}
}
}

#[allow(missing_docs)]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
Expand All @@ -97,6 +125,148 @@ pub struct EncryptionContext {
pub cipher: Cipher,
}

impl TryFrom<EncryptionContext> for CipherWithIdRequestModel {
type Error = CipherError;
fn try_from(
EncryptionContext {
cipher,
encrypted_for,
}: EncryptionContext,
) -> Result<Self, Self::Error> {
Ok(Self {
id: require!(cipher.id).into(),
encrypted_for: Some(encrypted_for.into()),
r#type: Some(cipher.r#type.into()),
organization_id: cipher.organization_id.map(|o| o.to_string()),
folder_id: cipher.folder_id.as_ref().map(ToString::to_string),
favorite: cipher.favorite.into(),
reprompt: Some(cipher.reprompt.into()),
key: cipher.key.map(|k| k.to_string()),
name: cipher.name.to_string(),
notes: cipher.notes.map(|n| n.to_string()),
fields: Some(
cipher
.fields
.into_iter()
.flatten()
.map(Into::into)
.collect(),
),
password_history: Some(
cipher
.password_history
.into_iter()
.flatten()
.map(Into::into)
.collect(),
),
attachments: None,
attachments2: Some(
cipher
.attachments
.into_iter()
.flatten()
.filter_map(|a| {
a.id.map(|id| {
(
id,
bitwarden_api_api::models::CipherAttachmentModel {
file_name: a.file_name.map(|n| n.to_string()),
key: a.key.map(|k| k.to_string()),
},
)
})
})
.collect(),
),
login: cipher.login.map(|l| Box::new(l.into())),
card: cipher.card.map(|c| Box::new(c.into())),
identity: cipher.identity.map(|i| Box::new(i.into())),
secure_note: cipher.secure_note.map(|s| Box::new(s.into())),
ssh_key: cipher.ssh_key.map(|s| Box::new(s.into())),
data: None, // TODO: Consume this instead of the individual fields above.
last_known_revision_date: Some(
cipher
.revision_date
.to_rfc3339_opts(SecondsFormat::Millis, true),
),
archived_date: cipher
.archived_date
.map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)),
})
}
}

impl From<EncryptionContext> for CipherRequestModel {
fn from(
EncryptionContext {
cipher,
encrypted_for,
}: EncryptionContext,
) -> Self {
Self {
encrypted_for: Some(encrypted_for.into()),
r#type: Some(cipher.r#type.into()),
organization_id: cipher.organization_id.map(|o| o.to_string()),
folder_id: cipher.folder_id.as_ref().map(ToString::to_string),
favorite: cipher.favorite.into(),
reprompt: Some(cipher.reprompt.into()),
key: cipher.key.map(|k| k.to_string()),
name: cipher.name.to_string(),
notes: cipher.notes.map(|n| n.to_string()),
fields: Some(
cipher
.fields
.into_iter()
.flatten()
.map(Into::into)
.collect(),
),
password_history: Some(
cipher
.password_history
.into_iter()
.flatten()
.map(Into::into)
.collect(),
),
attachments: None,
attachments2: Some(
cipher
.attachments
.into_iter()
.flatten()
.filter_map(|a| {
a.id.map(|id| {
(
id,
bitwarden_api_api::models::CipherAttachmentModel {
file_name: a.file_name.map(|n| n.to_string()),
key: a.key.map(|k| k.to_string()),
},
)
})
})
.collect(),
),
login: cipher.login.map(|l| Box::new(l.into())),
card: cipher.card.map(|c| Box::new(c.into())),
identity: cipher.identity.map(|i| Box::new(i.into())),
secure_note: cipher.secure_note.map(|s| Box::new(s.into())),
ssh_key: cipher.ssh_key.map(|s| Box::new(s.into())),
data: None, // TODO: Consume this instead of the individual fields above.
last_known_revision_date: Some(
cipher
.revision_date
.to_rfc3339_opts(SecondsFormat::Millis, true),
),
archived_date: cipher
.archived_date
.map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)),
}
}
}

#[allow(missing_docs)]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
Expand Down Expand Up @@ -692,6 +862,24 @@ impl Decryptable<KeyIds, SymmetricKeyId, CipherListView> for Cipher {
}
}

#[cfg(feature = "wasm")]
impl wasm_bindgen::__rt::VectorIntoJsValue for Cipher {
fn vector_into_jsvalue(
vector: wasm_bindgen::__rt::std::boxed::Box<[Self]>,
) -> wasm_bindgen::JsValue {
wasm_bindgen::__rt::js_value_vector_into_jsvalue(vector)
}
}

#[cfg(feature = "wasm")]
impl wasm_bindgen::__rt::VectorIntoJsValue for CipherView {
fn vector_into_jsvalue(
vector: wasm_bindgen::__rt::std::boxed::Box<[Self]>,
) -> wasm_bindgen::JsValue {
wasm_bindgen::__rt::js_value_vector_into_jsvalue(vector)
}
}

impl IdentifyKey<SymmetricKeyId> for Cipher {
fn key_identifier(&self) -> SymmetricKeyId {
match self.organization_id {
Expand Down Expand Up @@ -793,6 +981,68 @@ impl From<bitwarden_api_api::models::CipherRepromptType> for CipherRepromptType
}
}

impl From<CipherType> for bitwarden_api_api::models::CipherType {
fn from(t: CipherType) -> Self {
match t {
CipherType::Login => bitwarden_api_api::models::CipherType::Login,
CipherType::SecureNote => bitwarden_api_api::models::CipherType::SecureNote,
CipherType::Card => bitwarden_api_api::models::CipherType::Card,
CipherType::Identity => bitwarden_api_api::models::CipherType::Identity,
CipherType::SshKey => bitwarden_api_api::models::CipherType::SSHKey,
}
}
}

impl TryFrom<CipherResponseModel> for Cipher {
type Error = VaultParseError;

fn try_from(cipher: CipherResponseModel) -> Result<Self, Self::Error> {
Ok(Self {
id: cipher.id.map(CipherId::new),
organization_id: cipher.organization_id.map(OrganizationId::new),
folder_id: cipher.folder_id.map(FolderId::new),
collection_ids: vec![], // CipherResponseModel doesn't include collection_ids
name: require!(EncString::try_from_optional(cipher.name)?),
notes: EncString::try_from_optional(cipher.notes)?,
r#type: require!(cipher.r#type).into(),
login: cipher.login.map(|l| (*l).try_into()).transpose()?,
identity: cipher.identity.map(|i| (*i).try_into()).transpose()?,
card: cipher.card.map(|c| (*c).try_into()).transpose()?,
secure_note: cipher.secure_note.map(|s| (*s).try_into()).transpose()?,
// TODO: add ssh_key
ssh_key: None,
favorite: cipher.favorite.unwrap_or(false),
reprompt: cipher
.reprompt
.map(|r| r.into())
.unwrap_or(CipherRepromptType::None),
organization_use_totp: cipher.organization_use_totp.unwrap_or(true),
edit: cipher.edit.unwrap_or(true),
// TODO: add permissions
permissions: None,
view_password: cipher.view_password.unwrap_or(true),
local_data: None, // Not sent from server
attachments: cipher
.attachments
.map(|a| a.into_iter().map(|a| a.try_into()).collect())
.transpose()?,
fields: cipher
.fields
.map(|f| f.into_iter().map(|f| f.try_into()).collect())
.transpose()?,
password_history: cipher
.password_history
.map(|p| p.into_iter().map(|p| p.try_into()).collect())
.transpose()?,
creation_date: require!(cipher.creation_date).parse()?,
deleted_date: cipher.deleted_date.map(|d| d.parse()).transpose()?,
revision_date: require!(cipher.revision_date).parse()?,
key: EncString::try_from_optional(cipher.key)?,
archived_date: cipher.archived_date.map(|d| d.parse()).transpose()?,
})
}
}

#[cfg(test)]
mod tests {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::sync::Arc;

use bitwarden_core::{key_management::SymmetricKeyId, Client, OrganizationId};
use bitwarden_crypto::{CompositeEncryptable, IdentifyKey, SymmetricCryptoKey};
#[cfg(feature = "wasm")]
use bitwarden_encoding::B64;
use bitwarden_state::repository::{Repository, RepositoryError};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

Expand All @@ -11,6 +14,8 @@ use crate::{
DecryptError, EncryptError, Fido2CredentialFullView,
};

mod share_cipher;

#[allow(missing_docs)]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct CiphersClient {
Expand Down Expand Up @@ -174,8 +179,15 @@ impl CiphersClient {
let decrypted_key = cipher_view.decrypt_fido2_private_key(&mut key_store.context())?;
Ok(decrypted_key)
}
}

fn get_repository(&self) -> Result<Arc<dyn Repository<Cipher>>, RepositoryError> {
Ok(self
.client
.platform()
.state()
.get_client_managed::<Cipher>()?)
}
}
#[cfg(test)]
mod tests {

Expand Down
Loading