summaryrefslogtreecommitdiffstats
path: root/toolkit/components/passwordmgr/test/browser/browser_context_menu.js
blob: 5f97a913246fcc01b501ae7e9026c6ed30fbf4af (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
/**
 * Test the password manager context menu.
 */

/* eslint no-shadow:"off" */

"use strict";

// The origin for the test URIs.
const TEST_ORIGIN = "https://example.com";
const MULTIPLE_FORMS_PAGE_PATH =
  "/browser/toolkit/components/passwordmgr/test/browser/multiple_forms.html";

const CONTEXT_MENU = document.getElementById("contentAreaContextMenu");
const POPUP_HEADER = document.getElementById("fill-login");

/**
 * Initialize logins needed for the tests and disable autofill
 * for login forms for easier testing of manual fill.
 */
add_task(async function test_initialize() {
  Services.prefs.setBoolPref("signon.autofillForms", false);
  Services.prefs.setBoolPref("signon.usernameOnlyForm.enabled", true);
  registerCleanupFunction(() => {
    Services.prefs.clearUserPref("signon.autofillForms");
    Services.prefs.clearUserPref("signon.schemeUpgrades");
    Services.prefs.clearUserPref("signon.usernameOnlyForm.enabled");
  });
  await Services.logins.addLogins(loginList());
});

/**
 * Check if the context menu is populated with the right
 * menuitems for the target password input field.
 */
add_task(async function test_context_menu_populate_password_noSchemeUpgrades() {
  Services.prefs.setBoolPref("signon.schemeUpgrades", false);
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: TEST_ORIGIN + MULTIPLE_FORMS_PAGE_PATH,
    },
    async function (browser) {
      await openPasswordContextMenu(browser, "#test-password-1");

      // Check the content of the password manager popup
      let popupMenu = document.getElementById("fill-login-popup");
      checkMenu(popupMenu, 2);

      await closePopup(CONTEXT_MENU);
    }
  );
});

/**
 * Check if the context menu is populated with the right
 * menuitems for the target password input field.
 */
add_task(async function test_context_menu_populate_password_schemeUpgrades() {
  Services.prefs.setBoolPref("signon.schemeUpgrades", true);
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: TEST_ORIGIN + MULTIPLE_FORMS_PAGE_PATH,
    },
    async function (browser) {
      await openPasswordContextMenu(browser, "#test-password-1");

      // Check the content of the password manager popup
      let popupMenu = document.getElementById("fill-login-popup");
      checkMenu(popupMenu, 3);

      await closePopup(CONTEXT_MENU);
    }
  );
});

/**
 * Check if the context menu is populated with the right menuitems
 * for the target username field with a password field present.
 */
add_task(
  async function test_context_menu_populate_username_with_password_noSchemeUpgrades() {
    Services.prefs.setBoolPref("signon.schemeUpgrades", false);
    await BrowserTestUtils.withNewTab(
      {
        gBrowser,
        url:
          TEST_ORIGIN +
          "/browser/toolkit/components/" +
          "passwordmgr/test/browser/multiple_forms.html",
      },
      async function (browser) {
        await openPasswordContextMenu(browser, "#test-username-3");

        // Check the content of the password manager popup
        let popupMenu = document.getElementById("fill-login-popup");
        checkMenu(popupMenu, 2);

        await closePopup(CONTEXT_MENU);
      }
    );
  }
);
/**
 * Check if the context menu is populated with the right menuitems
 * for the target username field with a password field present.
 */
add_task(
  async function test_context_menu_populate_username_with_password_schemeUpgrades() {
    Services.prefs.setBoolPref("signon.schemeUpgrades", true);
    await BrowserTestUtils.withNewTab(
      {
        gBrowser,
        url:
          TEST_ORIGIN +
          "/browser/toolkit/components/" +
          "passwordmgr/test/browser/multiple_forms.html",
      },
      async function (browser) {
        await openPasswordContextMenu(browser, "#test-username-3");

        // Check the content of the password manager popup
        let popupMenu = document.getElementById("fill-login-popup");
        checkMenu(popupMenu, 3);

        await closePopup(CONTEXT_MENU);
      }
    );
  }
);

/**
 * Check if the context menu is populated with the right menuitems
 * for the target username field without a password field present.
 */
add_task(
  async function test_context_menu_populate_username_with_password_noSchemeUpgrades() {
    Services.prefs.setBoolPref("signon.schemeUpgrades", false);
    await BrowserTestUtils.withNewTab(
      {
        gBrowser,
        url:
          TEST_ORIGIN +
          "/browser/toolkit/components/" +
          "passwordmgr/test/browser/multiple_forms.html",
      },
      async function (browser) {
        await openPasswordContextMenu(browser, "#test-username-1");

        // Check the content of the password manager popup
        let popupMenu = document.getElementById("fill-login-popup");
        checkMenu(popupMenu, 2);

        await closePopup(CONTEXT_MENU);
      }
    );
  }
);
/**
 * Check if the context menu is populated with the right menuitems
 * for the target username field without a password field present.
 */
