summaryrefslogtreecommitdiffstats
path: root/browser/components/preferences/tests/browser_extension_controlled.js
blob: d187af5b7d17a61b405d8c41c2914d0a946de5e9 (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
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
/* eslint-env webextensions */

const PROXY_PREF = "network.proxy.type";
const HOMEPAGE_URL_PREF = "browser.startup.homepage";
const HOMEPAGE_OVERRIDE_KEY = "homepage_override";
const URL_OVERRIDES_TYPE = "url_overrides";
const NEW_TAB_KEY = "newTabURL";
const PREF_SETTING_TYPE = "prefs";

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

XPCOMUtils.defineLazyPreferenceGetter(this, "proxyType", PROXY_PREF);

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

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

const TEST_DIR = gTestPath.substr(0, gTestPath.lastIndexOf("/"));
const CHROME_URL_ROOT = TEST_DIR + "/";
const PERMISSIONS_URL =
  "chrome://browser/content/preferences/dialogs/sitePermissions.xhtml";
let sitePermissionsDialog;

function getSupportsFile(path) {
  let cr = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(
    Ci.nsIChromeRegistry
  );
  let uri = Services.io.newURI(CHROME_URL_ROOT + path);
  let fileurl = cr.convertChromeURL(uri);
  return fileurl.QueryInterface(Ci.nsIFileURL);
}

function waitForMessageChange(
  element,
  cb,
  opts = { attributes: true, attributeFilter: ["hidden"] }
) {
  return waitForMutation(element, opts, cb);
}

function getElement(id, doc = gBrowser.contentDocument) {
  return doc.getElementById(id);
}

function waitForMessageHidden(messageId, doc) {
  return waitForMessageChange(
    getElement(messageId, doc),
    target => target.hidden
  );
}

function waitForMessageShown(messageId, doc) {
  return waitForMessageChange(
    getElement(messageId, doc),
    target => !target.hidden
  );
}

function waitForEnableMessage(messageId, doc) {
  return waitForMessageChange(
    getElement(messageId, doc),
    target => target.classList.contains("extension-controlled-disabled"),
    { attributeFilter: ["class"], attributes: true }
  );
}

function waitForMessageContent(messageId, l10nId, doc) {
  return waitForMessageChange(
    getElement(messageId, doc),
    target => doc.l10n.getAttributes(target).id === l10nId,
    { childList: true }
  );
}

async function openNotificationsPermissionDialog() {
  let dialogOpened = promiseLoadSubDialog(PERMISSIONS_URL);

  await SpecialPowers.spawn(gBrowser.selectedBrowser, [], function () {
    let doc = content.document;
    let settingsButton = doc.getElementById("notificationSettingsButton");
    settingsButton.click();
  });

  sitePermissionsDialog = await dialogOpened;
  await sitePermissionsDialog.document.mozSubdialogReady;
}

async function disableExtensionViaClick(labelId, disableButtonId, doc) {
  let controlledLabel = doc.getElementById(labelId);

  let enableMessageShown = waitForEnableMessage(labelId, doc);
  doc.getElementById(disableButtonId).click();
  await enableMessageShown;

  let controlledDescription = controlledLabel.querySelector("description");
  is(
    doc.l10n.getAttributes(controlledDescription.querySelector("label")).id,
    "extension-controlled-enable",
    "The user is notified of how to enable the extension again."
  );

  // The user can dismiss the enable instructions.
  let hidden = waitForMessageHidden(labelId, doc);
  controlledLabel.querySelector("image:last-of-type").click();
  await hidden;
}

async function reEnableExtension(addon, labelId) {
  let controlledMessageShown = waitForMessageShown(labelId);
  await addon.enable();
  await controlledMessageShown;
}

add_task(async function testExtensionControlledHomepage() {
  const ADDON_ID = "@set_homepage";
  const SECOND_ADDON_ID = "@second_set_homepage";

  await openPreferencesViaOpenPreferencesAPI("paneHome", { leaveOpen: true });
  let homepagePref = () => Services.prefs.getCharPref(HOMEPAGE_URL_PREF);
  let originalHomepagePref = homepagePref();
  is(
    gBrowser.currentURI.spec,
    "about:preferences#home",
    "#home should be in the URI for about:preferences"
  );
  let doc = gBrowser.contentDocument;
  let homeModeEl = doc.getElementById("homeMode");
  let customSettingsSection = doc.getElementById("customSettings");

  is(homeModeEl.itemCount, 3, "The menu list starts with 3 options");

  let promise = TestUtils.waitForCondition(
    () => homeModeEl.itemCount === 4,
    "wait for the addon option to be added as an option in the menu list"
  );
  let extension = ExtensionTestUtils.loadExtension({
    useAddonManager: "permanent",
    manifest: {
      version: "1.0",
      name: "set_homepage",
      browser_specific_settings: {
        gecko: {
          id: ADDON_ID,
        },
      },
      chrome_settings_overrides: { homepage: "/home.html" },
    },
  });
  await extension.startup();
  await promise;

  // The homepage is set to the default and the custom settings section is hidden
  is(homeModeEl.disabled, false, "The homepage menulist is enabled");
  is(
    customSettingsSection.hidden,
    true,
    "The custom settings element is hidden"
  );

  let addon = await AddonManager.getAddonByID(ADDON_ID);
  is(
    homeModeEl.value,
    addon.id,
    "the home select menu's value is set to the addon"
  );

  promise = TestUtils.waitForPrefChange(HOMEPAGE_URL_PREF);
  // Set the Menu to the default value
  homeModeEl.value = "0";
  homeModeEl.dispatchEvent(new Event("command"));
  await promise;
  is(homepagePref(), originalHomepagePref, "homepage is set back to default");
  let levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    addon.id,
    HOMEPAGE_OVERRIDE_KEY,
    PREF_SETTING_TYPE
  );
  is(
    levelOfControl,
    "not_controllable",
    "getLevelOfControl returns not_controllable."
  );
  let setting = await ExtensionPreferencesManager.getSetting(
    HOMEPAGE_OVERRIDE_KEY
  );
  ok(!setting.value, "the setting is not set.");

  promise = TestUtils.waitForPrefChange(HOMEPAGE_URL_PREF);
  // Set the menu to the addon value
  homeModeEl.value = ADDON_ID;
  homeModeEl.dispatchEvent(new Event("command"));
  await promise;
  ok(
    homepagePref().startsWith("moz-extension") &&
      homepagePref().endsWith("home.html"),
    "Home url should be provided by the extension."
  );
  levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    addon.id,
    HOMEPAGE_OVERRIDE_KEY,
    PREF_SETTING_TYPE
  );
  is(
    levelOfControl,
    "controlled_by_this_extension",
    "getLevelOfControl returns controlled_by_this_extension."
  );
  setting = await ExtensionPreferencesManager.getSetting(HOMEPAGE_OVERRIDE_KEY);
  ok(
    setting.value.startsWith("moz-extension") &&
      setting.value.endsWith("home.html"),
    "The setting value is the same as the extension."
  );

  // Add a second extension, ensure it is added to the menulist and selected.
  promise = TestUtils.waitForCondition(
    () => homeModeEl.itemCount == 5,
    "addon option is added as an option in the menu list"
  );
  let secondExtension = ExtensionTestUtils.loadExtension({
    useAddonManager: "permanent",
    manifest: {
      version: "1.0",
      name: "second_set_homepage",
      browser_specific_settings: {
        gecko: {
          id: SECOND_ADDON_ID,
        },
      },
      chrome_settings_overrides: { homepage: "/home2.html" },
    },
  });
  await secondExtension.startup();
  await promise;

  let secondAddon = await AddonManager.getAddonByID(SECOND_ADDON_ID);
  is(homeModeEl.value, SECOND_ADDON_ID, "home menulist is set to the add-on");

  levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    secondAddon.id,
    HOMEPAGE_OVERRIDE_KEY,
    PREF_SETTING_TYPE
  );
  is(
    levelOfControl,
    "controlled_by_this_extension",
    "getLevelOfControl returns controlled_by_this_extension."
  );
  setting = await ExtensionPreferencesManager.getSetting(HOMEPAGE_OVERRIDE_KEY);
  ok(
    setting.value.startsWith("moz-extension") &&
      setting.value.endsWith("home2.html"),
    "The setting value is the same as the extension."
  );

  promise = TestUtils.waitForCondition(
    () => homeModeEl.itemCount == 4,
    "addon option is no longer an option in the menu list after disable, even if it was not selected"
  );
  await addon.disable();
  await promise;

  // Ensure that re-enabling an addon adds it back to the menulist
  promise = TestUtils.waitForCondition(
    () => homeModeEl.itemCount == 5,
    "addon option is added again to the menulist when enabled"
  );
  await addon.enable();
  await promise;

  promise = TestUtils.waitForCondition(
    () => homeModeEl.itemCount == 4,
    "addon option is no longer an option in the menu list after disable"
  );
  await secondAddon.disable();
  await promise;

  promise = TestUtils.waitForCondition(
    () => homeModeEl.itemCount == 5,
    "addon option is added again to the menulist when enabled"
  );
  await secondAddon.enable();
  await promise;

  promise = TestUtils.waitForCondition(
    () => homeModeEl.itemCount == 3,
    "addon options are no longer an option in the menu list after disabling all addons"
  );
  await secondAddon.disable();
  await addon.disable();
  await promise;

  is(homeModeEl.value, "0", "addon option is not selected in the menu list");

  levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    secondAddon.id,
    HOMEPAGE_OVERRIDE_KEY,
    PREF_SETTING_TYPE
  );
  is(
    levelOfControl,
    "controllable_by_this_extension",
    "getLevelOfControl returns controllable_by_this_extension."
  );
  setting = await ExtensionPreferencesManager.getSetting(HOMEPAGE_OVERRIDE_KEY);
  ok(!setting.value, "The setting value is back to default.");

  // The homepage elements are reset to their original state.
  is(homepagePref(), originalHomepagePref, "homepage is set back to default");
  is(homeModeEl.disabled, false, "The homepage menulist is enabled");
  BrowserTestUtils.removeTab(gBrowser.selectedTab);
  await extension.unload();
  await secondExtension.unload();
});

