Skip to main content

bitwarden_vault/cipher/cipher_client/
get.rs

1use bitwarden_core::key_management::KeyIds;
2use bitwarden_crypto::{CryptoError, KeyStore};
3use bitwarden_error::bitwarden_error;
4use bitwarden_state::repository::{Repository, RepositoryError};
5use thiserror::Error;
6#[cfg(feature = "wasm")]
7use wasm_bindgen::prelude::wasm_bindgen;
8
9use super::CiphersClient;
10use crate::{Cipher, CipherView, ItemNotFoundError, cipher::cipher::DecryptCipherListResult};
11
12#[allow(missing_docs)]
13#[bitwarden_error(flat)]
14#[derive(Debug, Error)]
15pub enum GetCipherError {
16    #[error(transparent)]
17    ItemNotFound(#[from] ItemNotFoundError),
18    #[error(transparent)]
19    Crypto(#[from] CryptoError),
20    #[error(transparent)]
21    Repository(#[from] RepositoryError),
22}
23
24async fn get_cipher(
25    store: &KeyStore<KeyIds>,
26    repository: &dyn Repository<Cipher>,
27    id: &str,
28) -> Result<CipherView, GetCipherError> {
29    let id = id.parse().map_err(|_| ItemNotFoundError)?;
30    let cipher = repository.get(id).await?.ok_or(ItemNotFoundError)?;
31
32    Ok(store.decrypt(&cipher)?)
33}
34
35async fn list_ciphers(
36    store: &KeyStore<KeyIds>,
37    repository: &dyn Repository<Cipher>,
38) -> Result<DecryptCipherListResult, GetCipherError> {
39    let ciphers = repository.list().await?;
40    let (successes, failures) = store.decrypt_list_with_failures(&ciphers);
41    Ok(DecryptCipherListResult {
42        successes,
43        failures: failures.into_iter().cloned().collect(),
44    })
45}
46
47#[cfg_attr(feature = "wasm", wasm_bindgen)]
48impl CiphersClient {
49    /// Get all ciphers from state and decrypt them, returning both successes and failures.
50    /// This method will not fail when some ciphers fail to decrypt, allowing for graceful
51    /// handling of corrupted or problematic cipher data.
52    pub async fn list(&self) -> Result<DecryptCipherListResult, GetCipherError> {
53        let key_store = self.client.internal.get_key_store();
54        let repository = self.get_repository()?;
55
56        list_ciphers(key_store, repository.as_ref()).await
57    }
58
59    /// Get [Cipher] by ID from state and decrypt it to a [CipherView].
60    pub async fn get(&self, cipher_id: &str) -> Result<CipherView, GetCipherError> {
61        let key_store = self.client.internal.get_key_store();
62        let repository = self.get_repository()?;
63
64        get_cipher(key_store, repository.as_ref(), cipher_id).await
65    }
66}