summaryrefslogtreecommitdiffstats
path: root/toolkit/components/passwordmgr/test/mochitest/test_munged_values.html
blob: 5afac7348b8fe26f2e9402b91c8b4f09c14448ff (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
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test handling of possibly-manipulated username values</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="../../../satchel/test/satchel_common.js"></script>
  <script src="pwmgr_common.js"></script>
  <link rel="stylesheet" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script type="application/javascript">
const readyPromise = registerRunTests();

const DEFAULT_ORIGIN = window.location.origin;

function removeAllUserFacingLoginsInParent() {
  runInParent(function removeAllUserFacingLogins() {
    Services.logins.removeAllUserFacingLogins();
  });
}

async function add2logins() {
  removeAllUserFacingLoginsInParent();
  await addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "real••••user", "pass1", "", ""], [DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "user2", "pass2", "", ""]);
}

async function addSingleLogin() {
  removeAllUserFacingLoginsInParent();
  await addLoginsInParent([DEFAULT_ORIGIN, DEFAULT_ORIGIN, null, "real••••user", "pass1", "", ""])
}

/**
 *  For any test including the character "!", generate a version of that test for every known munge
 *  character.
 **/
 function generateTestCases(test) {
  const MUNGE_CHARS = ["*", ".", "•"];

  const nothingToReplace = Object.values(test).every(value => typeof value !== "string" || !value.includes("!"));
  if (nothingToReplace) {
    return test;
  };

  return MUNGE_CHARS.map(char => {
    const newTest = {};
    for (const [propName, val] of Object.entries(test)) {
      if (typeof val === "string") {
        newTest[propName] = val.replace(/!/g, char);
      } else {
        newTest[propName] = val;
      }
  };
  return newTest;
})};

const loadPromise = new Promise(resolve => {
  document.addEventListener("DOMContentLoaded", () => {
    resolve();
  });
});

add_setup(async () => {
  info("Waiting for setup and page and window loads");
  await readyPromise;
  await loadPromise;
});

add_task(async function test_new_logins() {
  const TEST_CASES = [
  // ! is replaced with characters commonly used for munging
  {
    testName: "test_middle!MaskedUsername",
    username: "so!!!ne",
    expected: null,
  },
  {
    testName: "test_start!MaskedUsername",
    username: "!!!eone",
    expected: null,
  },
  {
    testName: "test_end!MaskedUsername",
    username: "some!!!",
    expected: null,
  },
  {
    testName: "test_ok!Username",
    username: "obelixand!",
    expected: "obelixand!",
  },
  {
    testName: "test_ok!Username2",
    username: "!!username!!",
    expected: "!!username!!",
  },
  {
    // We should only consider a username munged if it repeats of the same character
    testName: "test_combinedMungeCharacters",
    username: "*.•*.•*.•*.•*.•*.•",
    expected: "*.•*.•*.•*.•*.•*.•",
  },
].flatMap(generateTestCases);
  for (const tc of TEST_CASES) {
    info("Starting testcase: " + JSON.stringify(tc));
    // Create a new window for each test case, because if we instead try to use
    // the same window and change the page using window.location, that will trigger
    // an onLocationChange event, which can trigger unwanted FormSubmit outside of
    // clicking the submit button in each test document.
    const win = window.open("about:blank");
    const html = `
      <form id="form1" onsubmit="return false;">
        <input  type="text"       name="uname" value="${tc.username}">
        <input  type="password"   name="pword" value="thepassword">
        <button type="submit" id="submitBtn">Submit</button>
      </form>`;
    await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
    await SpecialPowers.spawn(win, [html], function(contentHtml) {
      const doc = this.content.document;
      for (const field of doc.querySelectorAll("input")) {
        const actualValue = field.value;
        field.value = "";
        SpecialPowers.wrap(field).setUserInput(actualValue);
      }
    });
    await SpecialPowers.spawn(win, [tc], function(testcase) {
      const doc = this.content.document;
      Assert.equal(doc.querySelector("[name='uname']").value, testcase.username, "Checking for filled username");
    });

    // Check data sent via PasswordManager:onFormSubmit
    const processedPromise = getSubmitMessage();
    await SpecialPowers.spawn(win, [], function() {
      this.content.document.getElementById("submitBtn").click();
    });

    const { data } = await processedPromise;
    info("Got submitted result: " + JSON.stringify(data));

    if (tc.expected === null) {
      is(data.usernameField, tc.expected, "Check usernameField");
    } else {
      is(data.usernameField.value, tc.expected, "Check usernameField");
    }

    win.close();
    await SimpleTest.promiseFocus(window);
  }
});