add_task(async function testPrefLockedHomepage() {
  const ADDON_ID = "@set_homepage";
  await openPreferencesViaOpenPreferencesAPI("paneHome", { leaveOpen: true });
  let doc = gBrowser.contentDocument;
  is(
    gBrowser.currentURI.spec,
    "about:preferences#home",
    "#home should be in the URI for about:preferences"
  );

  let homePagePref = "browser.startup.homepage";
  let buttonPrefs = [
    "pref.browser.homepage.disable_button.current_page",
    "pref.browser.homepage.disable_button.bookmark_page",
    "pref.browser.homepage.disable_button.restore_default",
  ];
  let homeModeEl = doc.getElementById("homeMode");
  let homePageInput = doc.getElementById("homePageUrl");
  let prefs = Services.prefs.getDefaultBranch(null);
  let mutationOpts = { attributes: true, attributeFilter: ["disabled"] };

  // Helper functions.
  let getButton = pref =>
    doc.querySelector(`.homepage-button[preference="${pref}"`);
  let waitForAllMutations = () =>
    Promise.all(
      buttonPrefs
        .map(pref => waitForMutation(getButton(pref), mutationOpts))
        .concat([
          waitForMutation(homeModeEl, mutationOpts),
          waitForMutation(homePageInput, mutationOpts),
        ])
    );
  let getHomepage = () =>
    Services.prefs.getCharPref("browser.startup.homepage");

  let originalHomepage = getHomepage();
  let extensionHomepage = "https://developer.mozilla.org/";
  let lockedHomepage = "http://www.yahoo.com";

  let lockPrefs = () => {
    buttonPrefs.forEach(pref => {
      prefs.setBoolPref(pref, true);
      prefs.lockPref(pref);
    });
    // Do the homepage last since that's the only pref that triggers a UI update.
    prefs.setCharPref(homePagePref, lockedHomepage);
    prefs.lockPref(homePagePref);
  };
  let unlockPrefs = () => {
    buttonPrefs.forEach(pref => {
      prefs.unlockPref(pref);
      prefs.setBoolPref(pref, false);
    });
    // Do the homepage last since that's the only pref that triggers a UI update.
    prefs.unlockPref(homePagePref);
    prefs.setCharPref(homePagePref, originalHomepage);
  };

  // Lock or unlock prefs then wait for all mutations to finish.
  // Expects a bool indicating if we should lock or unlock.
  let waitForLockMutations = lock => {
    let mutationsDone = waitForAllMutations();
    if (lock) {
      lockPrefs();
    } else {
      unlockPrefs();
    }
    return mutationsDone;
  };

  Assert.notEqual(
    originalHomepage,
    extensionHomepage,
    "The extension will change the homepage"
  );

  // Install an extension that sets the homepage to MDN.
  let promise = TestUtils.waitForPrefChange(HOMEPAGE_URL_PREF);
  let extension = ExtensionTestUtils.loadExtension({
    useAddonManager: "permanent",
    manifest: {
      version: "1.0",
      name: "set_homepage",
      browser_specific_settings: {
        gecko: {
          id: ADDON_ID,
        },
      },
      chrome_settings_overrides: { homepage: "https://developer.mozilla.org/" },
    },
  });
  await extension.startup();
  await promise;

  // Check that everything is still disabled, homepage didn't change.
  is(
    getHomepage(),
    extensionHomepage,
    "The reported homepage is set by the extension"
  );
  is(
    homePageInput.value,
    extensionHomepage,
    "The homepage is set by the extension"
  );

  // Lock all of the prefs, wait for the UI to update.
  await waitForLockMutations(true);

  // Check that everything is now disabled.
  is(getHomepage(), lockedHomepage, "The reported homepage is set by the pref");
  is(homePageInput.value, lockedHomepage, "The homepage is set by the pref");
  is(
    homePageInput.disabled,
    true,
    "The homepage is disabed when the pref is locked"
  );

  buttonPrefs.forEach(pref => {
    is(
      getButton(pref).disabled,
      true,
      `The ${pref} button is disabled when locked`
    );
  });

  let levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    ADDON_ID,
    HOMEPAGE_OVERRIDE_KEY,
    PREF_SETTING_TYPE
  );
  is(
    levelOfControl,
    "not_controllable",
    "getLevelOfControl returns not_controllable, the pref is locked."
  );

  // Verify that the UI is selecting the extension's Id in the menulist
  let unlockedPromise = TestUtils.waitForCondition(
    () => homeModeEl.value == ADDON_ID,
    "Homepage menulist value is equal to the extension ID"
  );
  // Unlock the prefs, wait for the UI to update.
  unlockPrefs();
  await unlockedPromise;

  is(
    homeModeEl.disabled,
    false,
    "the home select element is not disabled when the pref is not locked"
  );
  is(
    homePageInput.disabled,
    false,
    "The homepage is enabled when the pref is unlocked"
  );
  is(
    getHomepage(),
    extensionHomepage,
    "The homepage is reset to extension page"
  );

  levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    ADDON_ID,
    HOMEPAGE_OVERRIDE_KEY,
    PREF_SETTING_TYPE
  );
  is(
    levelOfControl,
    "controlled_by_this_extension",
    "getLevelOfControl returns controlled_by_this_extension after prefs are unlocked."
  );
  let setting = await ExtensionPreferencesManager.getSetting(
    HOMEPAGE_OVERRIDE_KEY
  );
  is(
    setting.value,
    extensionHomepage,
    "The setting value is equal to the extensionHomepage."
  );

  // Uninstall the add-on.
  promise = TestUtils.waitForPrefChange(HOMEPAGE_URL_PREF);
  await extension.unload();
  await promise;

  setting = await ExtensionPreferencesManager.getSetting(HOMEPAGE_OVERRIDE_KEY);
  ok(!setting, "The setting is gone after the addon is uninstalled.");

  // Check that everything is now enabled again.
  is(
    getHomepage(),
    originalHomepage,
    "The reported homepage is reset to original value"
  );
  is(homePageInput.value, "", "The homepage is empty");
  is(
    homePageInput.disabled,
    false,
    "The homepage is enabled after clearing lock"
  );
  is(
    homeModeEl.disabled,
    false,
    "Homepage menulist is enabled after clearing lock"
  );
  buttonPrefs.forEach(pref => {
    is(
      getButton(pref).disabled,
      false,
      `The ${pref} button is enabled when unlocked`
    );
  });

  // Lock the prefs without an extension.
  await waitForLockMutations(true);

  // Check that everything is now disabled.
  is(getHomepage(), lockedHomepage, "The reported homepage is set by the pref");
  is(homePageInput.value, lockedHomepage, "The homepage is set by the pref");
  is(
    homePageInput.disabled,
    true,
    "The homepage is disabed when the pref is locked"
  );
  is(
    homeModeEl.disabled,
    true,
    "Homepage menulist is disabled when pref is locked"
  );
  buttonPrefs.forEach(pref => {
    is(
      getButton(pref).disabled,
      true,
      `The ${pref} button is disabled when locked`
    );
  });

  // Unlock the prefs without an extension.
  await waitForLockMutations(false);

  // Check that everything is enabled again.
  is(
    getHomepage(),
    originalHomepage,
    "The homepage is reset to the original value"
  );
  is(homePageInput.value, "", "The homepage is clear after being unlocked");
  is(
    homePageInput.disabled,
    false,
    "The homepage is enabled after clearing lock"
  );
  is(
    homeModeEl.disabled,
    false,
    "Homepage menulist is enabled after clearing lock"
  );
  buttonPrefs.forEach(pref => {
    is(
      getButton(pref).disabled,
      false,
      `The ${pref} button is enabled when unlocked`
    );
  });

  BrowserTestUtils.removeTab(gBrowser.selectedTab);
});

