Skip to main content

bitwarden_vault/cipher/blob/conversions/
mod.rs

1use bitwarden_crypto::CryptoError;
2
3use super::v1::*;
4use crate::{
5    CipherView, PasswordHistoryView,
6    cipher::{
7        bank_account::BankAccountView,
8        card::CardView,
9        cipher::CipherType,
10        drivers_license::DriversLicenseView,
11        field::FieldView,
12        identity::IdentityView,
13        login::{Fido2CredentialFullView, Fido2CredentialView, LoginUriView, LoginView},
14        passport::PassportView,
15        secure_note::SecureNoteView,
16        ssh_key::SshKeyView,
17    },
18};
19
20fn none_if_empty<T>(v: Vec<T>) -> Option<Vec<T>> {
21    if v.is_empty() { None } else { Some(v) }
22}
23
24/// Generates bidirectional `From` impls between two types that share
25/// identical field names. Every field is `.clone()`d.
26macro_rules! impl_bidirectional_from {
27    ($type_a:ty, $type_b:ty, [$($field:ident),+ $(,)?]) => {
28        impl From<&$type_a> for $type_b {
29            fn from(src: &$type_a) -> Self {
30                Self { $($field: src.$field.clone()),+ }
31            }
32        }
33        impl From<&$type_b> for $type_a {
34            fn from(src: &$type_b) -> Self {
35                Self { $($field: src.$field.clone()),+ }
36            }
37        }
38    };
39}
40
41impl_bidirectional_from!(FieldView, FieldDataV1, [name, value, r#type, linked_id,]);
42
43impl_bidirectional_from!(
44    PasswordHistoryView,
45    PasswordHistoryDataV1,
46    [password, last_used_date,]
47);
48
49mod bank_account;
50mod card;
51mod drivers_license;
52mod identity;
53mod login;
54mod passport;
55mod secure_note;
56mod ssh_key;
57
58impl CipherBlobV1 {
59    pub(crate) fn from_cipher_view(view: &CipherView) -> Result<Self, CryptoError> {
60        let type_data = match view.r#type {
61            CipherType::Login => {
62                let login = view
63                    .login
64                    .as_ref()
65                    .ok_or(CryptoError::MissingField("login"))?;
66
67                let fido2_credentials = login
68                    .fido2_credentials
69                    .as_deref()
70                    .map(|creds| {
71                        creds
72                            .iter()
73                            .map(|v| {
74                                Fido2CredentialDataV1::from(&Fido2CredentialFullView::from(
75                                    v.clone(),
76                                ))
77                            })
78                            .collect()
79                    })
80                    .unwrap_or_default();
81
82                CipherTypeDataV1::Login(LoginDataV1 {
83                    username: login.username.clone(),
84                    password: login.password.clone(),
85                    password_revision_date: login.password_revision_date,
86                    uris: login
87                        .uris
88                        .as_ref()
89                        .map(|u| u.iter().map(LoginUriDataV1::from).collect())
90                        .unwrap_or_default(),
91                    totp: login.totp.clone(),
92                    autofill_on_page_load: login.autofill_on_page_load,
93                    http_authentication_enabled: login.http_authentication_enabled.unwrap_or(false),
94                    fido2_credentials,
95                })
96            }
97            CipherType::Card => {
98                let card = view
99                    .card
100                    .as_ref()
101                    .ok_or(CryptoError::MissingField("card"))?;
102                CipherTypeDataV1::Card(CardDataV1::from(card))
103            }
104            CipherType::Identity => {
105                let identity = view
106                    .identity
107                    .as_ref()
108                    .ok_or(CryptoError::MissingField("identity"))?;
109                CipherTypeDataV1::Identity(IdentityDataV1::from(identity))
110            }
111            CipherType::SecureNote => {
112                let secure_note = view
113                    .secure_note
114                    .as_ref()
115                    .ok_or(CryptoError::MissingField("secure_note"))?;
116                CipherTypeDataV1::SecureNote(SecureNoteDataV1::from(secure_note))
117            }
118            CipherType::SshKey => {
119                let ssh_key = view
120                    .ssh_key
121                    .as_ref()
122                    .ok_or(CryptoError::MissingField("ssh_key"))?;
123                CipherTypeDataV1::SshKey(SshKeyDataV1::from(ssh_key))
124            }
125            CipherType::BankAccount => {
126                let bank_account = view
127                    .bank_account
128                    .as_ref()
129                    .ok_or(CryptoError::MissingField("bank_account"))?;
130                CipherTypeDataV1::BankAccount(BankAccountDataV1::from(bank_account))
131            }
132            CipherType::DriversLicense => {
133                let drivers_license = view
134                    .drivers_license
135                    .as_ref()
136                    .ok_or(CryptoError::MissingField("drivers_license"))?;
137                CipherTypeDataV1::DriversLicense(DriversLicenseDataV1::from(drivers_license))
138            }
139            CipherType::Passport => {
140                let passport = view
141                    .passport
142                    .as_ref()
143                    .ok_or(CryptoError::MissingField("passport"))?;
144                CipherTypeDataV1::Passport(PassportDataV1::from(passport))
145            }
146        };
147
148        Ok(Self {
149            name: view.name.clone(),
150            notes: view.notes.clone(),
151            type_data,
152            fields: view
153                .fields
154                .as_ref()
155                .map(|f| f.iter().map(FieldDataV1::from).collect())
156                .unwrap_or_default(),
157            password_history: view
158                .password_history
159                .as_ref()
160                .map(|h| h.iter().map(PasswordHistoryDataV1::from).collect())
161                .unwrap_or_default(),
162        })
163    }
164
165    pub(crate) fn apply_to_cipher_view(&self, view: &mut CipherView) -> Result<(), CryptoError> {
166        view.name = self.name.clone();
167        view.notes = self.notes.clone();
168        view.fields = none_if_empty(self.fields.iter().map(FieldView::from).collect());
169        view.password_history = none_if_empty(
170            self.password_history
171                .iter()
172                .map(PasswordHistoryView::from)
173                .collect(),
174        );
175
176        view.login = None;
177        view.card = None;
178        view.identity = None;
179        view.secure_note = None;
180        view.ssh_key = None;
181        view.bank_account = None;
182        view.drivers_license = None;
183        view.passport = None;
184
185        match &self.type_data {
186            CipherTypeDataV1::Login(login_data) => {
187                let fido2_credentials = if login_data.fido2_credentials.is_empty() {
188                    None
189                } else {
190                    Some(
191                        login_data
192                            .fido2_credentials
193                            .iter()
194                            .map(|d| Fido2CredentialView::from(Fido2CredentialFullView::from(d)))
195                            .collect::<Vec<_>>(),
196                    )
197                };
198
199                view.r#type = CipherType::Login;
200                view.login = Some(LoginView {
201                    username: login_data.username.clone(),
202                    password: login_data.password.clone(),
203                    password_revision_date: login_data.password_revision_date,
204                    uris: none_if_empty(login_data.uris.iter().map(LoginUriView::from).collect()),
205                    totp: login_data.totp.clone(),
206                    autofill_on_page_load: login_data.autofill_on_page_load,
207                    http_authentication_enabled: Some(login_data.http_authentication_enabled),
208                    fido2_credentials,
209                });
210            }
211            CipherTypeDataV1::Card(card_data) => {
212                view.r#type = CipherType::Card;
213                view.card = Some(CardView::from(card_data));
214            }
215            CipherTypeDataV1::Identity(identity_data) => {
216                view.r#type = CipherType::Identity;
217                view.identity = Some(IdentityView::from(identity_data));
218            }
219            CipherTypeDataV1::SecureNote(secure_note_data) => {
220                view.r#type = CipherType::SecureNote;
221                view.secure_note = Some(SecureNoteView::from(secure_note_data));
222            }
223            CipherTypeDataV1::SshKey(ssh_key_data) => {
224                view.r#type = CipherType::SshKey;
225                view.ssh_key = Some(SshKeyView::from(ssh_key_data));
226            }
227            CipherTypeDataV1::BankAccount(bank_account_data) => {
228                view.r#type = CipherType::BankAccount;
229                view.bank_account = Some(BankAccountView::from(bank_account_data));
230            }
231            CipherTypeDataV1::DriversLicense(drivers_license_data) => {
232                view.r#type = CipherType::DriversLicense;
233                view.drivers_license = Some(DriversLicenseView::from(drivers_license_data));
234            }
235            CipherTypeDataV1::Passport(passport_data) => {
236                view.r#type = CipherType::Passport;
237                view.passport = Some(PassportView::from(passport_data));
238            }
239        }
240
241        Ok(())
242    }
243}
244
245#[cfg(test)]
246pub(crate) mod test_support {
247    use bitwarden_core::key_management::{
248        KeySlotIds, SymmetricKeySlotId, create_test_crypto_with_user_key,
249    };
250    use bitwarden_crypto::{KeyStore, SymmetricCryptoKey};
251    use chrono::{TimeZone, Utc};
252
253    use crate::{
254        CipherView,
255        cipher::cipher::{CipherRepromptType, CipherType},
256    };
257
258    pub(crate) fn create_test_key_store() -> (KeyStore<KeySlotIds>, SymmetricKeySlotId) {
259        let key = SymmetricCryptoKey::try_from(
260            "hvBMMb1t79YssFZkpetYsM3deyVuQv4r88Uj9gvYe0+G8EwxvW3v1iywVmSl61iwzd17JW5C/ivzxSP2C9h7Tw==".to_string(),
261        )
262        .unwrap();
263        let key_store = create_test_crypto_with_user_key(key);
264        (key_store, SymmetricKeySlotId::User)
265    }
266
267    pub(crate) fn create_shell_cipher_view(cipher_type: CipherType) -> CipherView {
268        CipherView {
269            partial: false,
270            id: None,
271            organization_id: None,
272            folder_id: None,
273            collection_ids: vec![],
274            key: None,
275            name: String::new(),
276            notes: None,
277            r#type: cipher_type,
278            login: None,
279            identity: None,
280            card: None,
281            secure_note: None,
282            ssh_key: None,
283            bank_account: None,
284            drivers_license: None,
285            passport: None,
286            favorite: false,
287            reprompt: CipherRepromptType::None,
288            organization_use_totp: false,
289            edit: true,
290            permissions: None,
291            view_password: true,
292            local_data: None,
293            attachments: None,
294            attachment_decryption_failures: None,
295            fields: None,
296            password_history: None,
297            creation_date: Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
298            deleted_date: None,
299            revision_date: Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
300            archived_date: None,
301        }
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::{CipherBlobV1, CipherTypeDataV1, test_support::*};
308    use crate::cipher::{
309        cipher::CipherType,
310        login::LoginView,
311        secure_note::{SecureNoteType, SecureNoteView},
312    };
313
314    #[test]
315    fn test_option_vec_normalization_none_to_empty_to_none() {
316        let original = crate::CipherView {
317            name: "Minimal Note".to_string(),
318            notes: None,
319            r#type: CipherType::SecureNote,
320            secure_note: Some(SecureNoteView {
321                r#type: SecureNoteType::Generic,
322            }),
323            fields: None,
324            password_history: None,
325            ..create_shell_cipher_view(CipherType::SecureNote)
326        };
327
328        let blob = CipherBlobV1::from_cipher_view(&original).unwrap();
329
330        assert!(blob.fields.is_empty());
331        assert!(blob.password_history.is_empty());
332
333        let mut restored = create_shell_cipher_view(CipherType::SecureNote);
334        blob.apply_to_cipher_view(&mut restored).unwrap();
335        assert!(restored.fields.is_none());
336        assert!(restored.password_history.is_none());
337    }
338
339    #[test]
340    fn test_login_none_uris_and_fido2_normalization() {
341        let original = crate::CipherView {
342            name: "Simple Login".to_string(),
343            notes: None,
344            r#type: CipherType::Login,
345            login: Some(LoginView {
346                username: Some("user".to_string()),
347                password: None,
348                password_revision_date: None,
349                uris: None,
350                totp: None,
351                autofill_on_page_load: None,
352                http_authentication_enabled: None,
353                fido2_credentials: None,
354            }),
355            ..create_shell_cipher_view(CipherType::Login)
356        };
357
358        let blob = CipherBlobV1::from_cipher_view(&original).unwrap();
359
360        if let CipherTypeDataV1::Login(ref login_data) = blob.type_data {
361            assert!(login_data.uris.is_empty());
362            assert!(login_data.fido2_credentials.is_empty());
363        } else {
364            panic!("Expected Login type data");
365        }
366
367        let mut restored = create_shell_cipher_view(CipherType::Login);
368        blob.apply_to_cipher_view(&mut restored).unwrap();
369
370        let login = restored.login.unwrap();
371        assert!(login.uris.is_none());
372        assert!(login.fido2_credentials.is_none());
373    }
374}