add_task(
  async function test_context_menu_populate_username_with_password_schemeUpgrades() {
    Services.prefs.setBoolPref("signon.schemeUpgrades", true);
    await BrowserTestUtils.withNewTab(
      {
        gBrowser,
        url:
          TEST_ORIGIN +
          "/browser/toolkit/components/" +
          "passwordmgr/test/browser/multiple_forms.html",
      },
      async function (browser) {
        await openPasswordContextMenu(browser, "#test-username-1");

        // Check the content of the password manager popup
        let popupMenu = document.getElementById("fill-login-popup");
        checkMenu(popupMenu, 3);

        await closePopup(CONTEXT_MENU);
      }
    );
  }
);

/**
 * Check if the password field is correctly filled when one
 * login menuitem is clicked.
 */
add_task(async function test_context_menu_password_fill() {
  Services.prefs.setBoolPref("signon.schemeUpgrades", true);
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: TEST_ORIGIN + MULTIPLE_FORMS_PAGE_PATH,
    },
    async function (browser) {
      let formDescriptions = await SpecialPowers.spawn(
        browser,
        [],
        async function () {
          let forms = Array.from(
            content.document.getElementsByClassName("test-form")
          );
          return forms.map(f => f.getAttribute("description"));
        }
      );

      for (let description of formDescriptions) {
        info("Testing form: " + description);

        let passwordInputIds = await SpecialPowers.spawn(
          browser,
          [{ description }],
          async function ({ description }) {
            let formElement = content.document.querySelector(
              `[description="${description}"]`
            );
            let passwords = Array.from(
              formElement.querySelectorAll(
                "input[type='password'], input[data-type='password']"
              )
            );
            return passwords.map(p => p.id);
          }
        );

        for (let inputId of passwordInputIds) {
          info("Testing password field: " + inputId);

          // Synthesize a right mouse click over the password input element.
          await openPasswordContextMenu(
            browser,
            "#" + inputId,
            async function () {
              let inputDisabled = await SpecialPowers.spawn(
                browser,
                [{ inputId }],
                async function ({ inputId }) {
                  let input = content.document.getElementById(inputId);
                  return input.disabled || input.readOnly;
                }
              );

              // If the password field is disabled or read-only, we want to see
              // the disabled Fill Password popup header.
              if (inputDisabled) {
                Assert.ok(!POPUP_HEADER.hidden, "Popup menu is not hidden.");
                Assert.ok(POPUP_HEADER.disabled, "Popup menu is disabled.");
                await closePopup(CONTEXT_MENU);
              }
              Assert.equal(
                POPUP_HEADER.getAttribute("data-l10n-id"),
                "main-context-menu-use-saved-password",
                "top-level label is correct"
              );

              return !inputDisabled;
            }
          );

          if (CONTEXT_MENU.state != "open") {
            continue;
          }

          // The only field affected by the password fill
          // should be the target password field itself.
          await assertContextMenuFill(browser, description, null, inputId, 1);
          await SpecialPowers.spawn(
            browser,
            [{ inputId }],
            async function ({ inputId }) {
              let passwordField = content.document.getElementById(inputId);
              Assert.equal(
                passwordField.value,
                "password1",
                "Check upgraded login was actually used"
              );
            }
          );

          await closePopup(CONTEXT_MENU);
        }
      }
    }
  );
});

/**
 * Check if the form is correctly filled when one
 * username context menu login menuitem is clicked.
 */
