Skip to main content

bitwarden_vault/cipher/cipher_client/
edit.rs

1use bitwarden_api_api::models::{
2    CipherCollectionsRequestModel, CipherPartialRequestModel, CipherRequestModel,
3};
4use bitwarden_collections::collection::CollectionId;
5use bitwarden_core::{
6    ApiError, MissingFieldError, NotAuthenticatedError, OrganizationId, UserId,
7    key_management::KeySlotIds, require,
8};
9use bitwarden_crypto::{CryptoError, IdentifyKey, KeyStore, SymmetricCryptoKey};
10use bitwarden_error::bitwarden_error;
11use bitwarden_state::repository::{Repository, RepositoryError};
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15
16use super::CiphersClient;
17use crate::{
18    AttachmentView, Cipher, CipherId, CipherRepromptType, CipherType, CipherView, FieldView,
19    FolderId, ItemNotFoundError, VaultParseError,
20    cipher::cipher::{EncryptMode, PartialCipher, StrictDecrypt},
21    cipher_view_type::CipherViewType,
22};
23
24#[allow(missing_docs)]
25#[bitwarden_error(flat)]
26#[derive(Debug, Error)]
27pub enum EditCipherError {
28    #[error(transparent)]
29    ItemNotFound(#[from] ItemNotFoundError),
30    #[error(transparent)]
31    Crypto(#[from] CryptoError),
32    #[error(transparent)]
33    Api(#[from] ApiError),
34    #[error(transparent)]
35    VaultParse(#[from] VaultParseError),
36    #[error(transparent)]
37    MissingField(#[from] MissingFieldError),
38    #[error(transparent)]
39    NotAuthenticated(#[from] NotAuthenticatedError),
40    #[error(transparent)]
41    Repository(#[from] RepositoryError),
42    #[error(transparent)]
43    Uuid(#[from] uuid::Error),
44    /// The stored cipher is PAM-gated, so local state holds only its partial copy and an edit
45    /// built on it would drop the item's password history and mis-stamp its revision date.
46    #[error(
47        "Cannot edit a PAM-gated cipher from local state; use `edit_gated` with a full original \
48         obtained under an active lease"
49    )]
50    GatedCipher,
51    /// `edit_gated` was handed a partial view as the original.
52    #[error("Editing a PAM-gated cipher requires a full original; the supplied view is partial")]
53    PartialOriginal,
54}
55
56/// Request to edit a cipher.
57#[derive(Clone, Serialize, Deserialize, Debug)]
58#[serde(rename_all = "camelCase")]
59#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
60#[bitwarden_ffi::wasm_record]
61pub struct CipherEditRequest {
62    /// ID of the cipher to edit.
63    pub id: CipherId,
64
65    /// Organization that owns the cipher, or `None` for the user's individual vault.
66    pub organization_id: Option<OrganizationId>,
67    /// Folder to place the cipher in, if any.
68    pub folder_id: Option<FolderId>,
69    /// Whether the cipher is marked as a favorite.
70    pub favorite: bool,
71    /// Whether the user must re-enter their master password to view the cipher.
72    pub reprompt: CipherRepromptType,
73    /// Display name of the cipher.
74    pub name: String,
75    /// Free-form notes.
76    pub notes: Option<String>,
77    /// Custom fields.
78    pub fields: Vec<FieldView>,
79    /// Type of the cipher and its type-specific data.
80    pub r#type: CipherViewType,
81    /// Revision date of the cipher being edited, as last seen by the client.
82    pub revision_date: DateTime<Utc>,
83    /// When the cipher was archived, or `None` if it is not archived.
84    pub archived_date: Option<DateTime<Utc>>,
85    /// Attachments on the cipher.
86    pub attachments: Vec<AttachmentView>,
87    /// The cipher's own encryption key, if it has one.
88    #[cfg_attr(feature = "wasm", tsify(type = "SymmetricKey | undefined"))]
89    pub key: Option<SymmetricCryptoKey>,
90}
91
92impl TryFrom<CipherView> for CipherEditRequest {
93    type Error = MissingFieldError;
94
95    fn try_from(value: CipherView) -> Result<Self, Self::Error> {
96        let type_data = match value.r#type {
97            CipherType::Login => value.login.map(CipherViewType::Login),
98            CipherType::SecureNote => value.secure_note.map(CipherViewType::SecureNote),
99            CipherType::Card => value.card.map(CipherViewType::Card),
100            CipherType::Identity => value.identity.map(CipherViewType::Identity),
101            CipherType::SshKey => value.ssh_key.map(CipherViewType::SshKey),
102            CipherType::BankAccount => value.bank_account.map(CipherViewType::BankAccount),
103            CipherType::DriversLicense => value.drivers_license.map(CipherViewType::DriversLicense),
104            CipherType::Passport => value.passport.map(CipherViewType::Passport),
105        };
106        Ok(Self {
107            id: value.id.ok_or(MissingFieldError("id"))?,
108            organization_id: value.organization_id,
109            folder_id: value.folder_id,
110            favorite: value.favorite,
111            reprompt: value.reprompt,
112            key: value.key,
113            name: value.name,
114            notes: value.notes,
115            fields: value.fields.unwrap_or_default(),
116            r#type: require!(type_data),
117            attachments: value.attachments.unwrap_or_default(),
118            revision_date: value.revision_date,
119            archived_date: value.archived_date,
120        })
121    }
122}
123
124/// Request to update the subset of cipher fields that a user without edit
125/// permissions is still allowed to change (`folder_id` and `favorite`).
126///
127/// Backed by the `PUT /ciphers/{id}/partial` server endpoint, which authorizes
128/// based on view (not edit) access.
129#[derive(Clone, Serialize, Deserialize, Debug)]
130#[serde(rename_all = "camelCase")]
131#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
132#[bitwarden_ffi::wasm_record]
133pub struct CipherPartialEditRequest {
134    /// ID of the cipher to edit.
135    pub id: CipherId,
136    /// Folder to place the cipher in, if any.
137    pub folder_id: Option<FolderId>,
138    /// Whether the cipher is marked as a favorite.
139    pub favorite: bool,
140}
141
142/// Internal helper to convert a [`CipherEditRequest`] into a [`CipherView`]
143/// so the existing `CipherView` encryption pipeline can be reused.
144///
145/// This conversion is lossy and intended for use only within the edit flow,
146/// as the `CipherView` produced will not have all fields populated (e.g. `collection_ids`).
147pub(crate) fn convert_request_to_cipher_view(r: CipherEditRequest) -> CipherView {
148    CipherView {
149        partial: false,
150        id: Some(r.id),
151        organization_id: r.organization_id,
152        folder_id: r.folder_id,
153        // `collection_ids` is empty because collections are updated via a separate endpoint.
154        collection_ids: vec![],
155        key: r.key,
156        name: r.name,
157        notes: r.notes,
158        r#type: r.r#type.get_cipher_type(),
159        login: r.r#type.as_login_view().cloned(),
160        identity: r.r#type.as_identity_view().cloned(),
161        card: r.r#type.as_card_view().cloned(),
162        secure_note: r.r#type.as_secure_note_view().cloned(),
163        ssh_key: r.r#type.as_ssh_key_view().cloned(),
164        bank_account: r.r#type.as_bank_account_view().cloned(),
165        drivers_license: r.r#type.as_drivers_license_view().cloned(),
166        passport: r.r#type.as_passport_view().cloned(),
167        favorite: r.favorite,
168        reprompt: r.reprompt,
169        organization_use_totp: false,
170        edit: true,
171        permissions: None,
172        view_password: true,
173        local_data: None,
174        attachments: Some(r.attachments),
175        attachment_decryption_failures: None,
176        fields: Some(r.fields),
177        password_history: None,
178        // `creation_date` is overwritten by the server on merge
179        creation_date: Utc::now(),
180        deleted_date: None,
181        revision_date: r.revision_date,
182        archived_date: r.archived_date,
183    }
184}
185
186async fn edit_cipher<R: Repository<Cipher> + ?Sized>(
187    key_store: &KeyStore<KeySlotIds>,
188    api_client: &bitwarden_api_api::apis::ApiClient,
189    repository: &R,
190    encrypted_for: UserId,
191    request: CipherEditRequest,
192    use_strict_decryption: bool,
193    use_blob: bool,
194) -> Result<CipherView, EditCipherError> {
195    let cipher_id = request.id;
196
197    let original_cipher = repository.get(cipher_id).await?.ok_or(ItemNotFoundError)?;
198
199    // A PAM-gated cipher is only ever stored partial — the server withholds its secrets from
200    // every bulk read and from write-returns alike — so the original below would carry blanks
201    // where the withheld fields belong. `update_password_history` would then drop the item's
202    // whole history (a partial view has none to chain) and stamp a fresh `password_revision_date`,
203    // and the PUT would persist both. Refuse rather than corrupt; `edit_gated` takes the full
204    // original from a lease-authorised read.
205    if original_cipher.partial_data.is_some() {
206        return Err(EditCipherError::GatedCipher);
207    }
208
209    let original_cipher_view: CipherView = if use_strict_decryption {
210        key_store.decrypt(&StrictDecrypt(original_cipher.clone()))?
211    } else {
212        key_store.decrypt(&original_cipher)?
213    };
214
215    submit_cipher_edit(
216        key_store,
217        api_client,
218        repository,
219        encrypted_for,
220        request,
221        &original_cipher_view,
222        original_cipher,
223        use_strict_decryption,
224        use_blob,
225    )
226    .await
227}
228
229/// The body both edit paths share: request → view, fold in password history against
230/// `original_cipher_view`, encrypt, PUT, and merge the write-return over `stored_cipher` before
231/// persisting it.
232///
233/// The paths differ only in where the original comes from — local state for [`edit_cipher`], the
234/// caller for [`edit_gated_cipher`], because a gated cipher has no full copy in state — so that is
235/// all either one is left holding.
236// `use_strict_decryption` and `use_blob` are
237// short-lived feature-rollout flags that will be removed once their migrations
238// complete, at which point the argument count drops back under the limit.
239#[allow(clippy::too_many_arguments)]
240async fn submit_cipher_edit<R: Repository<Cipher> + ?Sized>(
241    key_store: &KeyStore<KeySlotIds>,
242    api_client: &bitwarden_api_api::apis::ApiClient,
243    repository: &R,
244    encrypted_for: UserId,
245    request: CipherEditRequest,
246    original_cipher_view: &CipherView,
247    stored_cipher: Cipher,
248    use_strict_decryption: bool,
249    use_blob: bool,
250) -> Result<CipherView, EditCipherError> {
251    let cipher_id = request.id;
252    let stored_gated = stored_cipher.partial_data.is_some();
253
254    let mut view: CipherView = convert_request_to_cipher_view(request);
255    view.update_password_history(original_cipher_view);
256
257    let encrypted_by_key_id = key_store
258        .context()
259        .get_symmetric_key_id(view.key_identifier())
260        .map(|id| id.to_string());
261
262    let mode = if use_blob {
263        EncryptMode::Blob(view)
264    } else {
265        EncryptMode::Legacy(view)
266    };
267
268    let cipher: Cipher = key_store.encrypt(mode)?;
269    let mut cipher_request: CipherRequestModel = cipher.try_into()?;
270    cipher_request.encrypted_for = Some(encrypted_for.into());
271    cipher_request.encrypted_by_key_id = encrypted_by_key_id;
272
273    let cipher: Cipher = api_client
274        .ciphers_api()
275        .put(cipher_id.into(), Some(cipher_request))
276        .await?
277        .merge_with_cipher(Some(stored_cipher))?;
278    debug_assert!(cipher.id.unwrap_or_default() == cipher_id);
279
280    // Never let a write-return un-gate the stored copy. The server withholds secrets from a gated
281    // write-return, so a full response here should be impossible — but persisting one would put
282    // lease-scoped secrets into durable state, outliving the lease that justified them. Skip the
283    // write and let the next sync reconcile: the server already applied the change, so reporting
284    // a failure would be the worse lie.
285    //
286    // A no-op for [`edit_cipher`], which refuses a gated cipher outright, so nothing it stores is
287    // ever gated to begin with.
288    if !stored_gated || cipher.partial_data.is_some() {
289        repository.set(cipher_id, cipher.clone()).await?;
290    }
291
292    Ok(if use_strict_decryption {
293        key_store.decrypt(&StrictDecrypt(cipher))?
294    } else {
295        key_store.decrypt(&cipher)?
296    })
297}
298
299/// Edit a PAM-gated cipher against a full original supplied by the caller.
300///
301/// [`edit_cipher`] reads its original out of the repository, which for a gated cipher only ever
302/// holds the partial copy. This path takes the full view the caller obtained from a
303/// lease-authorised single-cipher read instead, so password history carries forward correctly.
304/// It mirrors the admin edit path, which takes its original as an argument for the same reason:
305/// no usable copy exists in local state.
306// `use_strict_decryption` and `use_blob` are
307// short-lived feature-rollout flags that will be removed once their migrations
308// complete, at which point the argument count drops back under the limit.
309#[allow(clippy::too_many_arguments)]
310async fn edit_gated_cipher<R: Repository<Cipher> + ?Sized>(
311    key_store: &KeyStore<KeySlotIds>,
312    api_client: &bitwarden_api_api::apis::ApiClient,
313    repository: &R,
314    encrypted_for: UserId,
315    request: CipherEditRequest,
316    original_cipher_view: CipherView,
317    use_strict_decryption: bool,
318    use_blob: bool,
319) -> Result<CipherView, EditCipherError> {
320    let cipher_id = request.id;
321
322    // The point of this path is the full original. A partial one lands us back in exactly the
323    // case `edit_cipher` refuses, only with the blanks handed in by the caller.
324    if original_cipher_view.partial {
325        return Err(EditCipherError::PartialOriginal);
326    }
327
328    // Read for `local_data`, which the response model does not carry, and for the gating the
329    // shared body checks before it persists the write-return.
330    let stored_cipher = repository.get(cipher_id).await?.ok_or(ItemNotFoundError)?;
331
332    submit_cipher_edit(
333        key_store,
334        api_client,
335        repository,
336        encrypted_for,
337        request,
338        &original_cipher_view,
339        stored_cipher,
340        use_strict_decryption,
341        use_blob,
342    )
343    .await
344}
345
346/// Update only the cipher fields available to users without edit permissions
347/// (`folder_id` and `favorite`) via the server's partial-update endpoint.
348async fn partial_edit_cipher<R: Repository<Cipher> + ?Sized>(
349    key_store: &KeyStore<KeySlotIds>,
350    api_client: &bitwarden_api_api::apis::ApiClient,
351    repository: &R,
352    request: CipherPartialEditRequest,
353    use_strict_decryption: bool,
354) -> Result<CipherView, EditCipherError> {
355    let cipher_id = request.id;
356
357    let original_cipher = repository.get(cipher_id).await?.ok_or(ItemNotFoundError)?;
358
359    let partial_request = CipherPartialRequestModel {
360        folder_id: request.folder_id.map(|id| id.to_string()),
361        favorite: Some(request.favorite),
362    };
363
364    let cipher: Cipher = api_client
365        .ciphers_api()
366        .put_partial(cipher_id.into(), Some(partial_request))
367        .await?
368        .merge_with_cipher(Some(original_cipher))?;
369    debug_assert!(cipher.id.unwrap_or_default() == cipher_id);
370    repository.set(cipher_id, cipher.clone()).await?;
371
372    Ok(if use_strict_decryption {
373        key_store.decrypt(&StrictDecrypt(cipher))?
374    } else {
375        key_store.decrypt(&cipher)?
376    })
377}
378
379#[allow(deprecated)]
380#[bitwarden_ffi::wasm_export]
381impl CiphersClient {
382    /// Edit an existing [Cipher] and save it to the server.
383    pub async fn edit(&self, request: CipherEditRequest) -> Result<CipherView, EditCipherError> {
384        let key_store = self.client.internal.get_key_store();
385        let config = self.client.internal.get_api_configurations();
386        let repository = self.get_repository()?;
387
388        let user_id = self
389            .client
390            .internal
391            .get_user_id()
392            .ok_or(NotAuthenticatedError)?;
393
394        let use_blob = self.should_use_blob_encryption(request.organization_id);
395
396        edit_cipher(
397            key_store,
398            &config.api_client,
399            repository.as_ref(),
400            user_id,
401            request,
402            self.is_strict_decrypt().await,
403            use_blob,
404        )
405        .await
406    }
407
408    /// Edit a PAM-gated [`Cipher`] whose secrets were revealed under an active lease.
409    ///
410    /// [`CiphersClient::edit`] builds its original from local state, which for a gated cipher only
411    /// ever holds the partial copy, and so refuses. Pass the full view obtained from the
412    /// lease-authorised read as `original_cipher_view` — it is what password history is diffed
413    /// against.
414    ///
415    /// The returned view reflects what was persisted, so it is partial: the server withholds
416    /// secrets from a gated write-return. The caller keeps its own full copy in memory.
417    pub async fn edit_gated(
418        &self,
419        request: CipherEditRequest,
420        original_cipher_view: CipherView,
421    ) -> Result<CipherView, EditCipherError> {
422        let key_store = self.client.internal.get_key_store();
423        let config = self.client.internal.get_api_configurations();
424        let repository = self.get_repository()?;
425
426        let user_id = self
427            .client
428            .internal
429            .get_user_id()
430            .ok_or(NotAuthenticatedError)?;
431
432        let use_blob = self.should_use_blob_encryption(request.organization_id);
433
434        edit_gated_cipher(
435            key_store,
436            &config.api_client,
437            repository.as_ref(),
438            user_id,
439            request,
440            original_cipher_view,
441            self.is_strict_decrypt().await,
442            use_blob,
443        )
444        .await
445    }
446
447    /// Update only `folder_id` and `favorite` on an existing [Cipher].
448    ///
449    /// Intended for users who do not have edit permissions on the cipher, but
450    /// are still allowed to change these personal organization fields.
451    pub async fn edit_partial(
452        &self,
453        request: CipherPartialEditRequest,
454    ) -> Result<CipherView, EditCipherError> {
455        let key_store = self.client.internal.get_key_store();
456        let config = self.client.internal.get_api_configurations();
457        let repository = self.get_repository()?;
458
459        partial_edit_cipher(
460            key_store,
461            &config.api_client,
462            repository.as_ref(),
463            request,
464            self.is_strict_decrypt().await,
465        )
466        .await
467    }
468
469    /// Adds the cipher matched by [CipherId] to any number of collections on the server.
470    pub async fn update_collection(
471        &self,
472        cipher_id: CipherId,
473        collection_ids: Vec<CollectionId>,
474    ) -> Result<CipherView, EditCipherError> {
475        let req = CipherCollectionsRequestModel {
476            collection_ids: collection_ids
477                .into_iter()
478                .map(|id| id.to_string())
479                .collect(),
480        };
481        let repository = self.get_repository()?;
482
483        let api_config = self.client.internal.get_api_configurations();
484        let api = api_config.api_client.ciphers_api();
485        let orig_cipher = repository.get(cipher_id).await?;
486        let cipher_response = api
487            .put_collections_v_next(cipher_id.into(), Some(req))
488            .await?
489            .cipher
490            .map(|c| *c)
491            .ok_or(MissingFieldError("cipher"))?;
492        let cipher: Cipher = cipher_response.merge_with_cipher(orig_cipher)?;
493        repository.set(cipher_id, cipher.clone()).await?;
494
495        Ok(self
496            .decrypt(cipher)
497            .await
498            .map_err(|_| CryptoError::KeyDecrypt)?)
499    }
500}
501
502#[cfg(test)]
503mod tests {
504    use bitwarden_api_api::{apis::ApiClient, models::CipherResponseModel};
505    use bitwarden_core::key_management::{
506        SymmetricKeySlotId, create_test_crypto_with_user_and_org_key,
507    };
508    use bitwarden_crypto::{
509        KeyStore, PrimitiveEncryptable, SymmetricCryptoKey, SymmetricKeyAlgorithm,
510    };
511    use bitwarden_test::MemoryRepository;
512    use chrono::TimeZone;
513
514    use super::*;
515    use crate::{
516        Cipher, CipherId, CipherRepromptType, CipherType, FieldType, Login, LoginView,
517        PasswordHistoryView, password_history::MAX_PASSWORD_HISTORY_ENTRIES,
518    };
519
520    const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
521    const TEST_USER_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
522
523    fn generate_test_cipher() -> CipherView {
524        CipherView {
525            partial: false,
526            id: Some(TEST_CIPHER_ID.parse().unwrap()),
527            organization_id: None,
528            folder_id: None,
529            collection_ids: vec![],
530            key: None,
531            name: "Test Login".to_string(),
532            notes: None,
533            r#type: CipherType::Login,
534            login: Some(LoginView {
535                username: Some("[email protected]".to_string()),
536                password: Some("password123".to_string()),
537                password_revision_date: None,
538                uris: None,
539                totp: None,
540                autofill_on_page_load: None,
541                http_authentication_enabled: None,
542                fido2_credentials: None,
543            }),
544            identity: None,
545            card: None,
546            secure_note: None,
547            ssh_key: None,
548            bank_account: None,
549            passport: None,
550            drivers_license: None,
551            favorite: false,
552            reprompt: CipherRepromptType::None,
553            organization_use_totp: true,
554            edit: true,
555            permissions: None,
556            view_password: true,
557            local_data: None,
558            attachments: None,
559            attachment_decryption_failures: None,
560            fields: None,
561            password_history: None,
562            creation_date: "2025-01-01T00:00:00Z".parse().unwrap(),
563            deleted_date: None,
564            revision_date: "2025-01-01T00:00:00Z".parse().unwrap(),
565            archived_date: None,
566        }
567    }
568
569    fn create_test_login_cipher(password: &str) -> CipherView {
570        let mut cipher_view = generate_test_cipher();
571        if let Some(ref mut login) = cipher_view.login {
572            login.password = Some(password.to_string());
573        }
574        cipher_view
575    }
576
577    async fn repository_add_cipher(
578        repository: &MemoryRepository<Cipher>,
579        store: &KeyStore<KeySlotIds>,
580        cipher_id: CipherId,
581        name: &str,
582    ) {
583        let cipher = {
584            let mut ctx = store.context();
585
586            Cipher {
587                partial_data: None,
588                id: Some(cipher_id),
589                organization_id: None,
590                folder_id: None,
591                collection_ids: vec![],
592                key: None,
593                name: Some(name.encrypt(&mut ctx, SymmetricKeySlotId::User).unwrap()),
594                notes: None,
595                r#type: CipherType::Login,
596                login: Some(Login {
597                    username: Some("[email protected]")
598                        .map(|u| u.encrypt(&mut ctx, SymmetricKeySlotId::User))
599                        .transpose()
600                        .unwrap(),
601                    password: Some("password123")
602                        .map(|p| p.encrypt(&mut ctx, SymmetricKeySlotId::User))
603                        .transpose()
604                        .unwrap(),
605                    password_revision_date: None,
606                    uris: None,
607                    totp: None,
608                    autofill_on_page_load: None,
609                    http_authentication_enabled: None,
610                    fido2_credentials: None,
611                }),
612                identity: None,
613                card: None,
614                secure_note: None,
615                ssh_key: None,
616                bank_account: None,
617                drivers_license: None,
618                passport: None,
619                favorite: false,
620                reprompt: CipherRepromptType::None,
621                organization_use_totp: true,
622                edit: true,
623                permissions: None,
624                view_password: true,
625                local_data: None,
626                attachments: None,
627                fields: None,
628                password_history: None,
629                creation_date: "2024-01-01T00:00:00Z".parse().unwrap(),
630                deleted_date: None,
631                revision_date: "2024-01-01T00:00:00Z".parse().unwrap(),
632                archived_date: None,
633                data: None,
634            }
635        };
636
637        repository.set(cipher_id, cipher).await.unwrap();
638    }
639
640    #[tokio::test]
641    async fn test_edit_cipher() {
642        let store: KeyStore<KeySlotIds> = KeyStore::default();
643        {
644            let mut ctx = store.context_mut();
645            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
646            ctx.persist_symmetric_key(local_key_id, SymmetricKeySlotId::User)
647                .unwrap();
648        }
649
650        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
651
652        let api_client = ApiClient::new_mocked(move |mock| {
653            mock.ciphers_api
654                .expect_put()
655                .returning(move |_id, body| {
656                    let body = body.unwrap();
657                    Ok(CipherResponseModel {
658                        object: Some("cipher".to_string()),
659                        id: Some(cipher_id.into()),
660                        name: body.name,
661                        r#type: body.r#type,
662                        organization_id: body
663                            .organization_id
664                            .as_ref()
665                            .and_then(|id| uuid::Uuid::parse_str(id).ok()),
666                        folder_id: body
667                            .folder_id
668                            .as_ref()
669                            .and_then(|id| uuid::Uuid::parse_str(id).ok()),
670                        favorite: body.favorite,
671                        reprompt: body.reprompt,
672                        key: body.key,
673                        notes: body.notes,
674                        view_password: Some(true),
675                        edit: Some(true),
676                        organization_use_totp: Some(true),
677                        revision_date: Some("2025-01-01T00:00:00Z".to_string()),
678                        creation_date: Some("2025-01-01T00:00:00Z".to_string()),
679                        deleted_date: None,
680                        login: body.login,
681                        card: body.card,
682                        identity: body.identity,
683                        secure_note: body.secure_note,
684                        ssh_key: body.ssh_key,
685                        bank_account: body.bank_account,
686                        drivers_license: body.drivers_license,
687                        passport: body.passport,
688                        fields: body.fields,
689                        password_history: body.password_history,
690                        attachments: None,
691                        permissions: None,
692                        data: None,
693                        partial_data: None,
694                        archived_date: None,
695                    })
696                })
697                .once();
698        });
699
700        let collection_id: CollectionId = "a4e13cc0-1234-5678-abcd-b181009709b8".parse().unwrap();
701
702        let repository = MemoryRepository::<Cipher>::default();
703        repository_add_cipher(&repository, &store, cipher_id, "old_name").await;
704        // Update the stored cipher to include a collection_id so we can verify it is preserved.
705        let mut stored = repository.get(cipher_id).await.unwrap().unwrap();
706        stored.collection_ids = vec![collection_id];
707        repository.set(cipher_id, stored).await.unwrap();
708
709        let cipher_view = generate_test_cipher();
710
711        let request = cipher_view.try_into().unwrap();
712
713        let result = edit_cipher(
714            &store,
715            &api_client,
716            &repository,
717            TEST_USER_ID.parse().unwrap(),
718            request,
719            false,
720            false,
721        )
722        .await
723        .unwrap();
724
725        assert_eq!(result.id, Some(cipher_id));
726        assert_eq!(result.name, "Test Login");
727        // collection_ids must be preserved even though CipherResponseModel omits them.
728        assert_eq!(result.collection_ids, vec![collection_id]);
729    }
730
731    /// Fixed org id + key for the PAM-gated fixtures — a partial is always org-owned — with a
732    /// `partial_data` envelope encrypted under that key. Same vectors as the ones pinned in
733    /// `cipher.rs`, so both sides exercise identical ciphertext.
734    const GATED_ORG_UUID: &str = "3cf0d3ba-3ded-4bf3-a51c-b03fd9ac6e07";
735    const GATED_ORG_KEY_B64: &str =
736        "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==";
737    const GATED_LOGIN_ENVELOPE: &str = r#"{"name":"2.qip4DSwdOzU2KwY3jgDjUg==|CsGRQgTwAzmszz+dkk5xIg==|rmW/mlnHq2MulR9uNKclD+1UBFLfOimedkq5tPRSLOc=","uris":[{"uri":"2.2na8mpfA1B1OBTUHkDz+fw==|yTWB1nEf3EHIZgsDINM8JnTYyxf7KVZvXraIGAVOiEg=|i2swsODSjEMRaYNnBHAigdphZBBUg2lkPNo763fX12w=","uriChecksum":null,"match":null}]}"#;
738
739    fn gated_key_store() -> (OrganizationId, KeyStore<KeySlotIds>) {
740        let org: OrganizationId = GATED_ORG_UUID.parse().unwrap();
741        let org_key: SymmetricCryptoKey = GATED_ORG_KEY_B64.to_string().try_into().unwrap();
742        let key_store = create_test_crypto_with_user_and_org_key(
743            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
744            org,
745            org_key,
746        );
747        (org, key_store)
748    }
749
750    /// The copy local state holds for a gated cipher: the reduced envelope and nothing else.
751    fn gated_stored_cipher(cipher_id: CipherId, organization_id: OrganizationId) -> Cipher {
752        Cipher {
753            partial_data: Some(GATED_LOGIN_ENVELOPE.to_string()),
754            id: Some(cipher_id),
755            organization_id: Some(organization_id),
756            folder_id: None,
757            collection_ids: vec![],
758            key: None,
759            name: None,
760            notes: None,
761            r#type: CipherType::Login,
762            login: None,
763            identity: None,
764            card: None,
765            secure_note: None,
766            ssh_key: None,
767            bank_account: None,
768            drivers_license: None,
769            passport: None,
770            favorite: false,
771            reprompt: CipherRepromptType::None,
772            organization_use_totp: false,
773            edit: true,
774            permissions: None,
775            view_password: true,
776            local_data: None,
777            attachments: None,
778            fields: None,
779            password_history: None,
780            creation_date: "2024-01-01T00:00:00Z".parse().unwrap(),
781            deleted_date: None,
782            revision_date: "2024-01-01T00:00:00Z".parse().unwrap(),
783            archived_date: None,
784            data: None,
785        }
786    }
787
788    /// The full original a caller obtains from a lease-authorised read: one prior history entry
789    /// and the password this edit replaces.
790    fn gated_original_view(organization_id: OrganizationId) -> CipherView {
791        let mut view = create_test_login_cipher("old_password");
792        view.organization_id = Some(organization_id);
793        view.password_history = Some(vec![PasswordHistoryView {
794            password: "older_password".to_string(),
795            last_used_date: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
796        }]);
797        view
798    }
799
800    /// The regular edit path builds its original from local state, which for a gated cipher only
801    /// ever holds the partial copy. Editing on that would blank every withheld field and drop the
802    /// item's password history, so it must refuse — before it reaches the server.
803    #[tokio::test]
804    async fn test_edit_refuses_a_gated_stored_cipher() {
805        let (org, store) = gated_key_store();
806        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
807
808        // Deliberately no `expect_put`: the guard has to fire before any request is built.
809        let api_client = ApiClient::new_mocked(|_mock| {});
810
811        let repository = MemoryRepository::<Cipher>::default();
812        repository
813            .set(cipher_id, gated_stored_cipher(cipher_id, org))
814            .await
815            .unwrap();
816
817        let mut cipher_view = generate_test_cipher();
818        cipher_view.organization_id = Some(org);
819
820        let result = edit_cipher(
821            &store,
822            &api_client,
823            &repository,
824            TEST_USER_ID.parse().unwrap(),
825            cipher_view.try_into().unwrap(),
826            false,
827            false,
828        )
829        .await;
830
831        assert!(matches!(result, Err(EditCipherError::GatedCipher)));
832    }
833
834    /// Handing the gated path the partial view the caller already had puts us back in exactly the
835    /// case the regular path refuses, with the blanks supplied by the caller instead of by state.
836    #[tokio::test]
837    async fn test_edit_gated_refuses_a_partial_original() {
838        let (org, store) = gated_key_store();
839        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
840        let api_client = ApiClient::new_mocked(|_mock| {});
841
842        let repository = MemoryRepository::<Cipher>::default();
843        repository
844            .set(cipher_id, gated_stored_cipher(cipher_id, org))
845            .await
846            .unwrap();
847
848        let mut cipher_view = generate_test_cipher();
849        cipher_view.organization_id = Some(org);
850        let mut original = cipher_view.clone();
851        original.partial = true;
852
853        let result = edit_gated_cipher(
854            &store,
855            &api_client,
856            &repository,
857            TEST_USER_ID.parse().unwrap(),
858            cipher_view.try_into().unwrap(),
859            original,
860            false,
861            false,
862        )
863        .await;
864
865        assert!(matches!(result, Err(EditCipherError::PartialOriginal)));
866    }
867
868    /// The whole reason this path exists: password history is diffed against the caller's full
869    /// original, not against the partial copy in state. The partial has no history at all, so a
870    /// wrong original shows up as a short array in the request body.
871    #[tokio::test]
872    async fn test_edit_gated_carries_history_from_the_supplied_original() {
873        let (org, store) = gated_key_store();
874        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
875
876        let api_client = ApiClient::new_mocked(move |mock| {
877            mock.ciphers_api
878                .expect_put()
879                .returning(move |_id, body| {
880                    let body = body.unwrap();
881                    // The original's one prior entry, plus the entry for the password this edit
882                    // replaces. Building on the partial copy would have sent none of either.
883                    assert_eq!(body.password_history.as_ref().map(|h| h.len()), Some(2));
884                    Ok(gated_response_model(cipher_id, org, body.r#type))
885                })
886                .once();
887        });
888
889        let repository = MemoryRepository::<Cipher>::default();
890        repository
891            .set(cipher_id, gated_stored_cipher(cipher_id, org))
892            .await
893            .unwrap();
894
895        let mut cipher_view = create_test_login_cipher("new_password");
896        cipher_view.organization_id = Some(org);
897
898        let result = edit_gated_cipher(
899            &store,
900            &api_client,
901            &repository,
902            TEST_USER_ID.parse().unwrap(),
903            cipher_view.try_into().unwrap(),
904            gated_original_view(org),
905            false,
906            false,
907        )
908        .await
909        .unwrap();
910
911        // The server withholds secrets from a gated write-return, so what comes back — and what
912        // is persisted — is still the reduced shape.
913        assert!(result.partial);
914        let stored = repository.get(cipher_id).await.unwrap().unwrap();
915        assert!(stored.partial_data.is_some());
916    }
917
918    /// Defence in depth for the durable-state property: the server strips a gated write-return, so
919    /// a full one should be unreachable — but were it ever to arrive, persisting it would put
920    /// lease-scoped secrets on disk, outliving the lease that justified them.
921    #[tokio::test]
922    async fn test_edit_gated_does_not_persist_a_full_write_return() {
923        let (org, store) = gated_key_store();
924        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
925
926        let api_client = ApiClient::new_mocked(move |mock| {
927            mock.ciphers_api
928                .expect_put()
929                .returning(move |_id, body| {
930                    let body = body.unwrap();
931                    // A server that has not been taught to strip write-returns.
932                    Ok(CipherResponseModel {
933                        partial_data: None,
934                        name: body.name,
935                        login: body.login,
936                        ..gated_response_model(cipher_id, org, body.r#type)
937                    })
938                })
939                .once();
940        });
941
942        let repository = MemoryRepository::<Cipher>::default();
943        repository
944            .set(cipher_id, gated_stored_cipher(cipher_id, org))
945            .await
946            .unwrap();
947
948        let mut cipher_view = create_test_login_cipher("new_password");
949        cipher_view.organization_id = Some(org);
950
951        let result = edit_gated_cipher(
952            &store,
953            &api_client,
954            &repository,
955            TEST_USER_ID.parse().unwrap(),
956            cipher_view.try_into().unwrap(),
957            gated_original_view(org),
958            false,
959            false,
960        )
961        .await
962        .unwrap();
963
964        // The caller still gets the full view in memory — it is the write to disk that is refused.
965        assert!(!result.partial);
966        let stored = repository.get(cipher_id).await.unwrap().unwrap();
967        assert!(stored.partial_data.is_some(), "local state must stay gated");
968        assert!(
969            stored.login.is_none(),
970            "no secret field may reach local state"
971        );
972    }
973
974    /// A gated write-return: metadata and the reduced envelope, every secret field withheld.
975    fn gated_response_model(
976        cipher_id: CipherId,
977        organization_id: OrganizationId,
978        r#type: Option<bitwarden_api_api::models::CipherType>,
979    ) -> CipherResponseModel {
980        CipherResponseModel {
981            object: Some("cipher".to_string()),
982            id: Some(cipher_id.into()),
983            organization_id: Some(organization_id.into()),
984            r#type,
985            partial_data: Some(GATED_LOGIN_ENVELOPE.to_string()),
986            name: None,
987            notes: None,
988            login: None,
989            card: None,
990            identity: None,
991            secure_note: None,
992            ssh_key: None,
993            bank_account: None,
994            drivers_license: None,
995            passport: None,
996            fields: None,
997            password_history: None,
998            attachments: None,
999            permissions: None,
1000            data: None,
1001            folder_id: None,
1002            favorite: Some(false),
1003            reprompt: None,
1004            key: None,
1005            view_password: Some(true),
1006            edit: Some(true),
1007            organization_use_totp: Some(false),
1008            revision_date: Some("2025-01-01T00:00:00Z".to_string()),
1009            creation_date: Some("2025-01-01T00:00:00Z".to_string()),
1010            deleted_date: None,
1011            archived_date: None,
1012        }
1013    }
1014
1015    #[tokio::test]
1016    async fn test_edit_partial_cipher() {
1017        let store: KeyStore<KeySlotIds> = KeyStore::default();
1018        {
1019            let mut ctx = store.context_mut();
1020            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
1021            ctx.persist_symmetric_key(local_key_id, SymmetricKeySlotId::User)
1022                .unwrap();
1023        }
1024
1025        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
1026        let new_folder_id: FolderId = "9b1e7c8f-3a04-4d2e-9d1e-b18100abcdef".parse().unwrap();
1027
1028        let api_client = ApiClient::new_mocked(move |mock| {
1029            mock.ciphers_api
1030                .expect_put_partial()
1031                .returning(move |id, body| {
1032                    let body = body.unwrap();
1033                    let expected_id: uuid::Uuid = cipher_id.into();
1034                    assert_eq!(id, expected_id);
1035                    assert_eq!(body.favorite, Some(true));
1036                    assert_eq!(
1037                        body.folder_id.as_deref(),
1038                        Some(new_folder_id.to_string().as_str())
1039                    );
1040                    Ok(CipherResponseModel {
1041                        object: Some("cipher".to_string()),
1042                        id: Some(cipher_id.into()),
1043                        name: Some(
1044                            "2.+oPT8B4xJhyhQRe1VkIx0A==|PBtC/bZkggXR+fSnL/pG7g==|UkjRD0VpnUYkjRC/05ZLdEBAmRbr3qWRyJey2bUvR9w=".to_string(),
1045                        ),
1046                        r#type: Some(bitwarden_api_api::models::CipherType::Login),
1047                        organization_id: None,
1048                        folder_id: Some(new_folder_id.into()),
1049                        favorite: Some(true),
1050                        reprompt: Some(bitwarden_api_api::models::CipherRepromptType::None),
1051                        key: None,
1052                        notes: None,
1053                        view_password: Some(true),
1054                        edit: Some(false),
1055                        organization_use_totp: Some(true),
1056                        revision_date: Some("2025-01-02T00:00:00Z".to_string()),
1057                        creation_date: Some("2024-01-01T00:00:00Z".to_string()),
1058                        deleted_date: None,
1059                        login: None,
1060                        card: None,
1061                        identity: None,
1062                        secure_note: None,
1063                        ssh_key: None,
1064                        bank_account: None,
1065                        drivers_license: None,
1066                        passport: None,
1067                        fields: None,
1068                        password_history: None,
1069                        attachments: None,
1070                        permissions: None,
1071                        data: None,
1072                        partial_data: None,
1073                        archived_date: None,
1074                    })
1075                })
1076                .once();
1077        });
1078
1079        let collection_id: CollectionId = "a4e13cc0-1234-5678-abcd-b181009709b8".parse().unwrap();
1080
1081        let repository = MemoryRepository::<Cipher>::default();
1082        repository_add_cipher(&repository, &store, cipher_id, "stored_name").await;
1083        // Stamp a collection id to verify it is preserved across partial edit.
1084        let mut stored = repository.get(cipher_id).await.unwrap().unwrap();
1085        stored.collection_ids = vec![collection_id];
1086        repository.set(cipher_id, stored).await.unwrap();
1087
1088        let request = CipherPartialEditRequest {
1089            id: cipher_id,
1090            folder_id: Some(new_folder_id),
1091            favorite: true,
1092        };
1093
1094        let result = partial_edit_cipher(&store, &api_client, &repository, request, false)
1095            .await
1096            .unwrap();
1097
1098        assert_eq!(result.id, Some(cipher_id));
1099        assert_eq!(result.folder_id, Some(new_folder_id));
1100        assert!(result.favorite);
1101        // Partial endpoint omits collection_ids; they must be preserved from the original.
1102        assert_eq!(result.collection_ids, vec![collection_id]);
1103    }
1104
1105    #[tokio::test]
1106    async fn test_edit_partial_cipher_does_not_exist() {
1107        let store: KeyStore<KeySlotIds> = KeyStore::default();
1108
1109        let repository = MemoryRepository::<Cipher>::default();
1110        let api_client = ApiClient::new_mocked(|_| {});
1111
1112        let request = CipherPartialEditRequest {
1113            id: TEST_CIPHER_ID.parse().unwrap(),
1114            folder_id: None,
1115            favorite: false,
1116        };
1117
1118        let result = partial_edit_cipher(&store, &api_client, &repository, request, false).await;
1119
1120        assert!(matches!(
1121            result.unwrap_err(),
1122            EditCipherError::ItemNotFound(_)
1123        ));
1124    }
1125
1126    #[tokio::test]
1127    async fn test_edit_cipher_does_not_exist() {
1128        let store: KeyStore<KeySlotIds> = KeyStore::default();
1129
1130        let repository = MemoryRepository::<Cipher>::default();
1131
1132        let cipher_view = generate_test_cipher();
1133        let api_client = ApiClient::new_mocked(|_| {});
1134
1135        let request = cipher_view.try_into().unwrap();
1136
1137        let result = edit_cipher(
1138            &store,
1139            &api_client,
1140            &repository,
1141            TEST_USER_ID.parse().unwrap(),
1142            request,
1143            false,
1144            false,
1145        )
1146        .await;
1147
1148        assert!(result.is_err());
1149        assert!(matches!(
1150            result.unwrap_err(),
1151            EditCipherError::ItemNotFound(_)
1152        ));
1153    }
1154
1155    #[tokio::test]
1156    async fn test_edit_cipher_http_error() {
1157        let store: KeyStore<KeySlotIds> = KeyStore::default();
1158        {
1159            let mut ctx = store.context_mut();
1160            let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
1161            ctx.persist_symmetric_key(local_key_id, SymmetricKeySlotId::User)
1162                .unwrap();
1163        }
1164
1165        let cipher_id: CipherId = "5faa9684-c793-4a2d-8a12-b33900187097".parse().unwrap();
1166
1167        let api_client = ApiClient::new_mocked(move |mock| {
1168            mock.ciphers_api
1169                .expect_put()
1170                .returning(move |_id, _body| Err(std::io::Error::other("Simulated error").into()));
1171        });
1172
1173        let repository = MemoryRepository::<Cipher>::default();
1174        repository_add_cipher(&repository, &store, cipher_id, "old_name").await;
1175        let cipher_view = generate_test_cipher();
1176
1177        let request = cipher_view.try_into().unwrap();
1178
1179        let result = edit_cipher(
1180            &store,
1181            &api_client,
1182            &repository,
1183            TEST_USER_ID.parse().unwrap(),
1184            request,
1185            false,
1186            false,
1187        )
1188        .await;
1189
1190        assert!(result.is_err());
1191        assert!(matches!(result.unwrap_err(), EditCipherError::Api(_)));
1192    }
1193
1194    /// Build the edit-side view the way the flow does: request → view, then
1195    /// fold in password history against the decrypted original.
1196    fn edit_view_with_history(new_cipher: CipherView, original: &CipherView) -> CipherView {
1197        let mut view: CipherView =
1198            convert_request_to_cipher_view(CipherEditRequest::try_from(new_cipher).unwrap());
1199        view.update_password_history(original);
1200        view
1201    }
1202
1203    #[test]
1204    fn test_password_history_on_password_change() {
1205        let original_cipher = create_test_login_cipher("old_password");
1206
1207        let start = Utc::now();
1208        let view =
1209            edit_view_with_history(create_test_login_cipher("new_password"), &original_cipher);
1210        let end = Utc::now();
1211        let history = view.password_history.unwrap_or_default();
1212
1213        assert_eq!(history.len(), 1);
1214        assert!(
1215            history[0].last_used_date >= start && history[0].last_used_date <= end,
1216            "last_used_date was not set properly"
1217        );
1218        assert_eq!(history[0].password, "old_password");
1219    }
1220
1221    #[test]
1222    fn test_password_history_on_unchanged_password() {
1223        let original_cipher = create_test_login_cipher("same_password");
1224        let view =
1225            edit_view_with_history(create_test_login_cipher("same_password"), &original_cipher);
1226
1227        assert!(view.password_history.unwrap_or_default().is_empty());
1228    }
1229
1230    #[test]
1231    fn test_password_history_is_preserved() {
1232        let mut original_cipher = create_test_login_cipher("same_password");
1233        original_cipher.password_history = Some(
1234            (0..4)
1235                .map(|i| PasswordHistoryView {
1236                    password: format!("old_password_{}", i),
1237                    last_used_date: Utc.with_ymd_and_hms(2025, i + 1, i + 1, i, i, i).unwrap(),
1238                })
1239                .collect(),
1240        );
1241
1242        let view =
1243            edit_view_with_history(create_test_login_cipher("same_password"), &original_cipher);
1244        let history = view.password_history.unwrap_or_default();
1245
1246        assert_eq!(history[0].password, "old_password_0");
1247
1248        assert_eq!(
1249            history[0].last_used_date,
1250            Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap()
1251        );
1252        assert_eq!(history[1].password, "old_password_1");
1253        assert_eq!(
1254            history[1].last_used_date,
1255            Utc.with_ymd_and_hms(2025, 2, 2, 1, 1, 1).unwrap()
1256        );
1257        assert_eq!(history[2].password, "old_password_2");
1258        assert_eq!(
1259            history[2].last_used_date,
1260            Utc.with_ymd_and_hms(2025, 3, 3, 2, 2, 2).unwrap()
1261        );
1262        assert_eq!(history[3].password, "old_password_3");
1263        assert_eq!(
1264            history[3].last_used_date,
1265            Utc.with_ymd_and_hms(2025, 4, 4, 3, 3, 3).unwrap()
1266        );
1267    }
1268
1269    #[test]
1270    fn test_password_history_with_hidden_fields() {
1271        let mut original_cipher = create_test_login_cipher("password");
1272        original_cipher.fields = Some(vec![FieldView {
1273            name: Some("Secret Key".to_string()),
1274            value: Some("old_secret_value".to_string()),
1275            r#type: FieldType::Hidden,
1276            linked_id: None,
1277        }]);
1278
1279        let mut new_cipher = create_test_login_cipher("password");
1280        new_cipher.fields = Some(vec![FieldView {
1281            name: Some("Secret Key".to_string()),
1282            value: Some("new_secret_value".to_string()),
1283            r#type: FieldType::Hidden,
1284            linked_id: None,
1285        }]);
1286
1287        let view = edit_view_with_history(new_cipher, &original_cipher);
1288        let history = view.password_history.unwrap_or_default();
1289
1290        assert_eq!(history.len(), 1);
1291        assert_eq!(history[0].password, "Secret Key: old_secret_value");
1292    }
1293
1294    #[test]
1295    fn test_password_history_length_limit() {
1296        let mut original_cipher = create_test_login_cipher("password");
1297        original_cipher.password_history = Some(
1298            (0..10)
1299                .map(|i| PasswordHistoryView {
1300                    password: format!("old_password_{}", i),
1301                    last_used_date: Utc::now(),
1302                })
1303                .collect(),
1304        );
1305
1306        let view =
1307            edit_view_with_history(create_test_login_cipher("new_password"), &original_cipher);
1308        let history = view.password_history.unwrap_or_default();
1309
1310        assert_eq!(history.len(), MAX_PASSWORD_HISTORY_ENTRIES);
1311        // Most recent change (original password) should be first
1312        assert_eq!(history[0].password, "password");
1313
1314        assert_eq!(history[1].password, "old_password_0");
1315        assert_eq!(history[2].password, "old_password_1");
1316        assert_eq!(history[3].password, "old_password_2");
1317        assert_eq!(history[4].password, "old_password_3");
1318    }
1319
1320    mod blob_encrypt {
1321        use bitwarden_core::key_management::create_test_crypto_with_user_key;
1322        use bitwarden_crypto::SymmetricCryptoKey;
1323
1324        use super::*;
1325        use crate::cipher::blob::try_parse_blob;
1326
1327        /// `EncryptMode::Blob(CipherView)` clears `password_history` from the
1328        /// wire-shaped `Cipher` — history must travel inside the sealed blob,
1329        /// not as a top-level encrypted field.
1330        #[test]
1331        fn password_history_lives_inside_blob_not_on_wire() {
1332            let store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
1333                SymmetricKeyAlgorithm::Aes256CbcHmac,
1334            ));
1335
1336            let original = create_test_login_cipher("old_password");
1337            let mut view = create_test_login_cipher("new_password");
1338            view.update_password_history(&original);
1339            // Sanity: the in-flight view captured the old password.
1340            assert_eq!(view.password_history.as_ref().unwrap().len(), 1);
1341
1342            let cipher: Cipher = store.encrypt(EncryptMode::Blob(view)).unwrap();
1343
1344            assert!(try_parse_blob(&cipher).is_some());
1345            assert!(
1346                cipher.password_history.is_none(),
1347                "password history must live inside the blob, not on the wire",
1348            );
1349            assert!(cipher.login.is_none());
1350            assert!(cipher.notes.is_none());
1351        }
1352
1353        /// End-to-end: a password change picked up by `update_password_history`
1354        /// is sealed inside the blob and unsealed back out by
1355        /// `BlobAwareDecrypt`.
1356        #[test]
1357        fn password_history_round_trips_through_the_blob() {
1358            let store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
1359                SymmetricKeyAlgorithm::Aes256CbcHmac,
1360            ));
1361
1362            let original = create_test_login_cipher("old_password");
1363            let mut view = create_test_login_cipher("new_password");
1364            view.update_password_history(&original);
1365
1366            let cipher: Cipher = store.encrypt(EncryptMode::Blob(view)).unwrap();
1367            let restored: CipherView = store.decrypt(&cipher).unwrap();
1368
1369            let history = restored
1370                .password_history
1371                .expect("history should round-trip through the blob");
1372            assert_eq!(history.len(), 1);
1373            assert_eq!(history[0].password, "old_password");
1374        }
1375    }
1376}