summaryrefslogtreecommitdiffstats
path: root/toolkit/components/passwordmgr/test/unit/test_module_LoginStore.js
blob: f7e764c78991229baca924dce5d26bcd9335cec0 (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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

/**
 * Tests the LoginStore object.
 */

"use strict";

// Globals

ChromeUtils.defineESModuleGetters(this, {
  LoginStore: "resource://gre/modules/LoginStore.sys.mjs",
});

const TEST_STORE_FILE_NAME = "test-logins.json";

const MAX_DATE_MS = 8640000000000000;

// Tests

/**
 * Saves login data to a file, then reloads it.
 */
add_task(async function test_save_reload() {
  let storeForSave = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);

  // The "load" method must be called before preparing the data to be saved.
  await storeForSave.load();

  let rawLoginData = {
    id: storeForSave.data.nextId++,
    hostname: "http://www.example.com",
    httpRealm: null,
    formSubmitURL: "http://www.example.com",
    usernameField: "field_" + String.fromCharCode(533, 537, 7570, 345),
    passwordField: "field_" + String.fromCharCode(421, 259, 349, 537),
    encryptedUsername: "(test)",
    encryptedPassword: "(test)",
    guid: "(test)",
    encType: Ci.nsILoginManagerCrypto.ENCTYPE_SDR,
    timeCreated: Date.now(),
    timeLastUsed: Date.now(),
    timePasswordChanged: Date.now(),
    timesUsed: 1,
  };
  storeForSave.data.logins.push(rawLoginData);

  await storeForSave._save();

  // Test the asynchronous initialization path.
  let storeForLoad = new LoginStore(storeForSave.path);
  await storeForLoad.load();

  Assert.equal(storeForLoad.data.logins.length, 1);
  Assert.deepEqual(storeForLoad.data.logins[0], rawLoginData);

  // Test the synchronous initialization path.
  storeForLoad = new LoginStore(storeForSave.path);
  storeForLoad.ensureDataReady();

  Assert.equal(storeForLoad.data.logins.length, 1);
  Assert.deepEqual(storeForLoad.data.logins[0], rawLoginData);
});

/**
 * Checks that loading from a missing file results in empty arrays.
 */
add_task(async function test_load_empty() {
  let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);

  Assert.equal(false, await IOUtils.exists(store.path));

  await store.load();

  Assert.equal(false, await IOUtils.exists(store.path));

  Assert.equal(store.data.logins.length, 0);
});

/**
 * Checks that saving empty data still overwrites any existing file.
 */
add_task(async function test_save_empty() {
  const store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);

  await store.load();
  await IOUtils.writeUTF8(store.path, "", { writeMode: "create" });
  await store._save();

  Assert.ok(await IOUtils.exists(store.path));
});

/**
 * Loads data from a string in a predefined format.  The purpose of this test is
 * to verify that the JSON format used in previous versions can be loaded.
 */
add_task(async function test_load_string_predefined() {
  let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);

  let string =
    '{"logins":[{' +
    '"id":1,' +
    '"hostname":"http://www.example.com",' +
    '"httpRealm":null,' +
    '"formSubmitURL":"http://www.example.com",' +
    '"usernameField":"usernameField",' +
    '"passwordField":"passwordField",' +
    '"encryptedUsername":"(test)",' +
    '"encryptedPassword":"(test)",' +
    '"guid":"(test)",' +
    '"encType":1,' +
    '"timeCreated":1262304000000,' +
    '"timeLastUsed":1262390400000,' +
    '"timePasswordChanged":1262476800000,' +
    '"timesUsed":1}],"disabledHosts":[' +
    '"http://www.example.org"]}';

  await IOUtils.writeUTF8(store.path, string, {
    tmpPath: store.path + ".tmp",
  });

  await store.load();

  Assert.equal(store.data.logins.length, 1);
  Assert.deepEqual(store.data.logins[0], {
    id: 1,
    hostname: "http://www.example.com",
    httpRealm: null,
    formSubmitURL: "http://www.example.com",
    usernameField: "usernameField",
    passwordField: "passwordField",
    encryptedUsername: "(test)",
    encryptedPassword: "(test)",
    guid: "(test)",
    encType: Ci.nsILoginManagerCrypto.ENCTYPE_SDR,
    timeCreated: 1262304000000,
    timeLastUsed: 1262390400000,
    timePasswordChanged: 1262476800000,
    timesUsed: 1,
  });
});

/**
 * Loads login data from a malformed JSON string.
 */
add_task(async function test_load_string_malformed() {
  let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);

  let string = '{"logins":[{"hostname":"http://www.example.com","id":1,';

  await IOUtils.writeUTF8(store.path, string, {
    tmpPath: store.path + ".tmp",
  });

  await store.load();

  // A backup file should have been created.
  Assert.ok(await IOUtils.exists(store.path + ".corrupt"));
  await IOUtils.remove(store.path + ".corrupt");

  // The store should be ready to accept new data.
  Assert.equal(store.data.logins.length, 0);
});