add_task(async function test_no_save_dialog_when_password_is_fully_munged() {
  const TEST_CASES = [
  {
      testName: "test_passFullyMungedBy!",
      password: "!!!!!!!!!",
      shouldShowPrompt: false,
    },
    {
      testName: "test_passStartsMungedBy!",
      password: "!!!!!!!butThenAPassword",
      shouldShowPrompt: true,
    },
    {
      testName: "test_passEndsMungedBy!",
      password: "aRealPasswordAndThen!!!!!!!",
      shouldShowPrompt: true,
    },
    {
      testName: "test_passMostlyMungedBy!",
      password: "!!!a!!!!",
      shouldShowPrompt: true,
    },
    {
      testName: "test_combinedMungedCharacters",
      password: "*.•*.•*.•*.•",
      shouldShowPrompt: true,
    },
  ].flatMap(generateTestCases);

  for (const tc of TEST_CASES) {
    info("Starting testcase: " + tc.testName)
    // Create a new window for each test case, because if we instead try to use
    // the same window and change the page using window.location, that will trigger
    // an onLocationChange event, which can trigger unwanted FormSubmit outside of
    // clicking the submit button in each test document.
    const win = window.open("about:blank");
    const html = `
      <form id="form1" onsubmit="return false;">
        <input  type="text"       name="uname" value="username">
        <input  type="password"   name="pword" value="${tc.password}">
        <button type="submit" id="submitBtn">Submit</button>
      </form>`;
    await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
    await SpecialPowers.spawn(win, [html], function(contentHtml) {
      const doc = this.content.document;
      for (const field of doc.querySelectorAll("input")) {
        const actualValue = field.value;
        field.value = "";
        SpecialPowers.wrap(field).setUserInput(actualValue);
      }
    });
    await SpecialPowers.spawn(win, [tc], function(testcase) {
      const doc = this.content.document;
      Assert.equal(doc.querySelector("[name='pword']").value, testcase.password, "Checking for filled password");
    });

    const formSubmitListener = SpecialPowers.spawn(win, [], function() {
      return new Promise(resolve => {
        this.content.windowRoot.addEventListener(
            "PasswordManager:ShowDoorhanger",
            event => {
              info(`PasswordManager:ShowDoorhanger called. Event: ${JSON.stringify(event)}`);
              resolve(event.detail.messageSent);
            }
          );
      });
    });

    await SpecialPowers.spawn(win, [], function() {
      this.content.document.getElementById("submitBtn").click();
    });

    const dialogRequested = await formSubmitListener;

    is(dialogRequested, tc.shouldShowPrompt, "Verify 'show save/update prompt' message sent to parent process");

    win.close();
    await SimpleTest.promiseFocus(window);
  }
});