add_task(async function testExtensionControlledNewTab() {
  const ADDON_ID = "@set_newtab";
  const SECOND_ADDON_ID = "@second_set_newtab";
  const DEFAULT_NEWTAB = "about:newtab";
  const NEWTAB_CONTROLLED_PREF = "browser.newtab.extensionControlled";

  await openPreferencesViaOpenPreferencesAPI("paneHome", { leaveOpen: true });
  is(
    gBrowser.currentURI.spec,
    "about:preferences#home",
    "#home should be in the URI for about:preferences"
  );

  let doc = gBrowser.contentDocument;
  let newTabMenuList = doc.getElementById("newTabMode");
  // The new tab page is set to the default.
  is(AboutNewTab.newTabURL, DEFAULT_NEWTAB, "new tab is set to default");

  let promise = TestUtils.waitForCondition(
    () => newTabMenuList.itemCount == 3,
    "addon option is added as an option in the menu list"
  );
  // Install an extension that will set the new tab page.
  let extension = ExtensionTestUtils.loadExtension({
    useAddonManager: "permanent",
    manifest: {
      version: "1.0",
      name: "set_newtab",
      browser_specific_settings: {
        gecko: {
          id: ADDON_ID,
        },
      },
      chrome_url_overrides: { newtab: "/newtab.html" },
    },
  });
  await extension.startup();

  await promise;
  let addon = await AddonManager.getAddonByID(ADDON_ID);

  is(newTabMenuList.value, ADDON_ID, "New tab menulist is set to the add-on");

  let levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    addon.id,
    NEW_TAB_KEY,
    URL_OVERRIDES_TYPE
  );
  is(
    levelOfControl,
    "controlled_by_this_extension",
    "getLevelOfControl returns controlled_by_this_extension."
  );
  let setting = ExtensionSettingsStore.getSetting(
    URL_OVERRIDES_TYPE,
    NEW_TAB_KEY
  );
  ok(
    setting.value.startsWith("moz-extension") &&
      setting.value.endsWith("newtab.html"),
    "The url_overrides is set by this extension"
  );

  promise = TestUtils.waitForPrefChange(NEWTAB_CONTROLLED_PREF);
  // Set the menu to the default value
  newTabMenuList.value = "0";
  newTabMenuList.dispatchEvent(new Event("command"));
  await promise;
  let newTabPref = Services.prefs.getBoolPref(NEWTAB_CONTROLLED_PREF, false);
  is(newTabPref, false, "the new tab is not controlled");

  levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    addon.id,
    NEW_TAB_KEY,
    URL_OVERRIDES_TYPE
  );
  is(
    levelOfControl,
    "not_controllable",
    "getLevelOfControl returns not_controllable."
  );
  setting = ExtensionSettingsStore.getSetting(URL_OVERRIDES_TYPE, NEW_TAB_KEY);
  ok(!setting.value, "The url_overrides is not set by this extension");

  promise = TestUtils.waitForPrefChange(NEWTAB_CONTROLLED_PREF);
  // Set the menu to a the addon value
  newTabMenuList.value = ADDON_ID;
  newTabMenuList.dispatchEvent(new Event("command"));
  await promise;
  newTabPref = Services.prefs.getBoolPref(NEWTAB_CONTROLLED_PREF, false);
  is(newTabPref, true, "the new tab is controlled");

  // Add a second extension, ensure it is added to the menulist and selected.
  promise = TestUtils.waitForCondition(
    () => newTabMenuList.itemCount == 4,
    "addon option is added as an option in the menu list"
  );
  let secondExtension = ExtensionTestUtils.loadExtension({
    useAddonManager: "permanent",
    manifest: {
      version: "1.0",
      name: "second_set_newtab",
      browser_specific_settings: {
        gecko: {
          id: SECOND_ADDON_ID,
        },
      },
      chrome_url_overrides: { newtab: "/newtab2.html" },
    },
  });
  await secondExtension.startup();
  await promise;
  let secondAddon = await AddonManager.getAddonByID(SECOND_ADDON_ID);
  is(
    newTabMenuList.value,
    SECOND_ADDON_ID,
    "New tab menulist is set to the add-on"
  );

  levelOfControl = await ExtensionPreferencesManager.getLevelOfControl(
    secondAddon.id,
    NEW_TAB_KEY,
    URL_OVERRIDES_TYPE
  );
  is(
    levelOfControl,
    "controlled_by_this_extension",
    "getLevelOfControl returns controlled_by_this_extension."
  );
  setting = ExtensionSettingsStore.getSetting(URL_OVERRIDES_TYPE, NEW_TAB_KEY);
  ok(
    setting.value.startsWith("moz-extension") &&
      setting.value.endsWith("newtab2.html"),
    "The url_overrides is set by the second extension"
  );

  promise = TestUtils.waitForCondition(
    () => newTabMenuList.itemCount == 3,
    "addon option is no longer an option in the menu list after disable, even if it was not selected"
  );
  await addon.disable();
  await promise;

  // Ensure that re-enabling an addon adds it back to the menulist
  promise = TestUtils.waitForCondition(
    () => newTabMenuList.itemCount == 4,
    "addon option is added again to the menulist when enabled"
  );
  await addon.enable();
  await promise;

  promise = TestUtils.waitForCondition(
    () => newTabMenuList.itemCount == 3,
    "addon option is no longer an option in the menu list after disable"
  );
  await secondAddon.disable();
  await promise;

  promise = TestUtils.waitForCondition(
    () => newTabMenuList.itemCount == 4,
    "addon option is added again to the menulist when enabled"
  );
  await secondAddon.enable();
  await promise;

  promise = TestUtils.waitForCondition(
    () => newTabMenuList.itemCount == 2,
    "addon options are all removed after disabling all"
  );
  await addon.disable();
  await secondAddon.disable();
  await promise;
  is(
    AboutNewTab.newTabURL,
    DEFAULT_NEWTAB,
    "new tab page is set back to default"
  );

  // Cleanup the tabs and add-on.
  BrowserTestUtils.removeTab(gBrowser.selectedTab);
  await extension.unload();
  await secondExtension.unload();
});

