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::cipher::CopyableCipherFields, Cipher, VaultParseError};
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#[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 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 CipherKind for Card {
131 fn decrypt_subtitle(
132 &self,
133 ctx: &mut KeyStoreContext<KeyIds>,
134 key: SymmetricKeyId,
135 ) -> Result<String, CryptoError> {
136 let brand = self
137 .brand
138 .as_ref()
139 .map(|b| b.decrypt(ctx, key))
140 .transpose()?;
141 let number = self
142 .number
143 .as_ref()
144 .map(|n| n.decrypt(ctx, key))
145 .transpose()?;
146
147 Ok(build_subtitle_card(brand, number))
148 }
149
150 fn get_copyable_fields(&self, _: Option<&Cipher>) -> Vec<CopyableCipherFields> {
151 [
152 self.number
153 .as_ref()
154 .map(|_| CopyableCipherFields::CardNumber),
155 self.code
156 .as_ref()
157 .map(|_| CopyableCipherFields::CardSecurityCode),
158 ]
159 .into_iter()
160 .flatten()
161 .collect()
162 }
163}
164
165fn build_subtitle_card(brand: Option<String>, number: Option<String>) -> String {
167 let mut subtitle =
169 String::with_capacity(brand.as_ref().map(|b| b.len()).unwrap_or_default() + 8);
170
171 if let Some(brand) = brand {
172 subtitle.push_str(&brand);
173 }
174
175 if let Some(number) = number {
176 let number_chars: Vec<_> = number.chars().collect();
177 let number_len = number_chars.len();
178 if number_len > 4 {
179 if !subtitle.is_empty() {
180 subtitle.push_str(", ");
181 }
182
183 let digit_count = match number_chars[0..2] {
185 ['3', '4'] | ['3', '7'] => 5,
186 _ => 4,
187 };
188
189 subtitle.push('*');
190 subtitle.extend(number_chars.iter().skip(number_len - digit_count));
191 }
192 }
193
194 subtitle
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn test_build_subtitle_card_visa() {
203 let brand = Some("Visa".to_owned());
204 let number = Some("4111111111111111".to_owned());
205
206 let subtitle = build_subtitle_card(brand, number);
207 assert_eq!(subtitle, "Visa, *1111");
208 }
209
210 #[test]
211 fn test_build_subtitle_card_mastercard() {
212 let brand = Some("Mastercard".to_owned());
213 let number = Some("5555555555554444".to_owned());
214
215 let subtitle = build_subtitle_card(brand, number);
216 assert_eq!(subtitle, "Mastercard, *4444");
217 }
218
219 #[test]
220 fn test_build_subtitle_card_amex() {
221 let brand = Some("Amex".to_owned());
222 let number = Some("378282246310005".to_owned());
223
224 let subtitle = build_subtitle_card(brand, number);
225 assert_eq!(subtitle, "Amex, *10005");
226 }
227
228 #[test]
229 fn test_build_subtitle_card_underflow() {
230 let brand = Some("Mastercard".to_owned());
231 let number = Some("4".to_owned());
232
233 let subtitle = build_subtitle_card(brand, number);
234 assert_eq!(subtitle, "Mastercard");
235 }
236
237 #[test]
238 fn test_build_subtitle_card_only_brand() {
239 let brand = Some("Mastercard".to_owned());
240 let number = None;
241
242 let subtitle = build_subtitle_card(brand, number);
243 assert_eq!(subtitle, "Mastercard");
244 }
245
246 #[test]
247 fn test_build_subtitle_card_only_card() {
248 let brand = None;
249 let number = Some("5555555555554444".to_owned());
250
251 let subtitle = build_subtitle_card(brand, number);
252 assert_eq!(subtitle, "*4444");
253 }
254 #[test]
255 fn test_get_copyable_fields_code() {
256 let card = Card {
257 cardholder_name: None,
258 exp_month: None,
259 exp_year: None,
260 code: Some("2.6TpmzzaQHgYr+mXjdGLQlg==|vT8VhfvMlWSCN9hxGYftZ5rjKRsZ9ofjdlUCx5Gubnk=|uoD3/GEQBWKKx2O+/YhZUCzVkfhm8rFK3sUEVV84mv8=".parse().unwrap()),
261 brand: None,
262 number: None,
263 };
264
265 let copyable_fields = card.get_copyable_fields(None);
266
267 assert_eq!(
268 copyable_fields,
269 vec![CopyableCipherFields::CardSecurityCode]
270 );
271 }
272
273 #[test]
274 fn test_build_subtitle_card_unicode() {
275 let brand = Some("Visa".to_owned());
276 let number = Some("•••• 3278".to_owned());
277
278 let subtitle = build_subtitle_card(brand, number);
279 assert_eq!(subtitle, "Visa, *3278");
280 }
281
282 #[test]
283 fn test_get_copyable_fields_number() {
284 let card = Card {
285 cardholder_name: None,
286 exp_month: None,
287 exp_year: None,
288 code: None,
289 brand: None,
290 number: Some("2.6TpmzzaQHgYr+mXjdGLQlg==|vT8VhfvMlWSCN9hxGYftZ5rjKRsZ9ofjdlUCx5Gubnk=|uoD3/GEQBWKKx2O+/YhZUCzVkfhm8rFK3sUEVV84mv8=".parse().unwrap()),
291 };
292
293 let copyable_fields = card.get_copyable_fields(None);
294
295 assert_eq!(copyable_fields, vec![CopyableCipherFields::CardNumber]);
296 }
297}