add_task(async function test_context_menu_username_login_fill() {
  Services.prefs.setBoolPref("signon.schemeUpgrades", true);
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: TEST_ORIGIN + MULTIPLE_FORMS_PAGE_PATH,
    },
    async function (browser) {
      let formDescriptions = await SpecialPowers.spawn(
        browser,
        [],
        async function () {
          let forms = Array.from(
            content.document.getElementsByClassName("test-form")
          );
          return forms.map(f => f.getAttribute("description"));
        }
      );

      for (let description of formDescriptions) {
        info("Testing form: " + description);
        let usernameInputIds = await SpecialPowers.spawn(
          browser,
          [{ description }],
          async function ({ description }) {
            let formElement = content.document.querySelector(
              `[description="${description}"]`
            );
            let inputs = Array.from(
              formElement.querySelectorAll(
                "input[type='text']:not([data-type='password'])"
              )
            );
            return inputs.map(p => p.id);
          }
        );

        for (let inputId of usernameInputIds) {
          info("Testing username field: " + inputId);

          // Synthesize a right mouse click over the username input element.
          await openPasswordContextMenu(
            browser,
            "#" + inputId,
            async function () {
              let headerHidden = POPUP_HEADER.hidden;
              let headerDisabled = POPUP_HEADER.disabled;
              let headerLabelID = POPUP_HEADER.getAttribute("data-l10n-id");

              let data = {
                description,
                inputId,
                headerHidden,
                headerDisabled,
                headerLabelID,
              };
              let shouldContinue = await SpecialPowers.spawn(
                browser,
                [data],
                async function (data) {
                  let {
                    description,
                    inputId,
                    headerHidden,
                    headerDisabled,
                    headerLabelID,
                  } = data;
                  let formElement = content.document.querySelector(
                    `[description="${description}"]`
                  );
                  let usernameField = content.document.getElementById(inputId);
                  // We always want to check if the first password field is filled,
                  // since this is the current behavior from the _fillForm function.
                  let passwordField = formElement.querySelector(
                    "input[type='password'], input[data-type='password']"
                  );

                  // If we don't want to see the actual popup menu,
                  // check if the popup is hidden or disabled.
                  if (
                    !passwordField ||
                    usernameField.disabled ||
                    usernameField.readOnly ||
                    passwordField.disabled ||
                    passwordField.readOnly
                  ) {
                    if (!passwordField) {
                      // Should show popup for a username-only form.
                      if (usernameField.autocomplete == "username") {
                        Assert.ok(!headerHidden, "Popup menu is not hidden.");
                      } else {
                        Assert.ok(headerHidden, "Popup menu is hidden.");
                      }
                    } else {
                      Assert.ok(!headerHidden, "Popup menu is not hidden.");
                      Assert.ok(headerDisabled, "Popup menu is disabled.");
                    }
                    return false;
                  }
                  Assert.equal(
                    headerLabelID,
                    "main-context-menu-use-saved-password",
                    "top-level label is correct"
                  );
                  return true;
                }
              );

              if (!shouldContinue) {
                await closePopup(CONTEXT_MENU);
              }

              return shouldContinue;
            }
          );

          if (CONTEXT_MENU.state != "open") {
            continue;
          }

          let passwordFieldId = await SpecialPowers.spawn(
            browser,
            [{ description }],
            async function ({ description }) {
              let formElement = content.document.querySelector(
                `[description="${description}"]`
              );
              return formElement.querySelector(
                "input[type='password'], input[data-type='password']"
              ).id;
            }
          );

          // We shouldn't change any field that's not the target username field or the first password field
          await assertContextMenuFill(
            browser,
            description,
            inputId,
            passwordFieldId,
            1
          );

          await SpecialPowers.spawn(
            browser,
            [{ passwordFieldId }],
            async function ({ passwordFieldId }) {
              let passwordField =
                content.document.getElementById(passwordFieldId);
              if (!passwordField.hasAttribute("expectedFail")) {
                Assert.equal(
                  passwordField.value,
                  "password1",
                  "Check upgraded login was actually used"
                );
              }
            }
          );

          await closePopup(CONTEXT_MENU);
        }
      }
    }
  );
});

/**
 * Check event telemetry is correctly recorded when opening the saved logins / management UI
 * from the context menu
 */
add_task(async function test_context_menu_open_management() {
  Services.prefs.setBoolPref("signon.schemeUpgrades", false);
  await BrowserTestUtils.withNewTab(
    {
      gBrowser,
      url: TEST_ORIGIN + MULTIPLE_FORMS_PAGE_PATH,
    },
    async function (browser) {
      await openPasswordContextMenu(browser, "#test-password-1");

      let openingFunc = () => gContextMenu.openPasswordManager();
      // wait until the management UI opens
      let passwordManager = await openPasswordManager(openingFunc);
      info("Management UI dialog was opened");

      TelemetryTestUtils.assertEvents(
        [["pwmgr", "open_management", "contextmenu"]],
        { category: "pwmgr", method: "open_management" },
        { clear: true, process: "content" }
      );

      await passwordManager.close();
      await closePopup(CONTEXT_MENU);
    }
  );
});

/**
 * Verify that only the expected form fields are filled.
 */