add_task(async function testExtensionControlledWebNotificationsPermission() {
  let manifest = {
    manifest_version: 2,
    name: "TestExtension",
    version: "1.0",
    description: "Testing WebNotificationsDisable",
    browser_specific_settings: { gecko: { id: "@web_notifications_disable" } },
    permissions: ["browserSettings"],
    browser_action: {
      default_title: "Testing",
    },
  };

  await openPreferencesViaOpenPreferencesAPI("privacy", { leaveOpen: true });
  await openNotificationsPermissionDialog();

  let doc = sitePermissionsDialog.document;
  let extensionControlledContent = doc.getElementById(
    "browserNotificationsPermissionExtensionContent"
  );

  // Test that extension content is initially hidden.
  ok(
    extensionControlledContent.hidden,
    "Extension content is initially hidden"
  );

  // Install an extension that will disable web notifications permission.
  let messageShown = waitForMessageShown(
    "browserNotificationsPermissionExtensionContent",
    doc
  );
  let extension = ExtensionTestUtils.loadExtension({
    manifest,
    useAddonManager: "permanent",
    background() {
      browser.browserSettings.webNotificationsDisabled.set({ value: true });
      browser.test.sendMessage("load-extension");
    },
  });
  await extension.startup();
  await extension.awaitMessage("load-extension");
  await messageShown;

  let controlledDesc = extensionControlledContent.querySelector("description");
  Assert.deepEqual(
    doc.l10n.getAttributes(controlledDesc),
    {
      id: "extension-controlling-web-notifications",
      args: {
        name: "TestExtension",
      },
    },
    "The user is notified that an extension is controlling the web notifications permission"
  );
  is(
    extensionControlledContent.hidden,
    false,
    "The extension controlled row is not hidden"
  );

  // Disable the extension.
  doc.getElementById("disableNotificationsPermissionExtension").click();

  // Verify the user is notified how to enable the extension.
  await waitForEnableMessage(extensionControlledContent.id, doc);
  is(
    doc.l10n.getAttributes(controlledDesc.querySelector("label")).id,
    "extension-controlled-enable",
    "The user is notified of how to enable the extension again"
  );

  // Verify the enable message can be dismissed.
  let hidden = waitForMessageHidden(extensionControlledContent.id, doc);
  let dismissButton = controlledDesc.querySelector("image:last-of-type");
  dismissButton.click();
  await hidden;

  // Verify that the extension controlled content in hidden again.
  is(
    extensionControlledContent.hidden,
    true,
    "The extension controlled row is now hidden"
  );

  await extension.unload();
  BrowserTestUtils.removeTab(gBrowser.selectedTab);
});

