summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_password_engine.js
blob: 081403f63d40184a90c6827c5d3ab55515f69511 (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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
const { FXA_PWDMGR_HOST, FXA_PWDMGR_REALM } = ChromeUtils.importESModule(
  "resource://gre/modules/FxAccountsCommon.sys.mjs"
);
const { LoginRec } = ChromeUtils.importESModule(
  "resource://services-sync/engines/passwords.sys.mjs"
);
const { Service } = ChromeUtils.importESModule(
  "resource://services-sync/service.sys.mjs"
);

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

const { LoginCSVImport } = ChromeUtils.importESModule(
  "resource://gre/modules/LoginCSVImport.sys.mjs"
);

const { FileTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/FileTestUtils.sys.mjs"
);

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

async function cleanup(engine, server) {
  await engine._tracker.stop();
  await engine.wipeClient();
  engine.lastModified = null;
  for (const pref of Svc.PrefBranch.getChildList("")) {
    Svc.PrefBranch.clearUserPref(pref);
  }
  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 loginInfo = new LoginInfo(
    "https://example.com",
    "",
    null,
    "username",
    "password",
    "",
    ""
  );

  // Setting syncCounter to -1 so that it will be incremented to 0 when added.
  loginInfo.syncCounter = -1;
  let login = await Services.logins.addLoginAsync(loginInfo);
  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 = await Services.logins.addLoginAsync(
      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");

    let foundLogins = await Services.logins.searchLoginsAsync({
      origin: FXA_PWDMGR_HOST,
    });
    equal(foundLogins.length, 1);
    equal(foundLogins[0].syncCounter, 0);
    equal(foundLogins[0].everSynced, false);
  } 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",
      "",
      ""
    );
    await Services.logins.addLoginAsync(login);

    let logins = await Services.logins.searchLoginsAsync({
      origin: "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",
      "",
      ""
    );
    await Services.logins.addLoginAsync(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 = await Services.logins.searchLoginsAsync({
      origin: "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 = await Services.logins.searchLoginsAsync({
      origin: "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_sync_outgoing() {
  _("Test syncing outgoing records");

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

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

  let collection = server.user("foo").collection("passwords");

  let loginInfo = new LoginInfo(
    "http://mozilla.com",
    "http://mozilla.com",
    null,
    "theuser",
    "thepassword",
    "username",
    "password"
  );
  let login = await Services.logins.addLoginAsync(loginInfo);

  engine._tracker.start();

  try {
    let foundLogins = await Services.logins.searchLoginsAsync({
      origin: "http://mozilla.com",
    });
    equal(foundLogins.length, 1);
    equal(foundLogins[0].syncCounter, 1);
    equal(foundLogins[0].everSynced, false);
    equal(collection.count(), 0);

    let guid = foundLogins[0].QueryInterface(Ci.nsILoginMetaInfo).guid;

    let changes = await engine.getChangedIDs();
    let change = changes[guid];
    equal(Object.keys(changes).length, 1);
    equal(change.counter, 1);
    ok(!change.deleted);

    // This test modifies the password and then performs a sync and
    // then ensures that the synced record is correct. This is done twice
    // to ensure that syncing occurs correctly when the server record does not
    // yet exist and when it does already exist.
    for (let i = 1; i <= 2; i++) {
      _("Modify the password iteration " + i);
      foundLogins[0].password = "newpassword" + i;
      Services.logins.modifyLogin(login, foundLogins[0]);
      foundLogins = await Services.logins.searchLoginsAsync({
        origin: "http://mozilla.com",
      });
      equal(foundLogins.length, 1);
      // On the first pass, the counter should be 2, one for the add and one for the modify.
      // No sync has occurred yet so everSynced should be false.
      // On the second pass, the counter will only be 1 for the modify. The everSynced
      // property should be true as the sync happened on the last iteration.
      equal(foundLogins[0].syncCounter, i == 2 ? 1 : 2);
      equal(foundLogins[0].everSynced, i == 2);

      changes = await engine.getChangedIDs();
      change = changes[guid];
      equal(Object.keys(changes).length, 1);
      equal(change.counter, i == 2 ? 1 : 2);
      ok(!change.deleted);

      _("Perform sync after modifying the password");
      await sync_engine_and_validate_telem(engine, false);

      equal(Object.keys(await engine.getChangedIDs()), 0);

      // The remote login should have the updated password.
      let newRec = collection.cleartext(guid);
      equal(
        newRec.password,
        "newpassword" + i,
        "Should update remote password for login"
      );

      foundLogins = await Services.logins.searchLoginsAsync({
        origin: "http://mozilla.com",
      });
      equal(foundLogins.length, 1);
      equal(foundLogins[0].syncCounter, 0);
      equal(foundLogins[0].everSynced, true);

      login.password = "newpassword" + i;
    }

    // Next, modify the username and sync.
    _("Modify the username");
    foundLogins[0].username = "newuser";
    Services.logins.modifyLogin(login, foundLogins[0]);
    foundLogins = await Services.logins.searchLoginsAsync({
      origin: "http://mozilla.com",
    });
    equal(foundLogins.length, 1);
    equal(foundLogins[0].syncCounter, 1);
    equal(foundLogins[0].everSynced, true);

    _("Perform sync after modifying the username");
    await sync_engine_and_validate_telem(engine, false);

    // The remote login should have the updated password.
    let newRec = collection.cleartext(guid);
    equal(
      newRec.username,
      "newuser",
      "Should update remote username for login"
    );

    foundLogins = await Services.logins.searchLoginsAsync({
      origin: "http://mozilla.com",
    });
    equal(foundLogins.length, 1);
    equal(foundLogins[0].syncCounter, 0);
    equal(foundLogins[0].everSynced, true);

    // Finally, remove the login. The server record should be marked as deleted.
    _("Remove the login");
    equal(collection.count(), 1);
    equal(Services.logins.countLogins("", "", ""), 2);
    equal((await Services.logins.getAllLogins()).length, 2);
    ok(await engine._store.itemExists(guid));

    ok((await engine._store.getAllIDs())[guid]);

    Services.logins.removeLogin(foundLogins[0]);
    foundLogins = await Services.logins.searchLoginsAsync({
      origin: "http://mozilla.com",
    });
    equal(foundLogins.length, 0);

    changes = await engine.getChangedIDs();
    change = changes[guid];
    equal(Object.keys(changes).length, 1);
    equal(change.counter, 1);
    ok(change.deleted);

    _("Perform sync after removing the login");
    await sync_engine_and_validate_telem(engine, false);

    equal(collection.count(), 1);
    let payload = collection.payloads()[0];
    ok(payload.deleted);

    equal(Object.keys(await engine.getChangedIDs()), 0);

    // All of these should not include the deleted login. Only the FxA password should exist.
    equal(Services.logins.countLogins("", "", ""), 1);
    equal((await Services.logins.getAllLogins()).length, 1);
    ok(!(await engine._store.itemExists(guid)));

    // getAllIDs includes deleted items but skips the FxA login.
    ok((await engine._store.getAllIDs())[guid]);
    let deletedLogin = await engine._store._getLoginFromGUID(guid);

    equal(deletedLogin.hostname, null, "deleted login hostname");
    equal(
      deletedLogin.formActionOrigin,
      null,
      "deleted login formActionOrigin"
    );
    equal(deletedLogin.formSubmitURL, null, "deleted login formSubmitURL");
    equal(deletedLogin.httpRealm, null, "deleted login httpRealm");
    equal(deletedLogin.username, null, "deleted login username");
    equal(deletedLogin.password, null, "deleted login password");
    equal(deletedLogin.usernameField, "", "deleted login usernameField");
    equal(deletedLogin.passwordField, "", "deleted login passwordField");
    equal(deletedLogin.unknownFields, null, "deleted login unknownFields");
    equal(deletedLogin.timeCreated, 0, "deleted login timeCreated");
    equal(deletedLogin.timeLastUsed, 0, "deleted login timeLastUsed");
    equal(deletedLogin.timesUsed, 0, "deleted login timesUsed");

    // These fields are not reset when the login is removed.
    equal(deletedLogin.guid, guid, "deleted login guid");
    equal(deletedLogin.everSynced, true, "deleted login everSynced");
    equal(deletedLogin.syncCounter, 0, "deleted login syncCounter");
    ok(
      deletedLogin.timePasswordChanged > 0,
      "deleted login timePasswordChanged"
    );
  } finally {
    await engine._tracker.stop();

    await cleanup(engine, server);
  }
});

add_task(async function test_sync_incoming() {
  _("Test syncing incoming records");

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

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

  let collection = server.user("foo").collection("passwords");

  const checkFields = [
    "formSubmitURL",
    "hostname",
    "httpRealm",
    "username",
    "password",
    "usernameField",
    "passwordField",
    "timeCreated",
  ];

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

  try {
    // This test creates a remote server record and then verifies that the login
    // has been added locally after the sync occurs.
    _("Create remote login");
    collection.insertRecord(Object.assign({}, details, { id: guid1 }));

    _("Perform sync when remote login has been added");
    await sync_engine_and_validate_telem(engine, false);

    let logins = await Services.logins.searchLoginsAsync({
      origin: "https://www.example.com",
    });
    equal(logins.length, 1);

    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid1);
    checkFields.forEach(field => {
      equal(logins[0][field], details[field]);
    });
    equal(logins[0].timePasswordChanged, details.timePasswordChanged);
    equal(logins[0].syncCounter, 0);
    equal(logins[0].everSynced, true);

    // Modify the password within the remote record and then sync again.
    _("Perform sync when remote login's password has been modified");
    let newTime = Date.now();
    collection.updateRecord(
      guid1,
      cleartext => {
        cleartext.password = "alpaca";
      },
      newTime / 1000 + 10
    );

    await engine.setLastSync(newTime / 1000 - 30);
    await sync_engine_and_validate_telem(engine, false);

    logins = await Services.logins.searchLoginsAsync({
      origin: "https://www.example.com",
    });
    equal(logins.length, 1);

    details.password = "alpaca";
    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid1);
    checkFields.forEach(field => {
      equal(logins[0][field], details[field]);
    });
    ok(logins[0].timePasswordChanged > details.timePasswordChanged);
    equal(logins[0].syncCounter, 0);
    equal(logins[0].everSynced, true);

    // Modify the username within the remote record and then sync again.
    _("Perform sync when remote login's username has been modified");
    newTime = Date.now();
    collection.updateRecord(
      guid1,
      cleartext => {
        cleartext.username = "guanaco";
      },
      newTime / 1000 + 10
    );

    await engine.setLastSync(newTime / 1000 - 30);
    await sync_engine_and_validate_telem(engine, false);

    logins = await Services.logins.searchLoginsAsync({
      origin: "https://www.example.com",
    });
    equal(logins.length, 1);

    details.username = "guanaco";
    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid1);
    checkFields.forEach(field => {
      equal(logins[0][field], details[field]);
    });
    ok(logins[0].timePasswordChanged > details.timePasswordChanged);
    equal(logins[0].syncCounter, 0);
    equal(logins[0].everSynced, true);

    // Mark the remote record as deleted and then sync again.
    _("Perform sync when remote login has been marked for deletion");
    newTime = Date.now();
    collection.updateRecord(
      guid1,
      cleartext => {
        cleartext.deleted = true;
      },
      newTime / 1000 + 10
    );

    await engine.setLastSync(newTime / 1000 - 30);
    await sync_engine_and_validate_telem(engine, false);

    logins = await Services.logins.searchLoginsAsync({
      origin: "https://www.example.com",
    });
    equal(logins.length, 0);
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_sync_incoming_deleted() {
  _("Test syncing incoming deleted records");

  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 details2 = {
    formSubmitURL: "https://www.example.org",
    hostname: "https://www.example.org",
    httpRealm: null,
    username: "capybara",
    password: "beaver",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Date.now(),
    timePasswordChanged: Date.now(),
    deleted: true,
  };

  try {
    // This test creates a remote server record that has been deleted
    // and then verifies that the login is not imported locally.
    _("Create remote login");
    collection.insertRecord(Object.assign({}, details2, { id: guid1 }));

    _("Perform sync when remote login has been deleted");
    await sync_engine_and_validate_telem(engine, false);

    let logins = await Services.logins.searchLoginsAsync({
      origin: "https://www.example.com",
    });
    equal(logins.length, 0);
    ok(!(await engine._store.getAllIDs())[guid1]);
    ok(!(await engine._store.itemExists(guid1)));
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_sync_incoming_deleted_localchanged_remotenewer() {
  _(
    "Test syncing incoming deleted records where the local login has been changed but the remote record is newer"
  );

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

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

  let collection = server.user("foo").collection("passwords");

  let loginInfo = new LoginInfo(
    "http://mozilla.com",
    "http://mozilla.com",
    null,
    "kangaroo",
    "kaola",
    "username",
    "password"
  );
  let login = await Services.logins.addLoginAsync(loginInfo);
  let guid = login.QueryInterface(Ci.nsILoginMetaInfo).guid;

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

    let foundLogins = await Services.logins.searchLoginsAsync({
      origin: "http://mozilla.com",
    });
    foundLogins[0].password = "wallaby";
    Services.logins.modifyLogin(login, foundLogins[0]);

    // Use a time in the future to ensure that the remote record is newer.
    collection.updateRecord(
      guid,
      cleartext => {
        cleartext.deleted = true;
      },
      Date.now() / 1000 + 1000
    );

    _(
      "Perform sync when remote login has been deleted and local login has been changed"
    );
    await sync_engine_and_validate_telem(engine, false);

    let logins = await Services.logins.searchLoginsAsync({
      origin: "https://mozilla.com",
    });
    equal(logins.length, 0);
    ok(await engine._store.getAllIDs());
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_sync_incoming_deleted_localchanged_localnewer() {
  _(
    "Test syncing incoming deleted records where the local login has been changed but the local record is newer"
  );

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

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

  let collection = server.user("foo").collection("passwords");

  let loginInfo = new LoginInfo(
    "http://www.mozilla.com",
    "http://www.mozilla.com",
    null,
    "lion",
    "tiger",
    "username",
    "password"
  );
  let login = await Services.logins.addLoginAsync(loginInfo);
  let guid = login.QueryInterface(Ci.nsILoginMetaInfo).guid;

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

    let foundLogins = await Services.logins.searchLoginsAsync({
      origin: "http://www.mozilla.com",
    });
    foundLogins[0].password = "cheetah";
    Services.logins.modifyLogin(login, foundLogins[0]);

    // Use a time in the past to ensure that the local record is newer.
    collection.updateRecord(
      guid,
      cleartext => {
        cleartext.deleted = true;
      },
      Date.now() / 1000 - 1000
    );

    _(
      "Perform sync when remote login has been deleted and local login has been changed"
    );
    await sync_engine_and_validate_telem(engine, false);

    let logins = await Services.logins.searchLoginsAsync({
      origin: "http://www.mozilla.com",
    });
    equal(logins.length, 1);
    equal(logins[0].password, "cheetah");
    equal(logins[0].syncCounter, 0);
    equal(logins[0].everSynced, true);
    ok(await engine._store.getAllIDs());
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_sync_incoming_no_formactionorigin() {
  _("Test syncing incoming a record where there is no formActionOrigin");

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

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

  let collection = server.user("foo").collection("passwords");

  const checkFields = [
    "formSubmitURL",
    "hostname",
    "httpRealm",
    "username",
    "password",
    "usernameField",
    "passwordField",
    "timeCreated",
  ];

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

  try {
    // This test creates a remote server record and then verifies that the login
    // has been added locally after the sync occurs.
    _("Create remote login");
    collection.insertRecord(Object.assign({}, details, { id: guid1 }));

    _("Perform sync when remote login has been added");
    await sync_engine_and_validate_telem(engine, false);

    let logins = await Services.logins.searchLoginsAsync({
      origin: "https://www.example.com",
      formActionOrigin: "",
    });
    equal(logins.length, 1);

    equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid1);
    checkFields.forEach(field => {
      equal(logins[0][field], details[field]);
    });
    equal(logins[0].timePasswordChanged, details.timePasswordChanged);
    equal(logins[0].syncCounter, 0);
    equal(logins[0].everSynced, true);
  } 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 rec1 = new LoginRec("passwords", guid1);
  let guid2 = Utils.makeGUID();
  let cleartext = {
    formSubmitURL: "https://www.example.com",
    hostname: "https://www.example.com",
    httpRealm: null,
    username: "foo",
    password: "bar",
    usernameField: "username-field",
    passwordField: "password-field",
    timeCreated: Math.round(Date.now()),
    timePasswordChanged: Math.round(Date.now()),
  };
  rec1.cleartext = cleartext;

  _("Create remote record with same details and guid1");
  collection.insert(guid1, encryptPayload(rec1.cleartext));

  _("Create remote record with guid2");
  collection.insert(guid2, encryptPayload(cleartext));

  _("Create local record with same details and guid1");
  await engine._store.create(rec1);

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

    let logins = await Services.logins.searchLoginsAsync({
      origin: "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 = await Services.logins.searchLoginsAsync({
      origin: "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 = await Services.logins.searchLoginsAsync({
      origin: "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 rec1 = new LoginRec("passwords", guid1);
  rec1.cleartext = {
    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(rec1);

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

    let logins = await Services.logins.searchLoginsAsync({
      origin: "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 rec1 = new LoginRec("passwords", guid1);
  rec1.cleartext = {
    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(rec1);

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

    let logins = await Services.logins.searchLoginsAsync({
      origin: "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.PrefBranch.setIntPref("engine.passwords.validation.interval", 0);
  Svc.PrefBranch.setIntPref(
    "engine.passwords.validation.percentageChance",
    100
  );
  Svc.PrefBranch.setIntPref("engine.passwords.validation.maxRecords", -1);
  Svc.PrefBranch.setBoolPref("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_roundtrip_unknown_fields() {
  _(
    "Testing that unknown fields from other clients get roundtripped back to server"
  );

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

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

  enableValidationPrefs();

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

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

    let logins = await Services.logins.searchLoginsAsync({
      origin: "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 = Math.round(Date.now());

    // pretend other clients have some snazzy new fields
    // we don't quite understand yet
    rec.cleartext.someStrField = "I am a str";
    rec.cleartext.someObjField = { newField: "I am a new field" };
    collection.insert(oldLogin.guid, encryptPayload(rec.cleartext));
  }

  await engine._tracker.stop();

  try {
    await sync_engine_and_validate_telem(engine, false);

    let logins = await Services.logins.searchLoginsAsync({
      origin: "https://mozilla.com",
    });
    equal(
      logins[0].password,
      "n3wpa55",
      "Should update local password for older login"
    );
    let expectedUnknowns = JSON.stringify({
      someStrField: "I am a str",
      someObjField: { newField: "I am a new field" },
    });
    // Check that the local record has all unknown fields properly
    // stringified
    equal(logins[0].unknownFields, expectedUnknowns);

    // Check that the server has the unknown fields unfurled and on the
    // top-level record
    let serverRec = collection.cleartext(oldLogin.guid);
    equal(serverRec.someStrField, "I am a str");
    equal(serverRec.someObjField.newField, "I am a new field");
  } finally {
    await cleanup(engine, server);
  }
});

add_task(async function test_new_passwords_from_csv() {
  _("Test syncing records imported from a csv file");

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

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

  let collection = server.user("foo").collection("passwords");

  engine._tracker.start();

  let data = [
    {
      hostname: "https://example.com",
      url: "https://example.com/path",
      username: "exampleuser",
      password: "examplepassword",
    },
    {
      hostname: "https://mozilla.org",
      url: "https://mozilla.org",
      username: "mozillauser",
      password: "mozillapassword",
    },
    {
      hostname: "https://www.example.org",
      url: "https://www.example.org/example1/example2",
      username: "person",
      password: "mypassword",
    },
  ];

  let csvData = ["url,username,login_password"];
  for (let row of data) {
    csvData.push(row.url + "," + row.username + "," + row.password);
  }

  let csvFile = FileTestUtils.getTempFile(`firefox_logins.csv`);
  await IOUtils.writeUTF8(csvFile.path, csvData.join("\r\n"));

  await LoginCSVImport.importFromCSV(csvFile.path);

  equal(
    engine._tracker.score,
    SCORE_INCREMENT_XLARGE,
    "Should only get one update notification for import"
  );

  _("Ensure that the csv import is correct");
  for (let item of data) {
    let foundLogins = await Services.logins.searchLoginsAsync({
      origin: item.hostname,
    });
    equal(foundLogins.length, 1);
    equal(foundLogins[0].syncCounter, 1);
    equal(foundLogins[0].everSynced, false);
    equal(foundLogins[0].username, item.username);
    equal(foundLogins[0].password, item.password);
  }

  _("Perform sync after modifying the password");
  await sync_engine_and_validate_telem(engine, false);

  _("Verify that the sync counter and status are updated");
  for (let item of data) {
    let foundLogins = await Services.logins.searchLoginsAsync({
      origin: item.hostname,
    });
    equal(foundLogins.length, 1);
    equal(foundLogins[0].syncCounter, 0);
    equal(foundLogins[0].everSynced, true);
    equal(foundLogins[0].username, item.username);
    equal(foundLogins[0].password, item.password);
    item.guid = foundLogins[0].guid;
  }

  equal(Object.keys(await engine.getChangedIDs()), 0);
  equal(collection.count(), 3);

  for (let item of data) {
    // The remote login should have the imported username and password.
    let newRec = collection.cleartext(item.guid);
    equal(newRec.username, item.username);
    equal(newRec.password, item.password);
  }
});