1use bitwarden_api_api::models::{CipherCollectionsRequestModel, 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 chrono::{DateTime, Utc};
15use serde::{Deserialize, Serialize};
16use thiserror::Error;
17#[cfg(feature = "wasm")]
18use tsify::Tsify;
19#[cfg(feature = "wasm")]
20use wasm_bindgen::prelude::*;
21
22use super::CiphersClient;
23use crate::{
24 AttachmentView, Cipher, CipherId, CipherRepromptType, CipherType, CipherView, FieldView,
25 FolderId, ItemNotFoundError, PasswordHistoryView, VaultParseError,
26 cipher::cipher::PartialCipher, cipher_view_type::CipherViewType,
27 password_history::MAX_PASSWORD_HISTORY_ENTRIES,
28};
29
30#[allow(missing_docs)]
31#[bitwarden_error(flat)]
32#[derive(Debug, Error)]
33pub enum EditCipherError {
34 #[error(transparent)]
35 ItemNotFound(#[from] ItemNotFoundError),
36 #[error(transparent)]
37 Crypto(#[from] CryptoError),
38 #[error(transparent)]
39 Api(#[from] ApiError),
40 #[error(transparent)]
41 VaultParse(#[from] VaultParseError),
42 #[error(transparent)]
43 MissingField(#[from] MissingFieldError),
44 #[error(transparent)]
45 NotAuthenticated(#[from] NotAuthenticatedError),
46 #[error(transparent)]
47 Repository(#[from] RepositoryError),
48 #[error(transparent)]
49 Uuid(#[from] uuid::Error),
50}
51
52impl<T> From<bitwarden_api_api::apis::Error<T>> for EditCipherError {
53 fn from(val: bitwarden_api_api::apis::Error<T>) -> Self {
54 Self::Api(val.into())
55 }
56}
57
58#[derive(Clone, Serialize, Deserialize, Debug)]
60#[serde(rename_all = "camelCase")]
61#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
62#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
63pub struct CipherEditRequest {
64 pub id: CipherId,
65
66 pub organization_id: Option<OrganizationId>,
67 pub folder_id: Option<FolderId>,
68 pub favorite: bool,
69 pub reprompt: CipherRepromptType,
70 pub name: String,
71 pub notes: Option<String>,
72 pub fields: Vec<FieldView>,
73 pub r#type: CipherViewType,
74 pub revision_date: DateTime<Utc>,
75 pub archived_date: Option<DateTime<Utc>>,
76 pub attachments: Vec<AttachmentView>,
77 pub key: Option<EncString>,
78}
79
80impl TryFrom<CipherView> for CipherEditRequest {
81 type Error = MissingFieldError;
82
83 fn try_from(value: CipherView) -> Result<Self, Self::Error> {
84 let type_data = match value.r#type {
85 CipherType::Login => value.login.map(CipherViewType::Login),
86 CipherType::SecureNote => value.secure_note.map(CipherViewType::SecureNote),
87 CipherType::Card => value.card.map(CipherViewType::Card),
88 CipherType::Identity => value.identity.map(CipherViewType::Identity),
89 CipherType::SshKey => value.ssh_key.map(CipherViewType::SshKey),
90 };
91 Ok(Self {
92 id: value.id.ok_or(MissingFieldError("id"))?,
93 organization_id: value.organization_id,
94 folder_id: value.folder_id,
95 favorite: value.favorite,
96 reprompt: value.reprompt,
97 key: value.key,
98 name: value.name,
99 notes: value.notes,
100 fields: value.fields.unwrap_or_default(),
101 r#type: require!(type_data),
102 attachments: value.attachments.unwrap_or_default(),
103 revision_date: value.revision_date,
104 archived_date: value.archived_date,
105 })
106 }
107}
108
109impl CipherEditRequest {
110 pub(super) fn generate_cipher_key(
111 &mut self,
112 ctx: &mut KeyStoreContext<KeyIds>,
113 key: SymmetricKeyId,
114 ) -> Result<(), CryptoError> {
115 let old_key = Cipher::decrypt_cipher_key(ctx, key, &self.key)?;
116
117 let new_key = ctx.generate_symmetric_key();
118
119 self.r#type
121 .as_login_view_mut()
122 .map(|l| l.reencrypt_fido2_credentials(ctx, old_key, new_key))
123 .transpose()?;
124 AttachmentView::reencrypt_keys(&mut self.attachments, ctx, old_key, new_key)?;
125 Ok(())
126 }
127}
128
129#[derive(Clone, Debug)]
132pub(super) struct CipherEditRequestInternal {
133 pub(super) edit_request: CipherEditRequest,
134 pub(super) password_history: Vec<PasswordHistoryView>,
135}
136
137impl CipherEditRequestInternal {
138 pub(super) fn new(edit_request: CipherEditRequest, orig_cipher: &CipherView) -> Self {
139 let mut internal_req = Self {
140 edit_request,
141 password_history: vec![],
142 };
143 internal_req.update_password_history(orig_cipher);
144
145 internal_req
146 }
147
148 fn update_password_history(&mut self, original_cipher: &CipherView) {
149 let changes = self
150 .detect_login_password_changes(original_cipher)
151 .into_iter()
152 .chain(self.detect_hidden_field_changes(original_cipher));
153 let history: Vec<_> = changes
154 .rev()
155 .chain(original_cipher.password_history.iter().flatten().cloned())
156 .take(MAX_PASSWORD_HISTORY_ENTRIES)
157 .collect();
158
159 self.password_history = history;
160 }
161
162 fn detect_login_password_changes(
163 &mut self,
164 original_cipher: &CipherView,
165 ) -> Vec<PasswordHistoryView> {
166 self.edit_request
167 .r#type
168 .as_login_view_mut()
169 .map_or(vec![], |login| {
170 login.detect_password_change(&original_cipher.login)
171 })
172 }
173
174 fn detect_hidden_field_changes(
175 &self,
176 original_cipher: &CipherView,
177 ) -> Vec<PasswordHistoryView> {
178 FieldView::detect_hidden_field_changes(
179 self.edit_request.fields.as_slice(),
180 original_cipher.fields.as_deref().unwrap_or(&[]),
181 )
182 }
183
184 fn generate_checksums(&mut self) {
185 if let Some(login) = &mut self.edit_request.r#type.as_login_view_mut() {
186 login.generate_checksums();
187 }
188 }
189}
190
191impl CompositeEncryptable<KeyIds, SymmetricKeyId, CipherRequestModel>
192 for CipherEditRequestInternal
193{
194 fn encrypt_composite(
195 &self,
196 ctx: &mut KeyStoreContext<KeyIds>,
197 key: SymmetricKeyId,
198 ) -> Result<CipherRequestModel, CryptoError> {
199 let mut cipher_data = (*self).clone();
200 cipher_data.generate_checksums();
201
202 let cipher_key = Cipher::decrypt_cipher_key(ctx, key, &self.edit_request.key)?;
203
204 let cipher_request = CipherRequestModel {
205 encrypted_for: None,
206 r#type: Some(cipher_data.edit_request.r#type.get_cipher_type().into()),
207 organization_id: cipher_data
208 .edit_request
209 .organization_id
210 .map(|id| id.to_string()),
211 folder_id: cipher_data.edit_request.folder_id.map(|id| id.to_string()),
212 favorite: Some(cipher_data.edit_request.favorite),
213 reprompt: Some(cipher_data.edit_request.reprompt.into()),
214 key: cipher_data.edit_request.key.map(|k| k.to_string()),
215 name: cipher_data
216 .edit_request
217 .name
218 .encrypt(ctx, cipher_key)?
219 .to_string(),
220 notes: cipher_data
221 .edit_request
222 .notes
223 .as_ref()
224 .map(|n| n.encrypt(ctx, cipher_key))
225 .transpose()?
226 .map(|n| n.to_string()),
227 fields: Some(
228 cipher_data
229 .edit_request
230 .fields
231 .encrypt_composite(ctx, cipher_key)?
232 .into_iter()
233 .map(|f| f.into())
234 .collect(),
235 ),
236 password_history: Some(
237 cipher_data
238 .password_history
239 .encrypt_composite(ctx, cipher_key)?
240 .into_iter()
241 .map(Into::into)
242 .collect(),
243 ),
244 attachments: None,
245 attachments2: Some(
246 cipher_data
247 .edit_request
248 .attachments
249 .encrypt_composite(ctx, cipher_key)?
250 .into_iter()
251 .map(|a| {
252 Ok((
253 a.id.clone().ok_or(CryptoError::MissingField("id"))?,
254 a.into(),
255 )) as Result<_, CryptoError>
256 })
257 .collect::<Result<_, _>>()?,
258 ),
259 login: cipher_data
260 .edit_request
261 .r#type
262 .as_login_view()
263 .map(|l| l.encrypt_composite(ctx, cipher_key))
264 .transpose()?
265 .map(|l| Box::new(l.into())),
266 card: cipher_data
267 .edit_request
268 .r#type
269 .as_card_view()
270 .map(|c| c.encrypt_composite(ctx, cipher_key))
271 .transpose()?
272 .map(|c| Box::new(c.into())),
273 identity: cipher_data
274 .edit_request
275 .r#type
276 .as_identity_view()
277 .map(|i| i.encrypt_composite(ctx, cipher_key))
278 .transpose()?
279 .map(|c| Box::new(c.into())),
280
281 secure_note: cipher_data
282 .edit_request
283 .r#type
284 .as_secure_note_view()
285 .map(|i| i.encrypt_composite(ctx, cipher_key))
286 .transpose()?
287 .map(|c| Box::new(c.into())),
288 ssh_key: cipher_data
289 .edit_request
290 .r#type
291 .as_ssh_key_view()
292 .map(|i| i.encrypt_composite(ctx, cipher_key))
293 .transpose()?
294 .map(|c| Box::new(c.into())),
295
296 last_known_revision_date: Some(
297 cipher_data
298 .edit_request
299 .revision_date
300 .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
301 ),
302 archived_date: cipher_data
303 .edit_request
304 .archived_date
305 .map(|d| d.to_rfc3339()),
306 data: None,
307 };
308
309 Ok(cipher_request)
310 }
311}
312
313impl IdentifyKey<SymmetricKeyId> for CipherEditRequest {
314 fn key_identifier(&self) -> SymmetricKeyId {
315 match self.organization_id {
316 Some(organization_id) => SymmetricKeyId::Organization(organization_id),
317 None => SymmetricKeyId::User,
318 }
319 }
320}
321
322impl IdentifyKey<SymmetricKeyId> for CipherEditRequestInternal {
323 fn key_identifier(&self) -> SymmetricKeyId {
324 self.edit_request.key_identifier()
325 }
326}
327
328async fn edit_cipher<R: Repository<Cipher> + ?Sized>(
329 key_store: &KeyStore<KeyIds>,
330 api_client: &bitwarden_api_api::apis::ApiClient,
331 repository: &R,
332 encrypted_for: UserId,
333 request: CipherEditRequest,
334) -> Result<CipherView, EditCipherError> {
335 let cipher_id = request.id;
336
337 let original_cipher = repository.get(cipher_id).await?.ok_or(ItemNotFoundError)?;
338 let original_cipher_view: CipherView = key_store.decrypt(&original_cipher)?;
339
340 let request = CipherEditRequestInternal::new(request, &original_cipher_view);
341
342 let mut cipher_request = key_store.encrypt(request)?;
343 cipher_request.encrypted_for = Some(encrypted_for.into());
344
345 let cipher: Cipher = api_client
346 .ciphers_api()
347 .put(cipher_id.into(), Some(cipher_request))
348 .await
349 .map_err(ApiError::from)?
350 .try_into()?;
351 debug_assert!(cipher.id.unwrap_or_default() == cipher_id);
352 repository.set(cipher_id, cipher.clone()).await?;
353
354 Ok(key_store.decrypt(&cipher)?)
355}
356
357#[cfg_attr(feature = "wasm", wasm_bindgen)]
358impl CiphersClient {
359 pub async fn edit(
361 &self,
362 mut request: CipherEditRequest,
363 ) -> Result<CipherView, EditCipherError> {
364 let key_store = self.client.internal.get_key_store();
365 let config = self.client.internal.get_api_configurations();
366 let repository = self.get_repository()?;
367
368 let user_id = self
369 .client
370 .internal
371 .get_user_id()
372 .ok_or(NotAuthenticatedError)?;
373
374 if request.key.is_none()
377 && self
378 .client
379 .internal
380 .get_flags()
381 .enable_cipher_key_encryption
382 {
383 let key = request.key_identifier();
384 request.generate_cipher_key(&mut key_store.context(), key)?;
385 }
386
387 edit_cipher(
388 key_store,
389 &config.api_client,
390 repository.as_ref(),
391 user_id,
392 request,
393 )
394 .await
395 }
396
397 pub async fn update_collection(
399 &self,
400 cipher_id: CipherId,
401 collection_ids: Vec<CollectionId>,
402 is_admin: bool,
403 ) -> Result<CipherView, EditCipherError> {
404 let req = CipherCollectionsRequestModel {
405 collection_ids: collection_ids
406 .into_iter()
407 .map(|id| id.to_string())
408 .collect(),
409 };
410 let repository = self.get_repository()?;
411
412 let api_config = self.client.internal.get_api_configurations();
413 let api = api_config.api_client.ciphers_api();
414 let orig_cipher = repository.get(cipher_id).await?;
415 let cipher = if is_admin {
416 api.put_collections_admin(&cipher_id.to_string(), Some(req))
417 .await?
418 .merge_with_cipher(orig_cipher)?
419 } else {
420 let response: Cipher = api
421 .put_collections(cipher_id.into(), Some(req))
422 .await?
423 .merge_with_cipher(orig_cipher)?;
424 repository.set(cipher_id, response.clone()).await?;
425 response
426 };
427
428 Ok(self.decrypt(cipher).map_err(|_| CryptoError::KeyDecrypt)?)
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use bitwarden_api_api::{apis::ApiClient, models::CipherResponseModel};
435 use bitwarden_core::key_management::SymmetricKeyId;
436 use bitwarden_crypto::{KeyStore, PrimitiveEncryptable, SymmetricKeyAlgorithm};
437 use bitwarden_test::MemoryRepository;
438 use chrono::TimeZone;
439
440 use super::*;
441 use crate::{
442 Cipher, CipherId, CipherRepromptType, CipherType, FieldType, Login, LoginView,
443 PasswordHistoryView,
444 };
445
446 const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
447 const TEST_USER_ID: &str = "550e8400-e29b-41d4-a716-446655440000";
448
449 fn generate_test_cipher() -> CipherView {
450 CipherView {
451 id: Some(TEST_CIPHER_ID.parse().unwrap()),
452 organization_id: None,
453 folder_id: None,
454 collection_ids: vec![],
455 key: None,
456 name: "Test Login".to_string(),
457 notes: None,
458 r#type: CipherType::Login,
459 login: Some(LoginView {
460 username: Some("[email protected]".to_string()),
461 password: Some("password123".to_string()),
462 password_revision_date: None,
463 uris: None,
464 totp: None,
465 autofill_on_page_load: None,
466 fido2_credentials: None,
467 }),
468 identity: None,
469 card: None,
470 secure_note: None,
471 ssh_key: None,
472 favorite: false,
473 reprompt: CipherRepromptType::None,
474 organization_use_totp: true,
475 edit: true,
476 permissions: None,
477 view_password: true,
478 local_data: None,
479 attachments: None,
480 attachment_decryption_failures: None,
481 fields: None,
482 password_history: None,
483 creation_date: "2025-01-01T00:00:00Z".parse().unwrap(),
484 deleted_date: None,
485 revision_date: "2025-01-01T00:00:00Z".parse().unwrap(),
486 archived_date: None,
487 }
488 }
489
490 fn create_test_login_cipher(password: &str) -> CipherView {
491 let mut cipher_view = generate_test_cipher();
492 if let Some(ref mut login) = cipher_view.login {
493 login.password = Some(password.to_string());
494 }
495 cipher_view
496 }
497
498 async fn repository_add_cipher(
499 repository: &MemoryRepository<Cipher>,
500 store: &KeyStore<KeyIds>,
501 cipher_id: CipherId,
502 name: &str,
503 ) {
504 let cipher = {
505 let mut ctx = store.context();
506
507 Cipher {
508 id: Some(cipher_id),
509 organization_id: None,
510 folder_id: None,
511 collection_ids: vec![],
512 key: None,
513 name: name.encrypt(&mut ctx, SymmetricKeyId::User).unwrap(),
514 notes: None,
515 r#type: CipherType::Login,
516 login: Some(Login {
517 username: Some("[email protected]")
518 .map(|u| u.encrypt(&mut ctx, SymmetricKeyId::User))
519 .transpose()
520 .unwrap(),
521 password: Some("password123")
522 .map(|p| p.encrypt(&mut ctx, SymmetricKeyId::User))
523 .transpose()
524 .unwrap(),
525 password_revision_date: None,
526 uris: None,
527 totp: None,
528 autofill_on_page_load: None,
529 fido2_credentials: None,
530 }),
531 identity: None,
532 card: None,
533 secure_note: None,
534 ssh_key: None,
535 favorite: false,
536 reprompt: CipherRepromptType::None,
537 organization_use_totp: true,
538 edit: true,
539 permissions: None,
540 view_password: true,
541 local_data: None,
542 attachments: None,
543 fields: None,
544 password_history: None,
545 creation_date: "2024-01-01T00:00:00Z".parse().unwrap(),
546 deleted_date: None,
547 revision_date: "2024-01-01T00:00:00Z".parse().unwrap(),
548 archived_date: None,
549 data: None,
550 }
551 };
552
553 repository.set(cipher_id, cipher).await.unwrap();
554 }
555
556 #[tokio::test]
557 async fn test_edit_cipher() {
558 let store: KeyStore<KeyIds> = KeyStore::default();
559 {
560 let mut ctx = store.context_mut();
561 let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
562 ctx.persist_symmetric_key(local_key_id, SymmetricKeyId::User)
563 .unwrap();
564 }
565
566 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
567
568 let api_client = ApiClient::new_mocked(move |mock| {
569 mock.ciphers_api
570 .expect_put()
571 .returning(move |_id, body| {
572 let body = body.unwrap();
573 Ok(CipherResponseModel {
574 object: Some("cipher".to_string()),
575 id: Some(cipher_id.into()),
576 name: Some(body.name),
577 r#type: body.r#type,
578 organization_id: body
579 .organization_id
580 .as_ref()
581 .and_then(|id| uuid::Uuid::parse_str(id).ok()),
582 folder_id: body
583 .folder_id
584 .as_ref()
585 .and_then(|id| uuid::Uuid::parse_str(id).ok()),
586 favorite: body.favorite,
587 reprompt: body.reprompt,
588 key: body.key,
589 notes: body.notes,
590 view_password: Some(true),
591 edit: Some(true),
592 organization_use_totp: Some(true),
593 revision_date: Some("2025-01-01T00:00:00Z".to_string()),
594 creation_date: Some("2025-01-01T00:00:00Z".to_string()),
595 deleted_date: None,
596 login: body.login,
597 card: body.card,
598 identity: body.identity,
599 secure_note: body.secure_note,
600 ssh_key: body.ssh_key,
601 fields: body.fields,
602 password_history: body.password_history,
603 attachments: None,
604 permissions: None,
605 data: None,
606 archived_date: None,
607 })
608 })
609 .once();
610 });
611
612 let repository = MemoryRepository::<Cipher>::default();
613 repository_add_cipher(&repository, &store, cipher_id, "old_name").await;
614 let cipher_view = generate_test_cipher();
615
616 let request = cipher_view.try_into().unwrap();
617
618 let result = edit_cipher(
619 &store,
620 &api_client,
621 &repository,
622 TEST_USER_ID.parse().unwrap(),
623 request,
624 )
625 .await
626 .unwrap();
627
628 assert_eq!(result.id, Some(cipher_id));
629 assert_eq!(result.name, "Test Login");
630 }
631
632 #[tokio::test]
633 async fn test_edit_cipher_does_not_exist() {
634 let store: KeyStore<KeyIds> = KeyStore::default();
635
636 let repository = MemoryRepository::<Cipher>::default();
637
638 let cipher_view = generate_test_cipher();
639 let api_client = ApiClient::new_mocked(|_| {});
640
641 let request = cipher_view.try_into().unwrap();
642
643 let result = edit_cipher(
644 &store,
645 &api_client,
646 &repository,
647 TEST_USER_ID.parse().unwrap(),
648 request,
649 )
650 .await;
651
652 assert!(result.is_err());
653 assert!(matches!(
654 result.unwrap_err(),
655 EditCipherError::ItemNotFound(_)
656 ));
657 }
658
659 #[tokio::test]
660 async fn test_edit_cipher_http_error() {
661 let store: KeyStore<KeyIds> = KeyStore::default();
662 {
663 let mut ctx = store.context_mut();
664 let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
665 ctx.persist_symmetric_key(local_key_id, SymmetricKeyId::User)
666 .unwrap();
667 }
668
669 let cipher_id: CipherId = "5faa9684-c793-4a2d-8a12-b33900187097".parse().unwrap();
670
671 let api_client = ApiClient::new_mocked(move |mock| {
672 mock.ciphers_api.expect_put().returning(move |_id, _body| {
673 Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
674 "Simulated error",
675 )))
676 });
677 });
678
679 let repository = MemoryRepository::<Cipher>::default();
680 repository_add_cipher(&repository, &store, cipher_id, "old_name").await;
681 let cipher_view = generate_test_cipher();
682
683 let request = cipher_view.try_into().unwrap();
684
685 let result = edit_cipher(
686 &store,
687 &api_client,
688 &repository,
689 TEST_USER_ID.parse().unwrap(),
690 request,
691 )
692 .await;
693
694 assert!(result.is_err());
695 assert!(matches!(result.unwrap_err(), EditCipherError::Api(_)));
696 }
697
698 #[test]
699 fn test_password_history_on_password_change() {
700 let original_cipher = create_test_login_cipher("old_password");
701 let edit_request =
702 CipherEditRequest::try_from(create_test_login_cipher("new_password")).unwrap();
703
704 let start = Utc::now();
705 let internal_req = CipherEditRequestInternal::new(edit_request, &original_cipher);
706 let history = internal_req.password_history;
707 let end = Utc::now();
708
709 assert_eq!(history.len(), 1);
710 assert!(
711 history[0].last_used_date >= start && history[0].last_used_date <= end,
712 "last_used_date was not set properly"
713 );
714 assert_eq!(history[0].password, "old_password");
715 }
716
717 #[test]
718 fn test_password_history_on_unchanged_password() {
719 let original_cipher = create_test_login_cipher("same_password");
720 let edit_request =
721 CipherEditRequest::try_from(create_test_login_cipher("same_password")).unwrap();
722
723 let internal_req = CipherEditRequestInternal::new(edit_request, &original_cipher);
724 let password_history = internal_req.password_history;
725
726 assert!(password_history.is_empty());
727 }
728
729 #[test]
730 fn test_password_history_is_preserved() {
731 let mut original_cipher = create_test_login_cipher("same_password");
732 original_cipher.password_history = Some(
733 (0..4)
734 .map(|i| PasswordHistoryView {
735 password: format!("old_password_{}", i),
736 last_used_date: Utc.with_ymd_and_hms(2025, i + 1, i + 1, i, i, i).unwrap(),
737 })
738 .collect(),
739 );
740
741 let edit_request =
742 CipherEditRequest::try_from(create_test_login_cipher("same_password")).unwrap();
743 let internal_req = CipherEditRequestInternal::new(edit_request, &original_cipher);
744 let history = internal_req.password_history;
745
746 assert_eq!(history[0].password, "old_password_0");
747
748 assert_eq!(
749 history[0].last_used_date,
750 Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap()
751 );
752 assert_eq!(history[1].password, "old_password_1");
753 assert_eq!(
754 history[1].last_used_date,
755 Utc.with_ymd_and_hms(2025, 2, 2, 1, 1, 1).unwrap()
756 );
757 assert_eq!(history[2].password, "old_password_2");
758 assert_eq!(
759 history[2].last_used_date,
760 Utc.with_ymd_and_hms(2025, 3, 3, 2, 2, 2).unwrap()
761 );
762 assert_eq!(history[3].password, "old_password_3");
763 assert_eq!(
764 history[3].last_used_date,
765 Utc.with_ymd_and_hms(2025, 4, 4, 3, 3, 3).unwrap()
766 );
767 }
768
769 #[test]
770 fn test_password_history_with_hidden_fields() {
771 let mut original_cipher = create_test_login_cipher("password");
772 original_cipher.fields = Some(vec![FieldView {
773 name: Some("Secret Key".to_string()),
774 value: Some("old_secret_value".to_string()),
775 r#type: FieldType::Hidden,
776 linked_id: None,
777 }]);
778
779 let mut new_cipher = create_test_login_cipher("password");
780 new_cipher.fields = Some(vec![FieldView {
781 name: Some("Secret Key".to_string()),
782 value: Some("new_secret_value".to_string()),
783 r#type: FieldType::Hidden,
784 linked_id: None,
785 }]);
786
787 let edit_request = CipherEditRequest::try_from(new_cipher).unwrap();
788
789 let internal_req = CipherEditRequestInternal::new(edit_request, &original_cipher);
790 let history = internal_req.password_history;
791
792 assert_eq!(history.len(), 1);
793 assert_eq!(history[0].password, "Secret Key: old_secret_value");
794 }
795
796 #[test]
797 fn test_password_history_length_limit() {
798 let mut original_cipher = create_test_login_cipher("password");
799 original_cipher.password_history = Some(
800 (0..10)
801 .map(|i| PasswordHistoryView {
802 password: format!("old_password_{}", i),
803 last_used_date: Utc::now(),
804 })
805 .collect(),
806 );
807
808 let edit_request =
810 CipherEditRequest::try_from(create_test_login_cipher("new_password")).unwrap();
811
812 let internal_req = CipherEditRequestInternal::new(edit_request, &original_cipher);
813 let history = internal_req.password_history;
814
815 assert_eq!(history.len(), MAX_PASSWORD_HISTORY_ENTRIES);
816 assert_eq!(history[0].password, "password");
818
819 assert_eq!(history[1].password, "old_password_0");
820 assert_eq!(history[2].password, "old_password_1");
821 assert_eq!(history[3].password, "old_password_2");
822 assert_eq!(history[4].password, "old_password_3");
823 }
824}