add_task(async function testExtensionControlledHomepageUninstalledAddon() {
  async function checkHomepageEnabled() {
    await openPreferencesViaOpenPreferencesAPI("paneHome", { leaveOpen: true });
    let doc = gBrowser.contentDocument;
    is(
      gBrowser.currentURI.spec,
      "about:preferences#home",
      "#home should be in the URI for about:preferences"
    );

    // The homepage is enabled.
    let homepageInput = doc.getElementById("homePageUrl");
    is(homepageInput.disabled, false, "The homepage input is enabled");
    is(homepageInput.value, "", "The homepage input is empty");

    BrowserTestUtils.removeTab(gBrowser.selectedTab);
  }

  await ExtensionSettingsStore.initialize();

  // Verify the setting isn't reported as controlled and the inputs are enabled.
  is(
    ExtensionSettingsStore.getSetting("prefs", "homepage_override"),
    null,
    "The homepage_override is not set"
  );
  await checkHomepageEnabled();

  // Disarm any pending writes before we modify the JSONFile directly.
  await ExtensionSettingsStore._reloadFile(false);

  // Write out a bad store file.
  let storeData = {
    prefs: {
      homepage_override: {
        initialValue: "",
        precedenceList: [
          {
            id: "bad@mochi.test",
            installDate: 1508802672,
            value: "https://developer.mozilla.org",
            enabled: true,
          },
        ],
      },
    },
  };
  let jsonFileName = "extension-settings.json";
  let storePath = PathUtils.join(PathUtils.profileDir, jsonFileName);

  await IOUtils.writeUTF8(storePath, JSON.stringify(storeData));

  // Reload the ExtensionSettingsStore so it will read the file on disk. Don't
  // finalize the current store since it will overwrite our file.
  await ExtensionSettingsStore._reloadFile(false);

  // Verify that the setting is reported as set, but the homepage is still enabled
  // since there is no matching installed extension.
  is(
    ExtensionSettingsStore.getSetting("prefs", "homepage_override").value,
    "https://developer.mozilla.org",
    "The homepage_override appears to be set"
  );
  await checkHomepageEnabled();

  // Remove the bad store file that we used.
  await IOUtils.remove(storePath);

  // Reload the ExtensionSettingsStore again so it clears the data we added.
  // Don't finalize the current store since it will write out the bad data.
  await ExtensionSettingsStore._reloadFile(false);

  is(
    ExtensionSettingsStore.getSetting("prefs", "homepage_override"),
    null,
    "The ExtensionSettingsStore is left empty."
  );
});