/**
 * Loads login data from a malformed JSON string, using the synchronous
 * initialization path.
 */
add_task(async function test_load_string_malformed_sync() {
  let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);

  let string = '{"logins":[{"hostname":"http://www.example.com","id":1,';

  await IOUtils.writeUTF8(store.path, string, {
    tmpPath: store.path + ".tmp",
  });

  store.ensureDataReady();

  // A backup file should have been created.
  Assert.ok(await IOUtils.exists(store.path + ".corrupt"));
  await IOUtils.remove(store.path + ".corrupt");

  // The store should be ready to accept new data.
  Assert.equal(store.data.logins.length, 0);
});

/**
 * Fix bad dates when loading login data
 */
add_task(async function test_load_bad_dates() {
  let rawLoginData = {
    encType: 1,
    encryptedPassword: "(test)",
    encryptedUsername: "(test)",
    formSubmitURL: "https://www.example.com",
    guid: "{2a97313f-873b-4048-9a3d-4f442b46c1e5}",
    hostname: "https://www.example.com",
    httpRealm: null,
    id: 1,
    passwordField: "pass",
    timesUsed: 1,
    usernameField: "email",
  };
  let rawStoreData = {
    dismissedBreachAlertsByLoginGUID: {},
    logins: [],
    nextId: 2,
    potentiallyVulnerablePasswords: [],
    version: 2,
  };

  /**
   * test that:
   * - bogus (0 or out-of-range) date values in any of the date fields are replaced with the
   *   earliest time marked by the other date fields
   * - bogus bogus (0 or out-of-range) date values in all date fields are replaced with the time of import
   */
  let tests = [
    {
      name: "Out-of-range time values",
      savedProps: {
        timePasswordChanged: MAX_DATE_MS + 1,
        timeLastUsed: MAX_DATE_MS + 1,
        timeCreated: MAX_DATE_MS + 1,
      },
      expectedProps: {
        timePasswordChanged: "now",
        timeLastUsed: "now",
        timeCreated: "now",
      },
    },
    {
      name: "All zero time values",
      savedProps: {
        timePasswordChanged: 0,
        timeLastUsed: 0,
        timeCreated: 0,
      },
      expectedProps: {
        timePasswordChanged: "now",
        timeLastUsed: "now",
        timeCreated: "now",
      },
    },
    {
      name: "Only timeCreated has value",
      savedProps: {
        timePasswordChanged: 0,
        timeLastUsed: 0,
        timeCreated: 946713600000,
      },
      expectedProps: {
        timePasswordChanged: 946713600000,
        timeLastUsed: 946713600000,
        timeCreated: 946713600000,
      },
    },
    {
      name: "timeCreated has 0 value",
      savedProps: {
        timePasswordChanged: 946713600000,
        timeLastUsed: 946713600000,
        timeCreated: 0,
      },
      expectedProps: {
        timePasswordChanged: 946713600000,
        timeLastUsed: 946713600000,
        timeCreated: 946713600000,
      },
    },
    {
      name: "timeCreated has out-of-range value",
      savedProps: {
        timePasswordChanged: 946713600000,
        timeLastUsed: 946713600000,
        timeCreated: MAX_DATE_MS + 1,
      },
      expectedProps: {
        timePasswordChanged: 946713600000,
        timeLastUsed: 946713600000,
        timeCreated: 946713600000,
      },
    },
    {
      name: "Use earliest time for missing value",
      savedProps: {
        timePasswordChanged: 0,
        timeLastUsed: 946713600000,
        timeCreated: 946540800000,
      },
      expectedProps: {
        timePasswordChanged: 946540800000,
        timeLastUsed: 946713600000,
        timeCreated: 946540800000,
      },
    },
  ];

  for (let testData of tests) {
    let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);
    let string = JSON.stringify(
      Object.assign({}, rawStoreData, {
        logins: [Object.assign({}, rawLoginData, testData.savedProps)],
      })
    );
    await IOUtils.writeUTF8(store.path, string, {
      tmpPath: store.path + ".tmp",
    });
    let now = Date.now();
    await store.load();

    Assert.equal(
      store.data.logins.length,
      1,
      `${testData.name}: Expected a single login`
    );

    let login = store.data.logins[0];
    for (let pname of ["timeCreated", "timeLastUsed", "timePasswordChanged"]) {
      if (testData.expectedProps[pname] === "now") {
        Assert.ok(
          login[pname] >= now,
          `${testData.name}: Check ${pname} is at/near now`
        );
      } else {
        Assert.equal(
          login[pname],
          testData.expectedProps[pname],
          `${testData.name}: Check expected ${pname}`
        );
      }
    }
    Assert.equal(store.data.version, 3, "Check version was bumped");
  }
});