bitwarden_vault/cipher/cipher_client/
create.rs

1use bitwarden_api_api::models::{CipherCreateRequestModel, CipherRequestModel};
2use bitwarden_collections::collection::CollectionId;
3use bitwarden_core::{
4    ApiError, MissingFieldError, NotAuthenticatedError, OrganizationId, UserId,
5    key_management::{KeyIds, SymmetricKeyId},
6    require,
7};
8use bitwarden_crypto::{
9    CompositeEncryptable, CryptoError, EncString, IdentifyKey, KeyStore, KeyStoreContext,
10    PrimitiveEncryptable,
11};
12use bitwarden_error::bitwarden_error;
13use bitwarden_state::repository::{Repository, RepositoryError};
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16#[cfg(feature = "wasm")]
17use tsify::Tsify;
18#[cfg(feature = "wasm")]
19use wasm_bindgen::prelude::*;
20
21use super::CiphersClient;
22use crate::{
23    Cipher, CipherRepromptType, CipherView, FieldView, FolderId, VaultParseError,
24    cipher_view_type::CipherViewType,
25};
26
27#[allow(missing_docs)]
28#[bitwarden_error(flat)]
29#[derive(Debug, Error)]
30pub enum CreateCipherError {
31    #[error(transparent)]
32    Crypto(#[from] CryptoError),
33    #[error(transparent)]
34    Api(#[from] ApiError),
35    #[error(transparent)]
36    VaultParse(#[from] VaultParseError),
37    #[error(transparent)]
38    MissingField(#[from] MissingFieldError),
39    #[error(transparent)]
40    NotAuthenticated(#[from] NotAuthenticatedError),
41    #[error(transparent)]
42    Repository(#[from] RepositoryError),
43}
44
45impl<T> From<bitwarden_api_api::apis::Error<T>> for CreateCipherError {
46    fn from(val: bitwarden_api_api::apis::Error<T>) -> Self {
47        Self::Api(val.into())
48    }
49}
50
51/// Request to add a cipher.
52#[derive(Serialize, Deserialize, Clone, Debug)]
53#[serde(rename_all = "camelCase")]
54#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
55#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
56pub struct CipherCreateRequest {
57    pub organization_id: Option<OrganizationId>,
58    pub collection_ids: Vec<CollectionId>,
59    pub folder_id: Option<FolderId>,
60    pub name: String,
61    pub notes: Option<String>,
62    pub favorite: bool,
63    pub reprompt: CipherRepromptType,
64    pub r#type: CipherViewType,
65    pub fields: Vec<FieldView>,
66}
67
68/// Used as an intermediary between the public-facing [CipherCreateRequest], and the encrypted
69/// value. This allows us to manage the cipher key creation internally.
70#[derive(Clone, Debug)]
71pub(super) struct CipherCreateRequestInternal {
72    pub(super) create_request: CipherCreateRequest,
73    key: Option<EncString>,
74}
75
76impl From<CipherCreateRequest> for CipherCreateRequestInternal {
77    fn from(create_request: CipherCreateRequest) -> Self {
78        Self {
79            create_request,
80            key: None,
81        }
82    }
83}
84
85impl CipherCreateRequestInternal {
86    /// Generate a new key for the cipher, re-encrypting internal data, if necessary, and stores the
87    /// encrypted key to the cipher data.
88    pub(crate) fn generate_cipher_key(
89        &mut self,
90        ctx: &mut KeyStoreContext<KeyIds>,
91        key: SymmetricKeyId,
92    ) -> Result<(), CryptoError> {
93        let old_key = Cipher::decrypt_cipher_key(ctx, key, &self.key)?;
94
95        let new_key = ctx.generate_symmetric_key();
96        self.create_request
97            .r#type
98            .as_login_view_mut()
99            .map(|l| l.reencrypt_fido2_credentials(ctx, old_key, new_key))
100            .transpose()?;
101
102        self.key = Some(ctx.wrap_symmetric_key(key, new_key)?);
103        Ok(())
104    }
105
106    fn generate_checksums(&mut self) {
107        if let Some(login) = &mut self.create_request.r#type.as_login_view_mut() {
108            login.generate_checksums();
109        }
110    }
111}
112
113impl CompositeEncryptable<KeyIds, SymmetricKeyId, CipherRequestModel>
114    for CipherCreateRequestInternal
115{
116    fn encrypt_composite(
117        &self,
118        ctx: &mut KeyStoreContext<KeyIds>,
119        key: SymmetricKeyId,
120    ) -> Result<CipherRequestModel, CryptoError> {
121        // Clone self so we can generating the checksums before encrypting.
122        let mut cipher_data = (*self).clone();
123        cipher_data.generate_checksums();
124
125        let cipher_key = Cipher::decrypt_cipher_key(ctx, key, &cipher_data.key)?;
126
127        let cipher_request = CipherRequestModel {
128            encrypted_for: None,
129            r#type: Some(cipher_data.create_request.r#type.get_cipher_type().into()),
130            organization_id: cipher_data
131                .create_request
132                .organization_id
133                .map(|id| id.to_string()),
134            folder_id: cipher_data
135                .create_request
136                .folder_id
137                .map(|id| id.to_string()),
138            favorite: Some(cipher_data.create_request.favorite),
139            reprompt: Some(cipher_data.create_request.reprompt.into()),
140            key: cipher_data.key.map(|k| k.to_string()),
141            name: cipher_data
142                .create_request
143                .name
144                .encrypt(ctx, cipher_key)?
145                .to_string(),
146            notes: cipher_data
147                .create_request
148                .notes
149                .as_ref()
150                .map(|n| n.encrypt(ctx, cipher_key))
151                .transpose()?
152                .map(|n| n.to_string()),
153            login: cipher_data
154                .create_request
155                .r#type
156                .as_login_view()
157                .as_ref()
158                .map(|l| l.encrypt_composite(ctx, cipher_key))
159                .transpose()?
160                .map(|l| Box::new(l.into())),
161            card: cipher_data
162                .create_request
163                .r#type
164                .as_card_view()
165                .as_ref()
166                .map(|c| c.encrypt_composite(ctx, cipher_key))
167                .transpose()?
168                .map(|c| Box::new(c.into())),
169            identity: cipher_data
170                .create_request
171                .r#type
172                .as_identity_view()
173                .as_ref()
174                .map(|i| i.encrypt_composite(ctx, cipher_key))
175                .transpose()?
176                .map(|i| Box::new(i.into())),
177            secure_note: cipher_data
178                .create_request
179                .r#type
180                .as_secure_note_view()
181                .as_ref()
182                .map(|s| s.encrypt_composite(ctx, cipher_key))
183                .transpose()?
184                .map(|s| Box::new(s.into())),
185            ssh_key: cipher_data
186                .create_request
187                .r#type
188                .as_ssh_key_view()
189                .as_ref()
190                .map(|s| s.encrypt_composite(ctx, cipher_key))
191                .transpose()?
192                .map(|s| Box::new(s.into())),
193            fields: Some(
194                cipher_data
195                    .create_request
196                    .fields
197                    .iter()
198                    .map(|f| f.encrypt_composite(ctx, cipher_key))
199                    .map(|f| f.map(|f| f.into()))
200                    .collect::<Result<Vec<_>, _>>()?,
201            ),
202            password_history: None,
203            attachments: None,
204            attachments2: None,
205            last_known_revision_date: None,
206            archived_date: None,
207            data: None,
208        };
209
210        Ok(cipher_request)
211    }
212}
213
214impl IdentifyKey<SymmetricKeyId> for CipherCreateRequestInternal {
215    fn key_identifier(&self) -> SymmetricKeyId {
216        match self.create_request.organization_id {
217            Some(organization_id) => SymmetricKeyId::Organization(organization_id),
218            None => SymmetricKeyId::User,
219        }
220    }
221}
222
223async fn create_cipher<R: Repository<Cipher> + ?Sized>(
224    key_store: &KeyStore<KeyIds>,
225    api_client: &bitwarden_api_api::apis::ApiClient,
226    repository: &R,
227    encrypted_for: UserId,
228    request: CipherCreateRequestInternal,
229) -> Result<CipherView, CreateCipherError> {
230    let collection_ids = request.create_request.collection_ids.clone();
231    let mut cipher_request = key_store.encrypt(request)?;
232    cipher_request.encrypted_for = Some(encrypted_for.into());
233
234    let cipher: Cipher;
235    if !collection_ids.is_empty() {
236        cipher = api_client
237            .ciphers_api()
238            .post_create(Some(CipherCreateRequestModel {
239                collection_ids: Some(collection_ids.into_iter().map(Into::into).collect()),
240                cipher: Box::new(cipher_request),
241            }))
242            .await
243            .map_err(ApiError::from)?
244            .try_into()?;
245        repository
246            .set(require!(cipher.id).to_string(), cipher.clone())
247            .await?;
248    } else {
249        cipher = api_client
250            .ciphers_api()
251            .post(Some(cipher_request))
252            .await
253            .map_err(ApiError::from)?
254            .try_into()?;
255        repository
256            .set(require!(cipher.id).to_string(), cipher.clone())
257            .await?;
258    }
259
260    Ok(key_store.decrypt(&cipher)?)
261}
262
263#[cfg_attr(feature = "wasm", wasm_bindgen)]
264impl CiphersClient {
265    async fn create_cipher(
266        &self,
267        request: CipherCreateRequest,
268    ) -> Result<CipherView, CreateCipherError> {
269        let key_store = self.client.internal.get_key_store();
270        let config = self.client.internal.get_api_configurations().await;
271        let repository = self.get_repository()?;
272        let mut internal_request: CipherCreateRequestInternal = request.into();
273
274        let user_id = self
275            .client
276            .internal
277            .get_user_id()
278            .ok_or(NotAuthenticatedError)?;
279
280        // TODO: Once this flag is removed, the key generation logic should
281        // be moved closer to the actual encryption logic.
282        if self
283            .client
284            .internal
285            .get_flags()
286            .enable_cipher_key_encryption
287        {
288            let key = internal_request.key_identifier();
289            internal_request.generate_cipher_key(&mut key_store.context(), key)?;
290        }
291
292        create_cipher(
293            key_store,
294            &config.api_client,
295            repository.as_ref(),
296            user_id,
297            internal_request,
298        )
299        .await
300    }
301
302    /// Creates a new [Cipher] and saves it to the server.
303    pub async fn create(
304        &self,
305        request: CipherCreateRequest,
306    ) -> Result<CipherView, CreateCipherError> {
307        self.create_cipher(request).await
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use bitwarden_api_api::{apis::ApiClient, models::CipherResponseModel};
314    use bitwarden_crypto::SymmetricKeyAlgorithm;
315    use bitwarden_test::MemoryRepository;
316    use chrono::Utc;
317
318    use super::*;
319    use crate::{CipherId, LoginView};
320
321    const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
322    const TEST_COLLECTION_ID: &str = "73546b86-8802-4449-ad2a-69ea981b4ffd";
323    const TEST_USER_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
324    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
325
326    fn generate_test_cipher_create_request() -> CipherCreateRequest {
327        CipherCreateRequest {
328            name: "Test Login".to_string(),
329            notes: Some("Test notes".to_string()),
330            r#type: CipherViewType::Login(LoginView {
331                username: Some("[email protected]".to_string()),
332                password: Some("password123".to_string()),
333                password_revision_date: None,
334                uris: None,
335                totp: None,
336                autofill_on_page_load: None,
337                fido2_credentials: None,
338            }),
339            organization_id: Default::default(),
340            folder_id: Default::default(),
341            favorite: Default::default(),
342            reprompt: Default::default(),
343            fields: Default::default(),
344            collection_ids: vec![],
345        }
346    }
347
348    #[tokio::test]
349    async fn test_create_cipher() {
350        let store: KeyStore<KeyIds> = KeyStore::default();
351        {
352            let mut ctx = store.context_mut();
353            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
354            ctx.persist_symmetric_key(local_key_id, SymmetricKeyId::User)
355                .unwrap();
356        }
357
358        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
359
360        let api_client = ApiClient::new_mocked(move |mock| {
361            mock.ciphers_api
362                .expect_post()
363                .returning(move |body| {
364                    let body = body.unwrap();
365                    Ok(CipherResponseModel {
366                        object: Some("cipher".to_string()),
367                        id: Some(cipher_id.into()),
368                        name: Some(body.name.clone()),
369                        r#type: body.r#type,
370                        organization_id: body
371                            .organization_id
372                            .as_ref()
373                            .and_then(|id| uuid::Uuid::parse_str(id).ok()),
374                        folder_id: body
375                            .folder_id
376                            .as_ref()
377                            .and_then(|id| uuid::Uuid::parse_str(id).ok()),
378                        favorite: body.favorite,
379                        reprompt: body.reprompt,
380                        key: body.key.clone(),
381                        notes: body.notes.clone(),
382                        view_password: Some(true),
383                        edit: Some(true),
384                        organization_use_totp: Some(true),
385                        revision_date: Some("2025-01-01T00:00:00Z".to_string()),
386                        creation_date: Some("2025-01-01T00:00:00Z".to_string()),
387                        deleted_date: None,
388                        login: body.login,
389                        card: body.card,
390                        identity: body.identity,
391                        secure_note: body.secure_note,
392                        ssh_key: body.ssh_key,
393                        fields: body.fields,
394                        password_history: body.password_history,
395                        attachments: None,
396                        permissions: None,
397                        data: None,
398                        archived_date: None,
399                    })
400                })
401                .once();
402        });
403
404        let repository = MemoryRepository::<Cipher>::default();
405        let request = generate_test_cipher_create_request();
406
407        let result = create_cipher(
408            &store,
409            &api_client,
410            &repository,
411            TEST_USER_ID.parse().unwrap(),
412            request.into(),
413        )
414        .await
415        .unwrap();
416
417        assert_eq!(result.id, Some(cipher_id));
418        assert_eq!(result.name, "Test Login");
419        assert_eq!(
420            result.login,
421            Some(LoginView {
422                username: Some("[email protected]".to_string()),
423                password: Some("password123".to_string()),
424                password_revision_date: None,
425                uris: None,
426                totp: None,
427                autofill_on_page_load: None,
428                fido2_credentials: None,
429            })
430        );
431
432        // Confirm the cipher was stored in the repository
433        let stored_cipher_view: CipherView = store
434            .decrypt(
435                &repository
436                    .get(cipher_id.to_string())
437                    .await
438                    .unwrap()
439                    .unwrap(),
440            )
441            .unwrap();
442        assert_eq!(stored_cipher_view.id, result.id);
443        assert_eq!(stored_cipher_view.name, result.name);
444        assert_eq!(stored_cipher_view.r#type, result.r#type);
445        assert!(stored_cipher_view.login.is_some());
446        assert_eq!(stored_cipher_view.favorite, result.favorite);
447    }
448
449    #[tokio::test]
450    async fn test_create_cipher_http_error() {
451        let store: KeyStore<KeyIds> = KeyStore::default();
452        {
453            let mut ctx = store.context_mut();
454            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
455            ctx.persist_symmetric_key(local_key_id, SymmetricKeyId::User)
456                .unwrap();
457        }
458
459        let api_client = ApiClient::new_mocked(move |mock| {
460            mock.ciphers_api.expect_post().returning(move |_body| {
461                Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
462                    "Simulated error",
463                )))
464            });
465        });
466
467        let repository = MemoryRepository::<Cipher>::default();
468
469        let request = generate_test_cipher_create_request();
470
471        let result = create_cipher(
472            &store,
473            &api_client,
474            &repository,
475            TEST_USER_ID.parse().unwrap(),
476            request.into(),
477        )
478        .await;
479
480        assert!(result.is_err());
481        assert!(matches!(result.unwrap_err(), CreateCipherError::Api(_)));
482    }
483
484    #[tokio::test]
485    async fn test_create_org_cipher() {
486        let api_client = ApiClient::new_mocked(move |mock| {
487            mock.ciphers_api
488                .expect_post_create()
489                .returning(move |body| {
490                    let request_body = body.unwrap();
491
492                    Ok(CipherResponseModel {
493                        id: Some(TEST_CIPHER_ID.try_into().unwrap()),
494                        organization_id: request_body
495                            .cipher
496                            .organization_id
497                            .and_then(|id| id.parse().ok()),
498                        name: Some(request_body.cipher.name.clone()),
499                        r#type: request_body.cipher.r#type,
500                        creation_date: Some(Utc::now().to_string()),
501                        revision_date: Some(Utc::now().to_string()),
502                        ..Default::default()
503                    })
504                })
505                .once();
506        });
507
508        let store: KeyStore<KeyIds> = KeyStore::default();
509        {
510            let mut ctx = store.context_mut();
511            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
512            ctx.persist_symmetric_key(
513                local_key_id,
514                SymmetricKeyId::Organization(TEST_ORG_ID.parse().unwrap()),
515            )
516            .unwrap();
517        }
518        let repository = MemoryRepository::<Cipher>::default();
519        let request = CipherCreateRequest {
520            organization_id: Some(TEST_ORG_ID.parse().unwrap()),
521            collection_ids: vec![TEST_COLLECTION_ID.parse().unwrap()],
522            folder_id: None,
523            name: "Test Cipher".into(),
524            notes: None,
525            favorite: false,
526            reprompt: CipherRepromptType::None,
527            r#type: CipherViewType::Login(LoginView {
528                username: None,
529                password: None,
530                password_revision_date: None,
531                uris: None,
532                totp: None,
533                autofill_on_page_load: None,
534                fido2_credentials: None,
535            }),
536            fields: vec![],
537        };
538
539        let response = create_cipher(
540            &store,
541            &api_client,
542            &repository,
543            TEST_USER_ID.parse().unwrap(),
544            request.into(),
545        )
546        .await
547        .unwrap();
548
549        let cipher: Cipher = repository
550            .get(TEST_CIPHER_ID.to_string())
551            .await
552            .unwrap()
553            .unwrap();
554        let cipher_view: CipherView = store.decrypt(&cipher).unwrap();
555
556        assert_eq!(response.id, cipher_view.id);
557        assert_eq!(response.organization_id, cipher_view.organization_id);
558
559        assert_eq!(response.id, Some(TEST_CIPHER_ID.parse().unwrap()));
560        assert_eq!(response.organization_id, Some(TEST_ORG_ID.parse().unwrap()));
561    }
562}