add_task(async function testExtensionControlledTrackingProtection() {
  const TP_PREF = "privacy.trackingprotection.enabled";
  const TP_DEFAULT = false;
  const EXTENSION_ID = "@set_tp";
  const CONTROLLED_LABEL_ID =
    "contentBlockingTrackingProtectionExtensionContentLabel";
  const CONTROLLED_BUTTON_ID =
    "contentBlockingDisableTrackingProtectionExtension";

  let tpEnabledPref = () => Services.prefs.getBoolPref(TP_PREF);

  await SpecialPowers.pushPrefEnv({ set: [[TP_PREF, TP_DEFAULT]] });

  function background() {
    browser.privacy.websites.trackingProtectionMode.set({ value: "always" });
  }

  function verifyState(isControlled) {
    is(tpEnabledPref(), isControlled, "TP pref is set to the expected value.");

    let controlledLabel = doc.getElementById(CONTROLLED_LABEL_ID);
    let controlledButton = doc.getElementById(CONTROLLED_BUTTON_ID);

    is(
      controlledLabel.hidden,
      !isControlled,
      "The extension controlled row's visibility is as expected."
    );
    is(
      controlledButton.hidden,
      !isControlled,
      "The disable extension button's visibility is as expected."
    );
    if (isControlled) {
      let controlledDesc = controlledLabel.querySelector("description");
      Assert.deepEqual(
        doc.l10n.getAttributes(controlledDesc),
        {
          id: "extension-controlling-websites-content-blocking-all-trackers",
          args: {
            name: "set_tp",
          },
        },
        "The user is notified that an extension is controlling TP."
      );
    }

    is(
      doc.getElementById("trackingProtectionMenu").disabled,
      isControlled,
      "TP control is enabled."
    );
  }

  await openPreferencesViaOpenPreferencesAPI("panePrivacy", {
    leaveOpen: true,
  });
  let doc = gBrowser.contentDocument;

  is(
    gBrowser.currentURI.spec,
    "about:preferences#privacy",
    "#privacy should be in the URI for about:preferences"
  );

  verifyState(false);

  // Install an extension that sets Tracking Protection.
  let extension = ExtensionTestUtils.loadExtension({
    useAddonManager: "permanent",
    manifest: {
      name: "set_tp",
      browser_specific_settings: { gecko: { id: EXTENSION_ID } },
      permissions: ["privacy"],
    },
    background,
  });

  let messageShown = waitForMessageShown(CONTROLLED_LABEL_ID);
  await extension.startup();
  await messageShown;
  let addon = await AddonManager.getAddonByID(EXTENSION_ID);

  verifyState(true);

  await disableExtensionViaClick(
    CONTROLLED_LABEL_ID,
    CONTROLLED_BUTTON_ID,
    doc
  );

  verifyState(false);

  // Enable the extension so we get the UNINSTALL event, which is needed by
  // ExtensionPreferencesManager to clean up properly.
  // TODO: BUG 1408226
  await reEnableExtension(addon, CONTROLLED_LABEL_ID);

  await extension.unload();

  BrowserTestUtils.removeTab(gBrowser.selectedTab);
});

