summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_password_engine.js
blob: 6fcf3e541cdeac1d4d8c150db87528d1ca5c3317 (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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
const { FXA_PWDMGR_HOST, FXA_PWDMGR_REALM } = ChromeUtils.import(
  "resource://gre/modules/FxAccountsCommon.js"
);
const { LoginRec } = ChromeUtils.import(
  "resource://services-sync/engines/passwords.js"
);
const { Service } = ChromeUtils.import("resource://services-sync/service.js");

const LoginInfo = Components.Constructor(
  "@mozilla.org/login-manager/loginInfo;1",
  Ci.nsILoginInfo,
  "init"
);

const PropertyBag = Components.Constructor(
  "@mozilla.org/hash-property-bag;1",
  Ci.nsIWritablePropertyBag
);

async function cleanup(engine, server) {
  await engine._tracker.stop();
  await engine.wipeClient();
  Svc.Prefs.resetBranch("");
  Service.recordManager.clearCache();
  if (server) {
    await promiseStopServer(server);
  }
}

add_task(async function setup() {
  // Disable addon sync because AddonManager won't be initialized here.
  await Service.engineManager.unregister("addons");
  await Service.engineManager.unregister("extension-storage");
});

add_task(async function test_ignored_fields() {
  _("Only changes to syncable fields should be tracked");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  enableValidationPrefs();

  let login = Services.logins.addLogin(
    new LoginInfo(
      "https://example.com",
      "",
      null,
      "username",
      "password",
      "",
      ""
    )
  );
  login.QueryInterface(Ci.nsILoginMetaInfo); // For `guid`.

  engine._tracker.start();

  try {
    let nonSyncableProps = new PropertyBag();
    nonSyncableProps.setProperty("timeLastUsed", Date.now());
    nonSyncableProps.setProperty("timesUsed", 3);
    Services.logins.modifyLogin(login, nonSyncableProps);

    let noChanges = await engine.pullNewChanges();
    deepEqual(noChanges, {}, "Should not track non-syncable fields");

    let syncableProps = new PropertyBag();
    syncableProps.setProperty("username", "newuser");
    Services.logins.modifyLogin(login, syncableProps);

    let changes = await engine.pullNewChanges();
    deepEqual(
      Object.keys(changes),
      [login.guid],
      "Should track syncable fields"
    );
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_ignored_sync_credentials() {
  _("Sync credentials in login manager should be ignored");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  enableValidationPrefs();

  engine._tracker.start();

  try {
    let login = Services.logins.addLogin(
      new LoginInfo(
        FXA_PWDMGR_HOST,
        null,
        FXA_PWDMGR_REALM,
        "fxa-uid",
        "creds",
        "",
        ""
      )
    );

    let noChanges = await engine.pullNewChanges();
    deepEqual(noChanges, {}, "Should not track new FxA credentials");

    let props = new PropertyBag();
    props.setProperty("password", "newcreds");
    Services.logins.modifyLogin(login, props);

    noChanges = await engine.pullNewChanges();
    deepEqual(noChanges, {}, "Should not track changes to FxA credentials");
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_password_engine() {
  _("Basic password sync test");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);
  let collection = server.user("foo").collection("passwords");

  enableValidationPrefs();

  _("Add new login to upload during first sync");
  let newLogin;
  {
    let login = new LoginInfo(
      "https://example.com",
      "",
      null,
      "username",
      "password",
      "",
      ""
    );
    Services.logins.addLogin(login);

    let logins = Services.logins.findLogins("https://example.com", "", "");
    equal(logins.length, 1, "Should find new login in login manager");
    newLogin = logins[0].QueryInterface(Ci.nsILoginMetaInfo);

    // Insert a server record that's older, so that we prefer the local one.
    let rec = new LoginRec("passwords", newLogin.guid);
    rec.formSubmitURL = newLogin.formActionOrigin;
    rec.httpRealm = newLogin.httpRealm;
    rec.hostname = newLogin.origin;
    rec.username = newLogin.username;
    rec.password = "sekrit";
    let remotePasswordChangeTime = Date.now() - 1 * 60 * 60 * 24 * 1000;
    rec.timeCreated = remotePasswordChangeTime;
    rec.timePasswordChanged = remotePasswordChangeTime;
    collection.insert(
      newLogin.guid,
      encryptPayload(rec.cleartext),
      remotePasswordChangeTime / 1000
    );
  }

  _("Add login with older password change time to replace during first sync");
  let oldLogin;
  {
    let login = new LoginInfo(
      "https://mozilla.com",
      "",
      null,
      "us3r",
      "0ldpa55",
      "",
      ""
    );
    Services.logins.addLogin(login);

    let props = new PropertyBag();
    let localPasswordChangeTime = Date.now() - 1 * 60 * 60 * 24 * 1000;
    props.setProperty("timePasswordChanged", localPasswordChangeTime);
    Services.logins.modifyLogin(login, props);

    let logins = Services.logins.findLogins("https://mozilla.com", "", "");
    equal(logins.length, 1, "Should find old login in login manager");
    oldLogin = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
    equal(oldLogin.timePasswordChanged, localPasswordChangeTime);

    let rec = new LoginRec("passwords", oldLogin.guid);
    rec.hostname = oldLogin.origin;
    rec.formSubmitURL = oldLogin.formActionOrigin;
    rec.httpRealm = oldLogin.httpRealm;
    rec.username = oldLogin.username;
    // Change the password and bump the password change time to ensure we prefer
    // the remote one during reconciliation.
    rec.password = "n3wpa55";
    rec.usernameField = oldLogin.usernameField;
    rec.passwordField = oldLogin.usernameField;
    rec.timeCreated = oldLogin.timeCreated;
    rec.timePasswordChanged = Date.now();
    collection.insert(oldLogin.guid, encryptPayload(rec.cleartext));
  }

  await engine._tracker.stop();

  try {
    await sync_engine_and_validate_telem(engine, false);

    let newRec = collection.cleartext(newLogin.guid);
    equal(
      newRec.password,
      "password",
      "Should update remote password for newer login"
    );

    let logins = Services.logins.findLogins("https://mozilla.com", "", "");
    equal(
      logins[0].password,
      "n3wpa55",
      "Should update local password for older login"
    );
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_password_dupe() {
  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);
  let collection = server.user("foo").collection("passwords");

  let guid1 = Utils.makeGUID();
  let guid2 = Utils.makeGUID();
  let details = {
    formSubmitURL: "https://www.example.com",
    hostname: "https://www.example.com",
    httpRealm: null,
    username: "foo",
    password: "bar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
  };

  _("Create remote record with same details and guid1");
  collection.insertRecord(Object.assign({}, details, { id: guid1 }));

  _("Create remote record with guid2");
  collection.insertRecord(Object.assign({}, details, { id: guid2 }));

  _("Create local record with same details and guid1");
  await engine._store.create(Object.assign({}, details, { id: guid1 }));

  try {
    _("Perform sync");
    await sync_engine_and_validate_telem(engine, false);

    let logins = Services.logins.findLogins("https://www.example.com", "", "");

    equal(logins.length, 1);
    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid2);
    equal(null, collection.payload(guid1));
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_updated_null_password_sync() {
  _("Ensure updated null login username is converted to a string");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);
  let collection = server.user("foo").collection("passwords");

  let guid1 = Utils.makeGUID();
  let guid2 = Utils.makeGUID();
  let remoteDetails = {
    formSubmitURL: "https://www.nullupdateexample.com",
    hostname: "https://www.nullupdateexample.com",
    httpRealm: null,
    username: null,
    password: "bar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
  };
  let localDetails = {
    formSubmitURL: "https://www.nullupdateexample.com",
    hostname: "https://www.nullupdateexample.com",
    httpRealm: null,
    username: "foo",
    password: "foobar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
  };

  _("Create remote record with same details and guid1");
  collection.insertRecord(Object.assign({}, remoteDetails, { id: guid1 }));

  try {
    _("Create local updated login with null password");
    await engine._store.update(Object.assign({}, localDetails, { id: guid2 }));

    _("Perform sync");
    await sync_engine_and_validate_telem(engine, false);

    let logins = Services.logins.findLogins(
      "https://www.nullupdateexample.com",
      "",
      ""
    );

    equal(logins.length, 1);
    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid1);
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_updated_undefined_password_sync() {
  _("Ensure updated undefined login username is converted to a string");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);
  let collection = server.user("foo").collection("passwords");

  let guid1 = Utils.makeGUID();
  let guid2 = Utils.makeGUID();
  let remoteDetails = {
    formSubmitURL: "https://www.undefinedupdateexample.com",
    hostname: "https://www.undefinedupdateexample.com",
    httpRealm: null,
    username: undefined,
    password: "bar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
  };
  let localDetails = {
    formSubmitURL: "https://www.undefinedupdateexample.com",
    hostname: "https://www.undefinedupdateexample.com",
    httpRealm: null,
    username: "foo",
    password: "foobar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
  };

  _("Create remote record with same details and guid1");
  collection.insertRecord(Object.assign({}, remoteDetails, { id: guid1 }));

  try {
    _("Create local updated login with undefined password");
    await engine._store.update(Object.assign({}, localDetails, { id: guid2 }));

    _("Perform sync");
    await sync_engine_and_validate_telem(engine, false);

    let logins = Services.logins.findLogins(
      "https://www.undefinedupdateexample.com",
      "",
      ""
    );

    equal(logins.length, 1);
    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid1);
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_new_null_password_sync() {
  _("Ensure new null login username is converted to a string");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  let guid1 = Utils.makeGUID();
  let details = {
    formSubmitURL: "https://www.example.com",
    hostname: "https://www.example.com",
    httpRealm: null,
    username: null,
    password: "bar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
  };

  try {
    _("Create local login with null password");
    await engine._store.create(Object.assign({}, details, { id: guid1 }));

    _("Perform sync");
    await sync_engine_and_validate_telem(engine, false);

    let logins = Services.logins.findLogins("https://www.example.com", "", "");

    equal(logins.length, 1);
    notEqual(logins[0].QueryInterface(Ci.nsILoginMetaInfo).username, null);
    notEqual(logins[0].QueryInterface(Ci.nsILoginMetaInfo).username, undefined);
    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).username, "");
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_new_undefined_password_sync() {
  _("Ensure new undefined login username is converted to a string");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  let guid1 = Utils.makeGUID();
  let details = {
    formSubmitURL: "https://www.example.com",
    hostname: "https://www.example.com",
    httpRealm: null,
    username: undefined,
    password: "bar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
  };

  try {
    _("Create local login with undefined password");
    await engine._store.create(Object.assign({}, details, { id: guid1 }));

    _("Perform sync");
    await sync_engine_and_validate_telem(engine, false);

    let logins = Services.logins.findLogins("https://www.example.com", "", "");

    equal(logins.length, 1);
    notEqual(logins[0].QueryInterface(Ci.nsILoginMetaInfo).username, null);
    notEqual(logins[0].QueryInterface(Ci.nsILoginMetaInfo).username, undefined);
    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).username, "");
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_sync_password_validation() {
  // This test isn't in test_password_validator to avoid duplicating cleanup.
  _("Ensure that if a password validation happens, it ends up in the ping");

  let engine = Service.engineManager.get("passwords");

  let server = await serverForFoo(engine);
  await SyncTestingInfrastructure(server);

  Svc.Prefs.set("engine.passwords.validation.interval", 0);
  Svc.Prefs.set("engine.passwords.validation.percentageChance", 100);
  Svc.Prefs.set("engine.passwords.validation.maxRecords", -1);
  Svc.Prefs.set("engine.passwords.validation.enabled", true);

  try {
    let ping = await wait_for_ping(() => Service.sync());

    let engineInfo = ping.engines.find(e => e.name == "passwords");
    ok(engineInfo, "Engine should be in ping");

    let validation = engineInfo.validation;
    ok(validation, "Engine should have validation info");
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_migrate_metadata() {
  _("Ensure we correctly migrate metadata from prefs to the LoginManager");

  // Sadly we first need to manually reset the login manager data for this.
  Services.logins.setSyncID(null);
  Services.logins.setLastSync(0);
  // And set the pref values we want to migrate from.
  Svc.Prefs.set("passwords.syncID", "pref-value");
  Svc.Prefs.set("passwords.lastSync", 1);

  let engine = Service.engineManager.get("passwords");

  try {
    equal(await engine.getSyncID(), "pref-value");
    equal(await engine.getLastSync(), 1);
    // check we removed the prefs.
    ok(!Svc.Prefs.isSet("passwords.syncID"));
    ok(!Svc.Prefs.isSet("passwords.lastSync"));

    // explicitly set them - prefs should not be touched.
    await engine.ensureCurrentSyncID("new-value");
    await engine.setLastSync(2);
    equal(await engine.getSyncID(), "new-value");
    equal(await engine.getLastSync(), 2);
    ok(!Svc.Prefs.isSet("passwords.syncID"));
    ok(!Svc.Prefs.isSet("passwords.lastSync"));

    // Perform an engine reset.
    await engine._resetClient();
    // timestamp should have been reset (but syncID isn't)
    equal(await engine.getSyncID(), "new-value");
    equal(await engine.getLastSync(), 0);
    // and still no prefs.
    ok(!Svc.Prefs.isSet("passwords.syncID"));
    ok(!Svc.Prefs.isSet("passwords.lastSync"));
  } finally {
    await cleanup(engine, null);
  }
});