add_task(async function test_no_autofill_munged_username_matching_password() {
  // run this test with 2 matching logins from this origin so we don't autofill
  await add2logins();
  const allLogins = await LoginManager.getAllLogins();
  const matchingLogins = Array.prototype.filter.call(allLogins, l => l.origin == DEFAULT_ORIGIN);
  is(matchingLogins.length, 2, "Expected number of matching logins");

  const bulletLogin = matchingLogins.find(l => l.username == "real••••user");
  ok(bulletLogin, "Found the real••••user login");

  const timesUsed = bulletLogin.timesUsed;
  const guid = bulletLogin.guid;

  const win = window.open("about:blank");
  const html =
    `<form id="form1" onsubmit="return false;">
      <input  type="text"       name="uname" value="">
      <input  type="password"   name="pword" value="">
      <button type="submit" id="submitBtn">Submit</button>
    </form>`;
  await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
  await SpecialPowers.spawn(win, [html], function(contentHtml) {
    const doc = this.content.document;
    for (const field of doc.querySelectorAll("input")) {
      const actualValue = field.value;
      field.value = "";
      SpecialPowers.wrap(field).setUserInput(actualValue);
    }
  });
  await SpecialPowers.spawn(win, [], function() {
    const doc = this.content.document;
    Assert.equal(doc.querySelector("[name='uname']").value, "", "Check username didn't get autofilled");
    SpecialPowers.wrap(doc.querySelector("[name='uname']")).setUserInput("real••••user");
    SpecialPowers.wrap(doc.querySelector("[name='pword']")).setUserInput("pass1");
  });

  // we shouldn't get the save password doorhanger...
  const popupShownPromise = noPopupBy();

  // Check data sent via PasswordManager:onFormSubmit
  const processedPromise = getSubmitMessage();
  await SpecialPowers.spawn(win, [], function() {
    this.content.document.getElementById("submitBtn").click();
  });

  const { data } = await processedPromise;
  info("Got submitted result: " + JSON.stringify(data));

  is(data.usernameField, null, "Check usernameField");

  const updatedLogins = await LoginManager.getAllLogins();
  const updatedLogin = Array.prototype.find.call(updatedLogins, l => l.guid == guid);
  ok(updatedLogin, "Got the login via guid");
  is(updatedLogin.timesUsed, timesUsed + 1, "timesUsed was incremented");

  await popupShownPromise;

  win.close();
  await SimpleTest.promiseFocus(window);
});


add_task(async function test_autofill_munged_username_matching_password() {
  // only a single matching login so we autofill the username
  await addSingleLogin();

  const allLogins = await LoginManager.getAllLogins();
  const matchingLogins = Array.prototype.filter.call(allLogins, l => l.origin == DEFAULT_ORIGIN);
  is(matchingLogins.length, 1, "Expected number of matching logins");

  info("matched login: " + matchingLogins[0].username);
  const bulletLogin = matchingLogins.find(l => l.username == "real••••user");
  ok(bulletLogin, "Found the real••••user login");

  const timesUsed = bulletLogin.timesUsed;
  const guid = bulletLogin.guid;

  const win = window.open("about:blank");
  const html =
    `<form id="form1" onsubmit="return false;">
      <input  type="text"       name="uname" value="">
      <input  type="password"   name="pword" value="">
      <button type="submit" id="submitBtn">Submit</button>
    </form>`;
  await loadFormIntoWindow(DEFAULT_ORIGIN, html, win);
  await SpecialPowers.spawn(win, [html], function(contentHtml) {
    const doc = this.content.document;
    for (const field of doc.querySelectorAll("input")) {
      const actualValue = field.value;
      field.value = "";
      SpecialPowers.wrap(field).setUserInput(actualValue);
    }
  });
  await SpecialPowers.spawn(win, [], function() {
    const doc = this.content.document;
    Assert.equal(doc.querySelector("[name='uname']").value, "real••••user", "Check username did get autofilled");
    doc.querySelector("[name='pword']").setUserInput("pass1");
  });

  // we shouldn't get the save/update password doorhanger as it didn't change
  const popupShownPromise = noPopupBy();

  // Check data sent via PasswordManager:onFormSubmit
  const processedPromise = getSubmitMessage();
  await SpecialPowers.spawn(win, [], function() {
    this.content.document.getElementById("submitBtn").click();
  });

  const { data } = await processedPromise;
  info("Got submitted result: " + JSON.stringify(data));

  is(data.usernameField, null, "Check usernameField");

  const updatedLogins = await LoginManager.getAllLogins();
  const updatedLogin = Array.prototype.find.call(updatedLogins, l => l.guid == guid);
  ok(updatedLogin, "Got the login via guid");
  is(updatedLogin.timesUsed, timesUsed + 1, "timesUsed was incremented");

  await popupShownPromise;

  win.close();
  await SimpleTest.promiseFocus(window);
});

</script>

<p id="display"></p>

<div id="content">
</div>
<pre id="test"></pre>
</body>
</html>