summaryrefslogtreecommitdiffstats
path: root/browser/components/migration/tests/unit/test_Chrome_credit_cards.js
blob: 5c4d3517d2fe112b9b577ee64a1f1c2b5df2bd8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

/* global structuredClone */

const PROFILE = {
  id: "Default",
  name: "Default",
};

const PAYMENT_METHODS = [
  {
    name_on_card: "Name Name",
    card_number: "4532962432748929", // Visa
    expiration_month: 3,
    expiration_year: 2027,
  },
  {
    name_on_card: "Name Name Name",
    card_number: "5359908373796416", // Mastercard
    expiration_month: 5,
    expiration_year: 2028,
  },
  {
    name_on_card: "Name",
    card_number: "346624461807588", // AMEX
    expiration_month: 4,
    expiration_year: 2026,
  },
];

let OSKeyStoreTestUtils;
add_setup(async function os_key_store_setup() {
  ({ OSKeyStoreTestUtils } = ChromeUtils.importESModule(
    "resource://testing-common/OSKeyStoreTestUtils.sys.mjs"
  ));
  OSKeyStoreTestUtils.setup();
  registerCleanupFunction(async function cleanup() {
    await OSKeyStoreTestUtils.cleanup();
  });
});

let rootDir = do_get_file("chromefiles/", true);

function checkCardsAreEqual(importedCard, testCard, id) {
  const CC_NUMBER_RE = /^(\*+)(.{4})$/;

  Assert.equal(
    importedCard["cc-name"],
    testCard.name_on_card,
    "The two logins ID " + id + " have the same name on card"
  );

  let matches = CC_NUMBER_RE.exec(importedCard["cc-number"]);
  Assert.notEqual(matches, null);
  Assert.equal(importedCard["cc-number"].length, testCard.card_number.length);
  Assert.equal(testCard.card_number.endsWith(matches[2]), true);
  Assert.notEqual(importedCard["cc-number-encrypted"], "");

  Assert.equal(
    importedCard["cc-exp-month"],
    testCard.expiration_month,
    "The two logins ID " + id + " have the same expiration month"
  );
  Assert.equal(
    importedCard["cc-exp-year"],
    testCard.expiration_year,
    "The two logins ID " + id + " have the same expiration year"
  );
}

add_task(async function setup_fakePaths() {
  let pathId;
  if (AppConstants.platform == "macosx") {
    pathId = "ULibDir";
  } else if (AppConstants.platform == "win") {
    pathId = "LocalAppData";
  } else {
    pathId = "Home";
  }
  registerFakePath(pathId, rootDir);
});