add_task(async function testExtensionControlledPasswordManager() {
  const PASSWORD_MANAGER_ENABLED_PREF = "signon.rememberSignons";
  const PASSWORD_MANAGER_ENABLED_DEFAULT = true;
  const CONTROLLED_BUTTON_ID = "disablePasswordManagerExtension";
  const CONTROLLED_LABEL_ID = "passwordManagerExtensionContent";
  const EXTENSION_ID = "@remember_signons";
  let manifest = {
    manifest_version: 2,
    name: "testPasswordManagerExtension",
    version: "1.0",
    description: "Testing rememberSignons",
    browser_specific_settings: { gecko: { id: EXTENSION_ID } },
    permissions: ["privacy"],
    browser_action: {
      default_title: "Testing rememberSignons",
    },
  };

  let passwordManagerEnabledPref = () =>
    Services.prefs.getBoolPref(PASSWORD_MANAGER_ENABLED_PREF);

  await SpecialPowers.pushPrefEnv({
    set: [[PASSWORD_MANAGER_ENABLED_PREF, PASSWORD_MANAGER_ENABLED_DEFAULT]],
  });
  is(
    passwordManagerEnabledPref(),
    true,
    "Password manager is enabled by default."
  );

  function verifyState(isControlled) {
    is(
      passwordManagerEnabledPref(),
      !isControlled,
      "Password manager pref is set to the expected value."
    );
    let controlledLabel =
      gBrowser.contentDocument.getElementById(CONTROLLED_LABEL_ID);
    let controlledButton =
      gBrowser.contentDocument.getElementById(CONTROLLED_BUTTON_ID);
    is(
      controlledLabel.hidden,
      !isControlled,
      "The extension's controlled row visibility is as expected."
    );
    is(
      controlledButton.hidden,
      !isControlled,
      "The extension's controlled button visibility is as expected."
    );
    if (isControlled) {
      let controlledDesc = controlledLabel.querySelector("description");
      Assert.deepEqual(
        gBrowser.contentDocument.l10n.getAttributes(controlledDesc),
        {
          id: "extension-controlling-password-saving",
          args: {
            name: "testPasswordManagerExtension",
          },
        },
        "The user is notified that an extension is controlling the remember signons pref."
      );
    }
  }

  await openPreferencesViaOpenPreferencesAPI("panePrivacy", {
    leaveOpen: true,
  });

  info("Verify that no extension is controlling the password manager pref.");
  verifyState(false);

  let extension = ExtensionTestUtils.loadExtension({
    manifest,
    useAddonManager: "permanent",
    background() {
      browser.privacy.services.passwordSavingEnabled.set({ value: false });
    },
  });
  let messageShown = waitForMessageShown(CONTROLLED_LABEL_ID);
  await extension.startup();
  await messageShown;

  info(
    "Verify that the test extension is controlling the password manager pref."
  );
  verifyState(true);

  info("Verify that the extension shows as controlled when loaded again.");
  BrowserTestUtils.removeTab(gBrowser.selectedTab);
  await openPreferencesViaOpenPreferencesAPI("panePrivacy", {
    leaveOpen: true,
  });
  verifyState(true);

  await disableExtensionViaClick(
    CONTROLLED_LABEL_ID,
    CONTROLLED_BUTTON_ID,
    gBrowser.contentDocument
  );

  info(
    "Verify that disabling the test extension removes the lock on the password manager pref."
  );
  verifyState(false);

  await extension.unload();

  BrowserTestUtils.removeTab(gBrowser.selectedTab);
});

