bitwarden_vault/cipher/
card.rs

1use bitwarden_api_api::models::CipherCardModel;
2use bitwarden_core::key_management::{KeyIds, SymmetricKeyId};
3use bitwarden_crypto::{
4    CompositeEncryptable, CryptoError, Decryptable, EncString, KeyStoreContext,
5    PrimitiveEncryptable,
6};
7use serde::{Deserialize, Serialize};
8#[cfg(feature = "wasm")]
9use tsify::Tsify;
10
11use super::cipher::CipherKind;
12use crate::{Cipher, VaultParseError, cipher::cipher::CopyableCipherFields};
13
14#[derive(Serialize, Deserialize, Debug, Clone)]
15#[serde(rename_all = "camelCase", deny_unknown_fields)]
16#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
17#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
18pub struct Card {
19    pub cardholder_name: Option<EncString>,
20    pub exp_month: Option<EncString>,
21    pub exp_year: Option<EncString>,
22    pub code: Option<EncString>,
23    pub brand: Option<EncString>,
24    pub number: Option<EncString>,
25}
26
27#[allow(missing_docs)]
28#[derive(Serialize, Deserialize, Debug, Clone)]
29#[serde(rename_all = "camelCase", deny_unknown_fields)]
30#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
31#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
32pub struct CardView {
33    pub cardholder_name: Option<String>,
34    pub exp_month: Option<String>,
35    pub exp_year: Option<String>,
36    pub code: Option<String>,
37    pub brand: Option<String>,
38    pub number: Option<String>,
39}
40
41/// Minimal CardView only including the needed details for list views
42#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
43#[serde(rename_all = "camelCase", deny_unknown_fields)]
44#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
45#[cfg_attr(feature = "wasm", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
46pub struct CardListView {
47    /// The brand of the card, e.g. Visa, Mastercard, etc.
48    pub brand: Option<String>,
49}
50
51#[allow(missing_docs)]
52#[derive(Serialize, Deserialize)]
53pub enum CardBrand {
54    Visa,
55    Mastercard,
56    Amex,
57    Discover,
58    #[serde(rename = "Diners Club")]
59    DinersClub,
60    #[serde(rename = "JCB")]
61    Jcb,
62    Maestro,
63    UnionPay,
64    RuPay,
65    #[serde(untagged)]
66    Other,
67}
68
69impl CompositeEncryptable<KeyIds, SymmetricKeyId, Card> for CardView {
70    fn encrypt_composite(
71        &self,
72        ctx: &mut KeyStoreContext<KeyIds>,
73        key: SymmetricKeyId,
74    ) -> Result<Card, CryptoError> {
75        Ok(Card {
76            cardholder_name: self.cardholder_name.encrypt(ctx, key)?,
77            exp_month: self.exp_month.encrypt(ctx, key)?,
78            exp_year: self.exp_year.encrypt(ctx, key)?,
79            code: self.code.encrypt(ctx, key)?,
80            brand: self.brand.encrypt(ctx, key)?,
81            number: self.number.encrypt(ctx, key)?,
82        })
83    }
84}
85
86impl Decryptable<KeyIds, SymmetricKeyId, CardListView> for Card {
87    fn decrypt(
88        &self,
89        ctx: &mut KeyStoreContext<KeyIds>,
90        key: SymmetricKeyId,
91    ) -> Result<CardListView, CryptoError> {
92        Ok(CardListView {
93            brand: self.brand.decrypt(ctx, key).ok().flatten(),
94        })
95    }
96}
97
98impl Decryptable<KeyIds, SymmetricKeyId, CardView> for Card {
99    fn decrypt(
100        &self,
101        ctx: &mut KeyStoreContext<KeyIds>,
102        key: SymmetricKeyId,
103    ) -> Result<CardView, CryptoError> {
104        Ok(CardView {
105            cardholder_name: self.cardholder_name.decrypt(ctx, key).ok().flatten(),
106            exp_month: self.exp_month.decrypt(ctx, key).ok().flatten(),
107            exp_year: self.exp_year.decrypt(ctx, key).ok().flatten(),
108            code: self.code.decrypt(ctx, key).ok().flatten(),
109            brand: self.brand.decrypt(ctx, key).ok().flatten(),
110            number: self.number.decrypt(ctx, key).ok().flatten(),
111        })
112    }
113}
114
115impl TryFrom<CipherCardModel> for Card {
116    type Error = VaultParseError;
117
118    fn try_from(card: CipherCardModel) -> Result<Self, Self::Error> {
119        Ok(Self {
120            cardholder_name: EncString::try_from_optional(card.cardholder_name)?,
121            exp_month: EncString::try_from_optional(card.exp_month)?,
122            exp_year: EncString::try_from_optional(card.exp_year)?,
123            code: EncString::try_from_optional(card.code)?,
124            brand: EncString::try_from_optional(card.brand)?,
125            number: EncString::try_from_optional(card.number)?,
126        })
127    }
128}
129
130impl From<Card> for bitwarden_api_api::models::CipherCardModel {
131    fn from(card: Card) -> Self {
132        Self {
133            cardholder_name: card.cardholder_name.map(|n| n.to_string()),
134            brand: card.brand.map(|b| b.to_string()),
135            number: card.number.map(|n| n.to_string()),
136            exp_month: card.exp_month.map(|m| m.to_string()),
137            exp_year: card.exp_year.map(|y| y.to_string()),
138            code: card.code.map(|c| c.to_string()),
139        }
140    }
141}
142
143impl CipherKind for Card {
144    fn decrypt_subtitle(
145        &self,
146        ctx: &mut KeyStoreContext<KeyIds>,
147        key: SymmetricKeyId,
148    ) -> Result<String, CryptoError> {
149        let brand = self
150            .brand
151            .as_ref()
152            .map(|b| b.decrypt(ctx, key))
153            .transpose()?;
154        let number = self
155            .number
156            .as_ref()
157            .map(|n| n.decrypt(ctx, key))
158            .transpose()?;
159
160        Ok(build_subtitle_card(brand, number))
161    }
162
163    fn get_copyable_fields(&self, _: Option<&Cipher>) -> Vec<CopyableCipherFields> {
164        [
165            self.number
166                .as_ref()
167                .map(|_| CopyableCipherFields::CardNumber),
168            self.code
169                .as_ref()
170                .map(|_| CopyableCipherFields::CardSecurityCode),
171        ]
172        .into_iter()
173        .flatten()
174        .collect()
175    }
176}
177
178/// Builds the subtitle for a card cipher
179fn build_subtitle_card(brand: Option<String>, number: Option<String>) -> String {
180    // Attempt to pre-allocate the string with the expected max-size
181    let mut subtitle =
182        String::with_capacity(brand.as_ref().map(|b| b.len()).unwrap_or_default() + 8);
183
184    if let Some(brand) = brand {
185        subtitle.push_str(&brand);
186    }
187
188    if let Some(number) = number {
189        let number_chars: Vec<_> = number.chars().collect();
190        let number_len = number_chars.len();
191        if number_len > 4 {
192            if !subtitle.is_empty() {
193                subtitle.push_str(", ");
194            }
195
196            // On AMEX cards we show 5 digits instead of 4
197            let digit_count = match number_chars[0..2] {
198                ['3', '4'] | ['3', '7'] => 5,
199                _ => 4,
200            };
201
202            subtitle.push('*');
203            subtitle.extend(number_chars.iter().skip(number_len - digit_count));
204        }
205    }
206
207    subtitle
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn test_build_subtitle_card_visa() {
216        let brand = Some("Visa".to_owned());
217        let number = Some("4111111111111111".to_owned());
218
219        let subtitle = build_subtitle_card(brand, number);
220        assert_eq!(subtitle, "Visa, *1111");
221    }
222
223    #[test]
224    fn test_build_subtitle_card_mastercard() {
225        let brand = Some("Mastercard".to_owned());
226        let number = Some("5555555555554444".to_owned());
227
228        let subtitle = build_subtitle_card(brand, number);
229        assert_eq!(subtitle, "Mastercard, *4444");
230    }
231
232    #[test]
233    fn test_build_subtitle_card_amex() {
234        let brand = Some("Amex".to_owned());
235        let number = Some("378282246310005".to_owned());
236
237        let subtitle = build_subtitle_card(brand, number);
238        assert_eq!(subtitle, "Amex, *10005");
239    }
240
241    #[test]
242    fn test_build_subtitle_card_underflow() {
243        let brand = Some("Mastercard".to_owned());
244        let number = Some("4".to_owned());
245
246        let subtitle = build_subtitle_card(brand, number);
247        assert_eq!(subtitle, "Mastercard");
248    }
249
250    #[test]
251    fn test_build_subtitle_card_only_brand() {
252        let brand = Some("Mastercard".to_owned());
253        let number = None;
254
255        let subtitle = build_subtitle_card(brand, number);
256        assert_eq!(subtitle, "Mastercard");
257    }
258
259    #[test]
260    fn test_build_subtitle_card_only_card() {
261        let brand = None;
262        let number = Some("5555555555554444".to_owned());
263
264        let subtitle = build_subtitle_card(brand, number);
265        assert_eq!(subtitle, "*4444");
266    }
267    #[test]
268    fn test_get_copyable_fields_code() {
269        let card = Card {
270            cardholder_name: None,
271            exp_month: None,
272            exp_year: None,
273            code: Some("2.6TpmzzaQHgYr+mXjdGLQlg==|vT8VhfvMlWSCN9hxGYftZ5rjKRsZ9ofjdlUCx5Gubnk=|uoD3/GEQBWKKx2O+/YhZUCzVkfhm8rFK3sUEVV84mv8=".parse().unwrap()),
274            brand: None,
275            number: None,
276        };
277
278        let copyable_fields = card.get_copyable_fields(None);
279
280        assert_eq!(
281            copyable_fields,
282            vec![CopyableCipherFields::CardSecurityCode]
283        );
284    }
285
286    #[test]
287    fn test_build_subtitle_card_unicode() {
288        let brand = Some("Visa".to_owned());
289        let number = Some("•••• 3278".to_owned());
290
291        let subtitle = build_subtitle_card(brand, number);
292        assert_eq!(subtitle, "Visa, *3278");
293    }
294
295    #[test]
296    fn test_get_copyable_fields_number() {
297        let card = Card {
298            cardholder_name: None,
299            exp_month: None,
300            exp_year: None,
301            code: None,
302            brand: None,
303            number: Some("2.6TpmzzaQHgYr+mXjdGLQlg==|vT8VhfvMlWSCN9hxGYftZ5rjKRsZ9ofjdlUCx5Gubnk=|uoD3/GEQBWKKx2O+/YhZUCzVkfhm8rFK3sUEVV84mv8=".parse().unwrap()),
304        };
305
306        let copyable_fields = card.get_copyable_fields(None);
307
308        assert_eq!(copyable_fields, vec![CopyableCipherFields::CardNumber]);
309    }
310}