add_task(async function test_credit_cards() {
  if (!OSKeyStoreTestUtils.canTestOSKeyStoreLogin()) {
    todo_check_true(
      OSKeyStoreTestUtils.canTestOSKeyStoreLogin(),
      "Cannot test OS key store login on official builds."
    );
    return;
  }

  let loginCrypto;
  let profilePathSegments;

  let mockMacOSKeychain = {
    passphrase: "bW96aWxsYWZpcmVmb3g=",
    serviceName: "TESTING Chrome Safe Storage",
    accountName: "TESTING Chrome",
  };
  if (AppConstants.platform == "macosx") {
    let { ChromeMacOSLoginCrypto } = ChromeUtils.importESModule(
      "resource:///modules/ChromeMacOSLoginCrypto.sys.mjs"
    );
    loginCrypto = new ChromeMacOSLoginCrypto(
      mockMacOSKeychain.serviceName,
      mockMacOSKeychain.accountName,
      mockMacOSKeychain.passphrase
    );
    profilePathSegments = [
      "Application Support",
      "Google",
      "Chrome",
      "Default",
    ];
  } else if (AppConstants.platform == "win") {
    let { ChromeWindowsLoginCrypto } = ChromeUtils.importESModule(
      "resource:///modules/ChromeWindowsLoginCrypto.sys.mjs"
    );
    loginCrypto = new ChromeWindowsLoginCrypto("Chrome");
    profilePathSegments = ["Google", "Chrome", "User Data", "Default"];
  } else {
    throw new Error("Not implemented");
  }

  let target = rootDir.clone();
  let defaultFolderPath = PathUtils.join(target.path, ...profilePathSegments);
  let webDataPath = PathUtils.join(defaultFolderPath, "Web Data");
  let localStatePath = defaultFolderPath.replace("Default", "");

  await IOUtils.makeDirectory(defaultFolderPath, {
    createAncestor: true,
    ignoreExisting: true,
  });

  // Copy Web Data database into Default profile
  const sourcePathWebData = do_get_file(
    "AppData/Local/Google/Chrome/User Data/Default/Web Data"
  ).path;
  await IOUtils.copy(sourcePathWebData, webDataPath);

  const sourcePathLocalState = do_get_file(
    "AppData/Local/Google/Chrome/User Data/Local State"
  ).path;
  await IOUtils.copy(sourcePathLocalState, localStatePath);

  let dbConn = await Sqlite.openConnection({ path: webDataPath });

  for (let card of PAYMENT_METHODS) {
    let encryptedCardNumber = await loginCrypto.encryptData(card.card_number);
    let cardNumberEncryptedValue = new Uint8Array(
      loginCrypto.stringToArray(encryptedCardNumber)
    );

    let cardCopy = structuredClone(card);

    cardCopy.card_number_encrypted = cardNumberEncryptedValue;
    delete cardCopy.card_number;

    await dbConn.execute(
      `INSERT INTO credit_cards
                           (name_on_card, card_number_encrypted, expiration_month, expiration_year)
                           VALUES (:name_on_card, :card_number_encrypted, :expiration_month, :expiration_year)
                          `,
      cardCopy
    );
  }

  await dbConn.close();

  let migrator = await MigrationUtils.getMigrator("chrome");
  if (AppConstants.platform == "macosx") {
    Object.assign(migrator, {
      _keychainServiceName: mockMacOSKeychain.serviceName,
      _keychainAccountName: mockMacOSKeychain.accountName,
      _keychainMockPassphrase: mockMacOSKeychain.passphrase,
    });
  }
  Assert.ok(
    await migrator.isSourceAvailable(),
    "Sanity check the source exists"
  );

  Services.prefs.setBoolPref(
    "browser.migrate.chrome.payment_methods.enabled",
    false
  );
  Assert.ok(
    !(
      (await migrator.getMigrateData(PROFILE)) &
      MigrationUtils.resourceTypes.PAYMENT_METHODS
    ),
    "Should be able to disable migrating payment methods"
  );
  // Clear the cached resources now so that a re-check for payment methods
  // will look again.
  delete migrator._resourcesByProfile[PROFILE.id];

  Services.prefs.setBoolPref(
    "browser.migrate.chrome.payment_methods.enabled",
    true
  );

  Assert.ok(
    (await migrator.getMigrateData(PROFILE)) &
      MigrationUtils.resourceTypes.PAYMENT_METHODS,
    "Should be able to enable migrating payment methods"
  );

  let { formAutofillStorage } = ChromeUtils.importESModule(
    "resource://autofill/FormAutofillStorage.sys.mjs"
  );
  await formAutofillStorage.initialize();

  await promiseMigration(
    migrator,
    MigrationUtils.resourceTypes.PAYMENT_METHODS,
    PROFILE
  );

  let cards = await formAutofillStorage.creditCards.getAll();

  Assert.equal(
    cards.length,
    PAYMENT_METHODS.length,
    "Check there are still the same number of credit cards after re-importing the data"
  );
  Assert.equal(
    cards.length,
    MigrationUtils._importQuantities.cards,
    "Check telemetry matches the actual import."
  );

  for (let i = 0; i < PAYMENT_METHODS.length; i++) {
    checkCardsAreEqual(cards[i], PAYMENT_METHODS[i], i + 1);
  }
});