async function assertContextMenuFill(
  browser,
  formId,
  usernameFieldId,
  passwordFieldId,
  loginIndex
) {
  let popupMenu = document.getElementById("fill-login-popup");
  let unchangedSelector = `[description="${formId}"] input:not(#${passwordFieldId})`;

  if (usernameFieldId) {
    unchangedSelector += `:not(#${usernameFieldId})`;
  }

  await SpecialPowers.spawn(
    browser,
    [{ unchangedSelector }],
    async function ({ unchangedSelector }) {
      let unchangedFields =
        content.document.querySelectorAll(unchangedSelector);

      // Store the value of fields that should remain unchanged.
      if (unchangedFields.length) {
        for (let field of unchangedFields) {
          field.setAttribute("original-value", field.value);
        }
      }
    }
  );

  // Execute the default command of the specified login menuitem found in the context menu.
  let loginItem =
    popupMenu.getElementsByClassName("context-login-item")[loginIndex];

  // Find the used login by it's username (Use only unique usernames in this test).
  let { username, password } = getLoginFromUsername(loginItem.label);

  let data = {
    username,
    password,
    usernameFieldId,
    passwordFieldId,
    formId,
    unchangedSelector,
  };
  let continuePromise = ContentTask.spawn(browser, data, async function (data) {
    let {
      username,
      password,
      usernameFieldId,
      passwordFieldId,
      formId,
      unchangedSelector,
    } = data;
    let form = content.document.querySelector(`[description="${formId}"]`);
    await ContentTaskUtils.waitForEvent(
      form,
      "input",
      "Username input value changed"
    );

    if (usernameFieldId) {
      let usernameField = content.document.getElementById(usernameFieldId);

      // If we have an username field, check if it's correctly filled
      if (usernameField.getAttribute("expectedFail") == null) {
        Assert.equal(
          username,
          usernameField.value,
          "Username filled and correct."
        );
      }
    }

    if (passwordFieldId) {
      let passwordField = content.document.getElementById(passwordFieldId);

      // If we have a password field, check if it's correctly filled
      if (passwordField && passwordField.getAttribute("expectedFail") == null) {
        Assert.equal(
          password,
          passwordField.value,
          "Password filled and correct."
        );
      }
    }

    let unchangedFields = content.document.querySelectorAll(unchangedSelector);

    // Check that all fields that should not change have the same value as before.
    if (unchangedFields.length) {
      Assert.ok(() => {
        for (let field of unchangedFields) {
          if (field.value != field.getAttribute("original-value")) {
            return false;
          }
        }
        return true;
      }, "Other fields were not changed.");
    }
  });

  loginItem.doCommand();

  return continuePromise;
}

/**
 * Check if every login that matches the page origin are available at the context menu.
 * @param {Element} contextMenu
 * @param {Number} expectedCount - Number of logins expected in the context menu. Used to ensure
 *                                  we continue testing something useful.
 */
function checkMenu(contextMenu, expectedCount) {
  let logins = loginList().filter(login => {
    return LoginHelper.isOriginMatching(login.origin, TEST_ORIGIN, {
      schemeUpgrades: Services.prefs.getBoolPref("signon.schemeUpgrades"),
    });
  });
  // Make an array of menuitems for easier comparison.
  let menuitems = [
    ...CONTEXT_MENU.getElementsByClassName("context-login-item"),
  ];
  Assert.equal(
    menuitems.length,
    expectedCount,
    "Expected number of menu items"
  );
  Assert.ok(
    logins.every(l => menuitems.some(m => l.username == m.label)),
    "Every login have an item at the menu."
  );
}

/**
 * Search for a login by it's username.
 *
 * Only unique login/origin combinations should be used at this test.
 */
function getLoginFromUsername(username) {
  return loginList().find(login => login.username == username);
}

/**
 * List of logins used for the test.
 *
 * We should only use unique usernames in this test,
 * because we need to search logins by username. There is one duplicate u+p combo
 * in order to test de-duping in the menu.
 */
function loginList() {
  return [
    LoginTestUtils.testData.formLogin({
      origin: "https://example.com",
      formActionOrigin: "https://example.com",
      username: "username",
      password: "password",
    }),
    // Same as above but HTTP in order to test de-duping.
    LoginTestUtils.testData.formLogin({
      origin: "http://example.com",
      formActionOrigin: "http://example.com",
      username: "username",
      password: "password",
    }),
    LoginTestUtils.testData.formLogin({
      origin: "http://example.com",
      formActionOrigin: "http://example.com",
      username: "username1",
      password: "password1",
    }),
    LoginTestUtils.testData.formLogin({
      origin: "https://example.com",
      formActionOrigin: "https://example.com",
      username: "username2",
      password: "password2",
    }),
    LoginTestUtils.testData.formLogin({
      origin: "http://example.org",
      formActionOrigin: "http://example.org",
      username: "username-cross-origin",
      password: "password-cross-origin",
    }),
  ];
}