bitwarden_vault/cipher/
field.rs

1use std::collections::HashMap;
2
3use bitwarden_api_api::models::CipherFieldModel;
4use bitwarden_core::{
5    MissingFieldError,
6    key_management::{KeyIds, SymmetricKeyId},
7    require,
8};
9use bitwarden_crypto::{
10    CompositeEncryptable, CryptoError, Decryptable, EncString, KeyStoreContext,
11    PrimitiveEncryptable,
12};
13use serde::{Deserialize, Serialize};
14use serde_repr::{Deserialize_repr, Serialize_repr};
15#[cfg(feature = "wasm")]
16use tsify::Tsify;
17#[cfg(feature = "wasm")]
18use wasm_bindgen::prelude::wasm_bindgen;
19
20use super::linked_id::LinkedIdType;
21use crate::{PasswordHistoryView, VaultParseError};
22
23/// Represents the type of a [FieldView].
24#[derive(Clone, Copy, Serialize_repr, Deserialize_repr, Debug, PartialEq, Eq)]
25#[repr(u8)]
26#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
27#[cfg_attr(feature = "wasm", wasm_bindgen)]
28pub enum FieldType {
29    /// Text field
30    Text = 0,
31    /// Hidden text field
32    Hidden = 1,
33    /// Boolean field
34    Boolean = 2,
35    /// Linked field
36    Linked = 3,
37}
38
39impl TryFrom<u8> for FieldType {
40    type Error = MissingFieldError;
41
42    fn try_from(value: u8) -> Result<Self, Self::Error> {
43        match value {
44            0 => Ok(FieldType::Text),
45            1 => Ok(FieldType::Hidden),
46            2 => Ok(FieldType::Boolean),
47            3 => Ok(FieldType::Linked),
48            _ => Err(MissingFieldError("FieldType")),
49        }
50    }
51}
52
53#[derive(Serialize, Deserialize, Debug, Clone)]
54#[serde(rename_all = "camelCase", deny_unknown_fields)]
55#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
56#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
57pub struct Field {
58    name: Option<EncString>,
59    value: Option<EncString>,
60    r#type: FieldType,
61
62    linked_id: Option<LinkedIdType>,
63}
64
65#[allow(missing_docs)]
66#[derive(Serialize, Deserialize, Debug, Clone)]
67#[serde(rename_all = "camelCase", deny_unknown_fields)]
68#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
69#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
70pub struct FieldView {
71    pub name: Option<String>,
72    pub value: Option<String>,
73    pub r#type: FieldType,
74
75    pub linked_id: Option<LinkedIdType>,
76}
77
78/// Minimal field view for list/search operations.
79/// Contains only the fields needed for search indexing.
80#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
81#[serde(rename_all = "camelCase", deny_unknown_fields)]
82#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
83#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
84pub struct FieldListView {
85    /// Only populated if the field has a name.
86    pub name: Option<String>,
87    /// Only populated for [FieldType::Text] fields.
88    pub value: Option<String>,
89    /// The field type.
90    pub r#type: FieldType,
91}
92
93#[cfg(feature = "wasm")]
94impl From<FieldView> for FieldListView {
95    fn from(field: FieldView) -> Self {
96        Self {
97            name: field.name,
98            value: if field.r#type == FieldType::Text {
99                field.value
100            } else {
101                None
102            },
103            r#type: field.r#type,
104        }
105    }
106}
107
108impl CompositeEncryptable<KeyIds, SymmetricKeyId, Field> for FieldView {
109    fn encrypt_composite(
110        &self,
111        ctx: &mut KeyStoreContext<KeyIds>,
112        key: SymmetricKeyId,
113    ) -> Result<Field, CryptoError> {
114        Ok(Field {
115            name: self.name.encrypt(ctx, key)?,
116            value: self.value.encrypt(ctx, key)?,
117            r#type: self.r#type,
118            linked_id: self.linked_id,
119        })
120    }
121}
122
123impl FieldView {
124    /// Compares two sets of FieldView and detects changes in hidden fields, for building password
125    /// history.
126    pub(crate) fn detect_hidden_field_changes(
127        fields: &[FieldView],
128        original: &[FieldView],
129    ) -> Vec<PasswordHistoryView> {
130        let current_fields = Self::extract_hidden_fields(fields);
131        let original_fields = Self::extract_hidden_fields(original);
132
133        original_fields
134            .into_iter()
135            .filter_map(|(field_name, original_value)| {
136                let current_value = current_fields.get(&field_name);
137                if current_value != Some(&original_value) {
138                    Some(PasswordHistoryView::new_field(&field_name, &original_value))
139                } else {
140                    None
141                }
142            })
143            .collect()
144    }
145
146    fn extract_hidden_fields(fields: &[FieldView]) -> HashMap<String, String> {
147        fields
148            .iter()
149            .filter_map(|f| match (&f.r#type, &f.name, &f.value) {
150                (FieldType::Hidden, Some(name), Some(value))
151                    if !name.is_empty() && !value.is_empty() =>
152                {
153                    Some((name.clone(), value.clone()))
154                }
155                _ => None,
156            })
157            .collect()
158    }
159}
160
161impl Decryptable<KeyIds, SymmetricKeyId, FieldView> for Field {
162    fn decrypt(
163        &self,
164        ctx: &mut KeyStoreContext<KeyIds>,
165        key: SymmetricKeyId,
166    ) -> Result<FieldView, CryptoError> {
167        Ok(FieldView {
168            name: self.name.decrypt(ctx, key).ok().flatten(),
169            value: self.value.decrypt(ctx, key).ok().flatten(),
170            r#type: self.r#type,
171            linked_id: self.linked_id,
172        })
173    }
174}
175
176impl TryFrom<CipherFieldModel> for Field {
177    type Error = VaultParseError;
178
179    fn try_from(model: CipherFieldModel) -> Result<Self, Self::Error> {
180        Ok(Self {
181            name: EncString::try_from_optional(model.name)?,
182            value: EncString::try_from_optional(model.value)?,
183            r#type: require!(model.r#type).try_into()?,
184            linked_id: model
185                .linked_id
186                .map(|id| (id as u32).try_into())
187                .transpose()?,
188        })
189    }
190}
191
192impl TryFrom<bitwarden_api_api::models::FieldType> for FieldType {
193    type Error = MissingFieldError;
194
195    fn try_from(model: bitwarden_api_api::models::FieldType) -> Result<Self, Self::Error> {
196        Ok(match model {
197            bitwarden_api_api::models::FieldType::Text => FieldType::Text,
198            bitwarden_api_api::models::FieldType::Hidden => FieldType::Hidden,
199            bitwarden_api_api::models::FieldType::Boolean => FieldType::Boolean,
200            bitwarden_api_api::models::FieldType::Linked => FieldType::Linked,
201            bitwarden_api_api::models::FieldType::__Unknown(_) => {
202                return Err(MissingFieldError("type"));
203            }
204        })
205    }
206}
207
208impl From<Field> for bitwarden_api_api::models::CipherFieldModel {
209    fn from(field: Field) -> Self {
210        Self {
211            name: field.name.map(|n| n.to_string()),
212            value: field.value.map(|v| v.to_string()),
213            r#type: Some(field.r#type.into()),
214            linked_id: field.linked_id.map(|id| u32::from(id) as i32),
215        }
216    }
217}
218
219impl From<FieldType> for bitwarden_api_api::models::FieldType {
220    fn from(field_type: FieldType) -> Self {
221        match field_type {
222            FieldType::Text => bitwarden_api_api::models::FieldType::Text,
223            FieldType::Hidden => bitwarden_api_api::models::FieldType::Hidden,
224            FieldType::Boolean => bitwarden_api_api::models::FieldType::Boolean,
225            FieldType::Linked => bitwarden_api_api::models::FieldType::Linked,
226        }
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn test_field_type_try_from_u8_valid() {
236        assert_eq!(FieldType::try_from(0).unwrap(), FieldType::Text);
237        assert_eq!(FieldType::try_from(1).unwrap(), FieldType::Hidden);
238        assert_eq!(FieldType::try_from(2).unwrap(), FieldType::Boolean);
239        assert_eq!(FieldType::try_from(3).unwrap(), FieldType::Linked);
240    }
241
242    #[test]
243    fn test_field_type_try_from_u8_invalid() {
244        assert!(FieldType::try_from(4).is_err());
245        assert!(FieldType::try_from(255).is_err());
246    }
247}