Skip to main content

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.set(require!(cipher.id), cipher.clone()).await?;
246    } else {
247        cipher = api_client
248            .ciphers_api()
249            .post(Some(cipher_request))
250            .await
251            .map_err(ApiError::from)?
252            .try_into()?;
253        repository.set(require!(cipher.id), cipher.clone()).await?;
254    }
255
256    Ok(key_store.decrypt(&cipher)?)
257}
258
259#[cfg_attr(feature = "wasm", wasm_bindgen)]
260impl CiphersClient {
261    async fn create_cipher(
262        &self,
263        request: CipherCreateRequest,
264    ) -> Result<CipherView, CreateCipherError> {
265        let key_store = self.client.internal.get_key_store();
266        let config = self.client.internal.get_api_configurations();
267        let repository = self.get_repository()?;
268        let mut internal_request: CipherCreateRequestInternal = request.into();
269
270        let user_id = self
271            .client
272            .internal
273            .get_user_id()
274            .ok_or(NotAuthenticatedError)?;
275
276        // TODO: Once this flag is removed, the key generation logic should
277        // be moved closer to the actual encryption logic.
278        if self
279            .client
280            .internal
281            .get_flags()
282            .enable_cipher_key_encryption
283        {
284            let key = internal_request.key_identifier();
285            internal_request.generate_cipher_key(&mut key_store.context(), key)?;
286        }
287
288        create_cipher(
289            key_store,
290            &config.api_client,
291            repository.as_ref(),
292            user_id,
293            internal_request,
294        )
295        .await
296    }
297
298    /// Creates a new [Cipher] and saves it to the server.
299    pub async fn create(
300        &self,
301        request: CipherCreateRequest,
302    ) -> Result<CipherView, CreateCipherError> {
303        self.create_cipher(request).await
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use bitwarden_api_api::{apis::ApiClient, models::CipherResponseModel};
310    use bitwarden_crypto::SymmetricKeyAlgorithm;
311    use bitwarden_test::MemoryRepository;
312    use chrono::Utc;
313
314    use super::*;
315    use crate::{CipherId, LoginView};
316
317    const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
318    const TEST_COLLECTION_ID: &str = "73546b86-8802-4449-ad2a-69ea981b4ffd";
319    const TEST_USER_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
320    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
321
322    fn generate_test_cipher_create_request() -> CipherCreateRequest {
323        CipherCreateRequest {
324            name: "Test Login".to_string(),
325            notes: Some("Test notes".to_string()),
326            r#type: CipherViewType::Login(LoginView {
327                username: Some("[email protected]".to_string()),
328                password: Some("password123".to_string()),
329                password_revision_date: None,
330                uris: None,
331                totp: None,
332                autofill_on_page_load: None,
333                fido2_credentials: None,
334            }),
335            organization_id: Default::default(),
336            folder_id: Default::default(),
337            favorite: Default::default(),
338            reprompt: Default::default(),
339            fields: Default::default(),
340            collection_ids: vec![],
341        }
342    }
343
344    #[tokio::test]
345    async fn test_create_cipher() {
346        let store: KeyStore<KeyIds> = KeyStore::default();
347        {
348            let mut ctx = store.context_mut();
349            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
350            ctx.persist_symmetric_key(local_key_id, SymmetricKeyId::User)
351                .unwrap();
352        }
353
354        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
355
356        let api_client = ApiClient::new_mocked(move |mock| {
357            mock.ciphers_api
358                .expect_post()
359                .returning(move |body| {
360                    let body = body.unwrap();
361                    Ok(CipherResponseModel {
362                        object: Some("cipher".to_string()),
363                        id: Some(cipher_id.into()),
364                        name: Some(body.name.clone()),
365                        r#type: body.r#type,
366                        organization_id: body
367                            .organization_id
368                            .as_ref()
369                            .and_then(|id| uuid::Uuid::parse_str(id).ok()),
370                        folder_id: body
371                            .folder_id
372                            .as_ref()
373                            .and_then(|id| uuid::Uuid::parse_str(id).ok()),
374                        favorite: body.favorite,
375                        reprompt: body.reprompt,
376                        key: body.key.clone(),
377                        notes: body.notes.clone(),
378                        view_password: Some(true),
379                        edit: Some(true),
380                        organization_use_totp: Some(true),
381                        revision_date: Some("2025-01-01T00:00:00Z".to_string()),
382                        creation_date: Some("2025-01-01T00:00:00Z".to_string()),
383                        deleted_date: None,
384                        login: body.login,
385                        card: body.card,
386                        identity: body.identity,
387                        secure_note: body.secure_note,
388                        ssh_key: body.ssh_key,
389                        fields: body.fields,
390                        password_history: body.password_history,
391                        attachments: None,
392                        permissions: None,
393                        data: None,
394                        archived_date: None,
395                    })
396                })
397                .once();
398        });
399
400        let repository = MemoryRepository::<Cipher>::default();
401        let request = generate_test_cipher_create_request();
402
403        let result = create_cipher(
404            &store,
405            &api_client,
406            &repository,
407            TEST_USER_ID.parse().unwrap(),
408            request.into(),
409        )
410        .await
411        .unwrap();
412
413        assert_eq!(result.id, Some(cipher_id));
414        assert_eq!(result.name, "Test Login");
415        assert_eq!(
416            result.login,
417            Some(LoginView {
418                username: Some("[email protected]".to_string()),
419                password: Some("password123".to_string()),
420                password_revision_date: None,
421                uris: None,
422                totp: None,
423                autofill_on_page_load: None,
424                fido2_credentials: None,
425            })
426        );
427
428        // Confirm the cipher was stored in the repository
429        let stored_cipher_view: CipherView = store
430            .decrypt(&repository.get(cipher_id).await.unwrap().unwrap())
431            .unwrap();
432        assert_eq!(stored_cipher_view.id, result.id);
433        assert_eq!(stored_cipher_view.name, result.name);
434        assert_eq!(stored_cipher_view.r#type, result.r#type);
435        assert!(stored_cipher_view.login.is_some());
436        assert_eq!(stored_cipher_view.favorite, result.favorite);
437    }
438
439    #[tokio::test]
440    async fn test_create_cipher_http_error() {
441        let store: KeyStore<KeyIds> = KeyStore::default();
442        {
443            let mut ctx = store.context_mut();
444            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
445            ctx.persist_symmetric_key(local_key_id, SymmetricKeyId::User)
446                .unwrap();
447        }
448
449        let api_client = ApiClient::new_mocked(move |mock| {
450            mock.ciphers_api.expect_post().returning(move |_body| {
451                Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
452                    "Simulated error",
453                )))
454            });
455        });
456
457        let repository = MemoryRepository::<Cipher>::default();
458
459        let request = generate_test_cipher_create_request();
460
461        let result = create_cipher(
462            &store,
463            &api_client,
464            &repository,
465            TEST_USER_ID.parse().unwrap(),
466            request.into(),
467        )
468        .await;
469
470        assert!(result.is_err());
471        assert!(matches!(result.unwrap_err(), CreateCipherError::Api(_)));
472    }
473
474    #[tokio::test]
475    async fn test_create_org_cipher() {
476        let api_client = ApiClient::new_mocked(move |mock| {
477            mock.ciphers_api
478                .expect_post_create()
479                .returning(move |body| {
480                    let request_body = body.unwrap();
481
482                    Ok(CipherResponseModel {
483                        id: Some(TEST_CIPHER_ID.try_into().unwrap()),
484                        organization_id: request_body
485                            .cipher
486                            .organization_id
487                            .and_then(|id| id.parse().ok()),
488                        name: Some(request_body.cipher.name.clone()),
489                        r#type: request_body.cipher.r#type,
490                        creation_date: Some(Utc::now().to_string()),
491                        revision_date: Some(Utc::now().to_string()),
492                        ..Default::default()
493                    })
494                })
495                .once();
496        });
497
498        let store: KeyStore<KeyIds> = KeyStore::default();
499        {
500            let mut ctx = store.context_mut();
501            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
502            ctx.persist_symmetric_key(
503                local_key_id,
504                SymmetricKeyId::Organization(TEST_ORG_ID.parse().unwrap()),
505            )
506            .unwrap();
507        }
508        let repository = MemoryRepository::<Cipher>::default();
509        let request = CipherCreateRequest {
510            organization_id: Some(TEST_ORG_ID.parse().unwrap()),
511            collection_ids: vec![TEST_COLLECTION_ID.parse().unwrap()],
512            folder_id: None,
513            name: "Test Cipher".into(),
514            notes: None,
515            favorite: false,
516            reprompt: CipherRepromptType::None,
517            r#type: CipherViewType::Login(LoginView {
518                username: None,
519                password: None,
520                password_revision_date: None,
521                uris: None,
522                totp: None,
523                autofill_on_page_load: None,
524                fido2_credentials: None,
525            }),
526            fields: vec![],
527        };
528
529        let response = create_cipher(
530            &store,
531            &api_client,
532            &repository,
533            TEST_USER_ID.parse().unwrap(),
534            request.into(),
535        )
536        .await
537        .unwrap();
538
539        let cipher: Cipher = repository
540            .get(TEST_CIPHER_ID.parse().unwrap())
541            .await
542            .unwrap()
543            .unwrap();
544        let cipher_view: CipherView = store.decrypt(&cipher).unwrap();
545
546        assert_eq!(response.id, cipher_view.id);
547        assert_eq!(response.organization_id, cipher_view.organization_id);
548
549        assert_eq!(response.id, Some(TEST_CIPHER_ID.parse().unwrap()));
550        assert_eq!(response.organization_id, Some(TEST_ORG_ID.parse().unwrap()));
551    }
552}