add_task(async function testExtensionControlledProxyConfig() {
  const proxySvc = Ci.nsIProtocolProxyService;
  const PROXY_DEFAULT = proxySvc.PROXYCONFIG_SYSTEM;
  const EXTENSION_ID = "@set_proxy";
  const CONTROLLED_SECTION_ID = "proxyExtensionContent";
  const CONTROLLED_BUTTON_ID = "disableProxyExtension";
  const CONNECTION_SETTINGS_DESC_ID = "connectionSettingsDescription";
  const PANEL_URL =
    "chrome://browser/content/preferences/dialogs/connection.xhtml";

  await SpecialPowers.pushPrefEnv({ set: [[PROXY_PREF, PROXY_DEFAULT]] });

  function background() {
    browser.proxy.settings.set({ value: { proxyType: "none" } });
  }

  function expectedConnectionSettingsMessage(doc, isControlled) {
    return isControlled
      ? "extension-controlling-proxy-config"
      : "network-proxy-connection-description";
  }

  function connectionSettingsMessagePromise(doc, isControlled) {
    return waitForMessageContent(
      CONNECTION_SETTINGS_DESC_ID,
      expectedConnectionSettingsMessage(doc, isControlled),
      doc
    );
  }

  function verifyProxyState(doc, isControlled) {
    let isPanel = doc.getElementById(CONTROLLED_BUTTON_ID);
    is(
      proxyType === proxySvc.PROXYCONFIG_DIRECT,
      isControlled,
      "Proxy pref is set to the expected value."
    );

    if (isPanel) {
      let controlledSection = doc.getElementById(CONTROLLED_SECTION_ID);

      is(
        controlledSection.hidden,
        !isControlled,
        "The extension controlled row's visibility is as expected."
      );
      if (isPanel) {
        is(
          doc.getElementById(CONTROLLED_BUTTON_ID).hidden,
          !isControlled,
          "The disable extension button's visibility is as expected."
        );
      }
      if (isControlled) {
        let controlledDesc = controlledSection.querySelector("description");
        Assert.deepEqual(
          doc.l10n.getAttributes(controlledDesc),
          {
            id: "extension-controlling-proxy-config",
            args: {
              name: "set_proxy",
            },
          },
          "The user is notified that an extension is controlling proxy settings."
        );
      }
      function getProxyControls() {
        let controlGroup = doc.getElementById("networkProxyType");
        let manualControlContainer = controlGroup.querySelector("#proxy-grid");
        return {
          manualControls: [
            ...manualControlContainer.querySelectorAll(
              "label[data-l10n-id]:not([control=networkProxyNone])"
            ),
            ...manualControlContainer.querySelectorAll("input"),
            ...manualControlContainer.querySelectorAll("checkbox"),
            ...doc.querySelectorAll("#networkProxySOCKSVersion > radio"),
          ],
          pacControls: [doc.getElementById("networkProxyAutoconfigURL")],
          otherControls: [
            doc.querySelector("label[control=networkProxyNone]"),
            doc.getElementById("networkProxyNone"),
            ...controlGroup.querySelectorAll(":scope > radio"),
            ...doc.querySelectorAll("#ConnectionsDialogPane > checkbox"),
          ],
        };
      }
      let controlState = isControlled ? "disabled" : "enabled";
      let controls = getProxyControls();
      for (let element of controls.manualControls) {
        let disabled =
          isControlled || proxyType !== proxySvc.PROXYCONFIG_MANUAL;
        is(
          element.disabled,
          disabled,
          `Manual proxy controls should be ${controlState} - control: ${element.outerHTML}.`
        );
      }
      for (let element of controls.pacControls) {
        let disabled = isControlled || proxyType !== proxySvc.PROXYCONFIG_PAC;
        is(
          element.disabled,
          disabled,
          `PAC proxy controls should be ${controlState} - control: ${element.outerHTML}.`
        );
      }
      for (let element of controls.otherControls) {
        is(
          element.disabled,
          isControlled,
          `Other proxy controls should be ${controlState} - control: ${element.outerHTML}.`
        );
      }
    } else {
      let elem = doc.getElementById(CONNECTION_SETTINGS_DESC_ID);
      is(
        doc.l10n.getAttributes(elem).id,
        expectedConnectionSettingsMessage(doc, isControlled),
        "The connection settings description is as expected."
      );
    }
  }

  async function reEnableProxyExtension(addon) {
    let messageChanged = connectionSettingsMessagePromise(mainDoc, true);
    await addon.enable();
    await messageChanged;
  }

  async function openProxyPanel() {
    let panel = await openAndLoadSubDialog(PANEL_URL);
    let closingPromise = BrowserTestUtils.waitForEvent(
      panel.document.getElementById("ConnectionsDialog"),
      "dialogclosing"
    );
    ok(panel, "Proxy panel opened.");
    return { panel, closingPromise };
  }

  async function closeProxyPanel(panelObj) {
    let dialog = panelObj.panel.document.getElementById("ConnectionsDialog");
    dialog.cancelDialog();
    let panelClosingEvent = await panelObj.closingPromise;
    ok(panelClosingEvent, "Proxy panel closed.");
  }

  await openPreferencesViaOpenPreferencesAPI("paneGeneral", {
    leaveOpen: true,
  });
  let mainDoc = gBrowser.contentDocument;

  is(
    gBrowser.currentURI.spec,
    "about:preferences#general",
    "#general should be in the URI for about:preferences"
  );

  verifyProxyState(mainDoc, false);

  // Open the connections panel.
  let panelObj = await openProxyPanel();
  let panelDoc = panelObj.panel.document;

  verifyProxyState(panelDoc, false);

  await closeProxyPanel(panelObj);

  verifyProxyState(mainDoc, false);

  // Install an extension that controls proxy settings. The extension needs
  // incognitoOverride because controlling the proxy.settings requires private
  // browsing access.
  let extension = ExtensionTestUtils.loadExtension({
    incognitoOverride: "spanning",
    useAddonManager: "permanent",
    manifest: {
      name: "set_proxy",
      browser_specific_settings: { gecko: { id: EXTENSION_ID } },
      permissions: ["proxy"],
    },
    background,
  });

  let messageChanged = connectionSettingsMessagePromise(mainDoc, true);
  await extension.startup();
  await messageChanged;
  let addon = await AddonManager.getAddonByID(EXTENSION_ID);

  verifyProxyState(mainDoc, true);
  messageChanged = connectionSettingsMessagePromise(mainDoc, false);

  panelObj = await openProxyPanel();
  panelDoc = panelObj.panel.document;

  verifyProxyState(panelDoc, true);

  await disableExtensionViaClick(
    CONTROLLED_SECTION_ID,
    CONTROLLED_BUTTON_ID,
    panelDoc
  );

  verifyProxyState(panelDoc, false);

  await closeProxyPanel(panelObj);
  await messageChanged;

  verifyProxyState(mainDoc, false);

  await reEnableProxyExtension(addon);

  verifyProxyState(mainDoc, true);
  messageChanged = connectionSettingsMessagePromise(mainDoc, false);

  panelObj = await openProxyPanel();
  panelDoc = panelObj.panel.document;

  verifyProxyState(panelDoc, true);

  await disableExtensionViaClick(
    CONTROLLED_SECTION_ID,
    CONTROLLED_BUTTON_ID,
    panelDoc
  );

  verifyProxyState(panelDoc, false);

  await closeProxyPanel(panelObj);
  await messageChanged;

  verifyProxyState(mainDoc, false);

  // Enable the extension so we get the UNINSTALL event, which is needed by
  // ExtensionPreferencesManager to clean up properly.
  // TODO: BUG 1408226
  await reEnableProxyExtension(addon);

  await extension.unload();

  BrowserTestUtils.removeTab(gBrowser.selectedTab);
});

// Test that the newtab menu selection is correct when loading about:preferences
add_task(async function testMenuSyncFromPrefs() {
  const DEFAULT_NEWTAB = "about:newtab";

  await openPreferencesViaOpenPreferencesAPI("paneHome", { leaveOpen: true });
  is(
    gBrowser.currentURI.spec,
    "about:preferences#home",
    "#home should be in the URI for about:preferences"
  );

  let doc = gBrowser.contentDocument;
  let newTabMenuList = doc.getElementById("newTabMode");
  // The new tab page is set to the default.
  is(AboutNewTab.newTabURL, DEFAULT_NEWTAB, "new tab is set to default");

  is(newTabMenuList.value, "0", "New tab menulist is set to the default");

  newTabMenuList.value = "1";
  newTabMenuList.dispatchEvent(new Event("command"));
  is(newTabMenuList.value, "1", "New tab menulist is set to blank");

  gBrowser.reloadTab(gBrowser.selectedTab);

  await TestUtils.waitForCondition(
    () => gBrowser.contentDocument.getElementById("newTabMode"),
    "wait until element exists in new contentDoc"
  );

  is(
    gBrowser.contentDocument.getElementById("newTabMode").value,
    "1",
    "New tab menulist is still set to blank"
  );

  // Cleanup
  newTabMenuList.value = "0";
  newTabMenuList.dispatchEvent(new Event("command"));
  is(AboutNewTab.newTabURL, DEFAULT_NEWTAB, "new tab is set to default");
  BrowserTestUtils.removeTab(gBrowser.selectedTab);
});