File: test_ext_webrequest_auth.html

package info (click to toggle)
thunderbird 1%3A60.9.0-1~deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,339,424 kB
  • sloc: cpp: 5,457,040; ansic: 2,360,385; python: 596,167; asm: 340,963; java: 326,296; xml: 258,830; sh: 84,445; makefile: 23,701; perl: 17,317; objc: 3,768; yacc: 1,766; ada: 1,681; lex: 1,364; pascal: 1,264; cs: 879; exp: 527; php: 436; lisp: 258; ruby: 153; awk: 152; sed: 53; csh: 27
file content (426 lines) | stat: -rw-r--r-- 16,106 bytes parent folder | download | duplicates (2)
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
<!DOCTYPE HTML>

<html>
<head>
<meta charset="utf-8">
  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
  <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
  <script type="text/javascript" src="head_webrequest.js"></script>
  <script type="text/javascript" src="head.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
<script>
"use strict";

// This file defines content scripts.
/* eslint-env mozilla/frame-script */

let baseUrl = "http://mochi.test:8888/tests/toolkit/components/passwordmgr/test/authenticate.sjs";
function testXHR(url) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = resolve;
    xhr.onabort = reject;
    xhr.onerror = reject;
    xhr.send();
  });
}

function getAuthHandler(result, blocking = true) {
  function background(result) {
    browser.webRequest.onAuthRequired.addListener((details) => {
      browser.test.succeed(`authHandler.onAuthRequired called with ${details.requestId} ${details.url} result ${JSON.stringify(result)}`);
      browser.test.sendMessage("onAuthRequired");
      return result;
    }, {urls: ["*://mochi.test/*"]}, ["blocking"]);
    browser.webRequest.onCompleted.addListener((details) => {
      browser.test.succeed(`authHandler.onCompleted called with ${details.requestId} ${details.url}`);
      browser.test.sendMessage("onCompleted");
    }, {urls: ["*://mochi.test/*"]});
    browser.webRequest.onErrorOccurred.addListener((details) => {
      browser.test.succeed(`authHandler.onErrorOccurred called with ${details.requestId} ${details.url}`);
      browser.test.sendMessage("onErrorOccurred");
    }, {urls: ["*://mochi.test/*"]});
  }

  let permissions = [
    "webRequest",
    "*://mochi.test/*",
  ];
  if (blocking) {
    permissions.push("webRequestBlocking");
  }
  return ExtensionTestUtils.loadExtension({
    manifest: {
      permissions,
    },
    background: `(${background})(${JSON.stringify(result)})`,
  });
}

add_task(async function test_webRequest_auth() {
  // Make use of head_webrequest to ensure event sequence.
  let events = {
    "onBeforeRequest":     [{urls: ["*://mochi.test/*"]}, ["blocking"]],
    "onBeforeSendHeaders": [{urls: ["*://mochi.test/*"]}, ["blocking", "requestHeaders"]],
    "onSendHeaders":       [{urls: ["*://mochi.test/*"]}, ["requestHeaders"]],
    "onBeforeRedirect":    [{urls: ["*://mochi.test/*"]}],
    "onHeadersReceived":   [{urls: ["*://mochi.test/*"]}, ["blocking", "responseHeaders"]],
    "onAuthRequired":      [{urls: ["*://mochi.test/*"]}, ["blocking", "responseHeaders"]],
    "onResponseStarted":   [{urls: ["*://mochi.test/*"]}],
    "onCompleted":         [{urls: ["*://mochi.test/*"]}, ["responseHeaders"]],
    "onErrorOccurred":     [{urls: ["*://mochi.test/*"]}],
  };

  let extension = makeExtension(events);
  await extension.startup();
  let authInfo = {
    username: "testuser",
    password: "testpass",
  };
  let expect = {
    "authenticate.sjs": {
      type: "xmlhttprequest",
      // we expect these additional events after onAuthRequired
      optional_events: ["onBeforeRequest", "onHeadersReceived"],
      authInfo,
    },
  };
  // expecting origin == undefined
  extension.sendMessage("set-expected", {expect, origin: location.href});
  await extension.awaitMessage("continue");

  await testXHR(`${baseUrl}?realm=webRequest_auth&user=${authInfo.username}&pass=${authInfo.password}`);

  await extension.awaitMessage("done");
  await extension.unload();
});

// This test is the same as above, however we shouldn't receive onAuthRequired
// since those credentials are now cached (thus optional_events is not set).
add_task(async function test_webRequest_cached_credentials() {
  // Make use of head_webrequest to ensure event sequence.
  let events = {
    "onBeforeRequest":     [{urls: ["*://mochi.test/*"]}, ["blocking"]],
    "onBeforeSendHeaders": [{urls: ["*://mochi.test/*"]}, ["blocking", "requestHeaders"]],
    "onSendHeaders":       [{urls: ["*://mochi.test/*"]}, ["requestHeaders"]],
    "onBeforeRedirect":    [{urls: ["*://mochi.test/*"]}],
    "onHeadersReceived":   [{urls: ["*://mochi.test/*"]}, ["blocking", "responseHeaders"]],
    "onAuthRequired":      [{urls: ["*://mochi.test/*"]}, ["blocking", "responseHeaders"]],
    "onResponseStarted":   [{urls: ["*://mochi.test/*"]}],
    "onCompleted":         [{urls: ["*://mochi.test/*"]}, ["responseHeaders"]],
    "onErrorOccurred":     [{urls: ["*://mochi.test/*"]}],
  };

  let extension = makeExtension(events);
  await extension.startup();
  let authInfo = {
    username: "testuser",
    password: "testpass",
  };
  let expect = {
    "authenticate.sjs": {
      type: "xmlhttprequest",
      events: ["onBeforeRequest", "onBeforeSendHeaders", "onSendHeaders", "onHeadersReceived", "onResponseStarted", "onCompleted"],
    },
  };
  // expecting origin == undefined
  extension.sendMessage("set-expected", {expect, origin: location.href});
  await extension.awaitMessage("continue");

  await testXHR(`${baseUrl}?realm=webRequest_auth&user=${authInfo.username}&pass=${authInfo.password}`);

  await extension.awaitMessage("done");
  await extension.unload();
});

add_task(async function test_webRequest_cached_credentials2() {
  let authCredentials = {
    username: "testuser",
    password: "testpass",
  };
  let ex1 = getAuthHandler();
  await ex1.startup();

  await testXHR(`${baseUrl}?realm=webRequest_auth&user=${authCredentials.username}&pass=${authCredentials.password}`);

  await ex1.awaitMessage("onCompleted");
  await ex1.unload();
});

add_task(async function test_webRequest_window() {
  let authCredentials = {
    username: "testuser",
    password: "testpass",
  };
  let ex1 = getAuthHandler();
  await ex1.startup();

  let win = window.open(`${baseUrl}?realm=test_webRequest_window&user=${authCredentials.username}&pass=${authCredentials.password}`);

  await ex1.awaitMessage("onCompleted");
  await ex1.unload();
  win.close();
});

add_task(async function test_webRequest_auth_cancelled() {
  let authCredentials = {
    username: "testuser_canceled",
    password: "testpass_canceled",
  };
  let ex1 = getAuthHandler({authCredentials});
  await ex1.startup();
  let ex2 = getAuthHandler({cancel: true});
  await ex2.startup();

  await Assert.rejects(testXHR(`${baseUrl}?realm=test_webRequest_auth_cancelled&user=${authCredentials.username}&pass=${authCredentials.password}`), "caught rejected xhr");

  await Promise.all([
    ex1.awaitMessage("onAuthRequired"),
    ex2.awaitMessage("onAuthRequired"),
    ex1.awaitMessage("onErrorOccurred"),
    ex2.awaitMessage("onErrorOccurred"),
  ]);
  await ex1.unload();
  await ex2.unload();
});

add_task(async function test_webRequest_auth_nonblocking() {
  // The first listener handles the auth request, the second listener
  // is a non-blocking listener and cannot respond but will get the call.
  let authCredentials = {
    username: "foobar",
    password: "testpass",
  };
  let handlingExt = getAuthHandler({authCredentials});
  await handlingExt.startup();
  let extension = getAuthHandler({}, false);
  await extension.startup();

  await testXHR(`${baseUrl}?realm=webRequest_auth_nonblocking&user=${authCredentials.username}&pass=${authCredentials.password}`);

  await Promise.all([
    extension.awaitMessage("onAuthRequired"),
    extension.awaitMessage("onCompleted"),
    handlingExt.awaitMessage("onAuthRequired"),
    handlingExt.awaitMessage("onCompleted"),
  ]);
  await extension.unload();
  await handlingExt.unload();
});


add_task(async function test_webRequest_auth_blocking_noreturn() {
  // The first listener is blocking but doesn't return anything.  The second
  // listener cancels the request.
  let ext = getAuthHandler();
  await ext.startup();
  let canceler = getAuthHandler({cancel: true});
  await canceler.startup();

  await Assert.rejects(testXHR(`${baseUrl}?realm=auth_blocking_noreturn&user=auth_blocking_noreturn&pass=auth_blocking_noreturn`), "caught rejected xhr");

  await Promise.all([
    ext.awaitMessage("onAuthRequired"),
    ext.awaitMessage("onErrorOccurred"),
    canceler.awaitMessage("onAuthRequired"),
    canceler.awaitMessage("onErrorOccurred"),
  ]);
  await ext.unload();
  await canceler.unload();
});

add_task(async function test_webRequest_auth_nonblocking_forwardAuthProvider() {
  // The chrome script sets up a default auth handler on the channel, the
  // extension does not return anything in the authRequred call.  We should
  // get the call in the extension first, then in the chrome code where we
  // cancel the request to avoid dealing with the prompt dialog here.  The test
  // is to ensure that WebRequest calls the previous notificationCallbacks
  // if the authorization is not handled by the onAuthRequired handler.

  let chromeScript = SpecialPowers.loadChromeScript(() => {
    ChromeUtils.import("resource://gre/modules/Services.jsm");
    ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");

    let observer = channel => {
      if (!(channel instanceof Ci.nsIHttpChannel && channel.URI.host === "mochi.test")) {
        return;
      }
      Services.obs.removeObserver(observer, "http-on-modify-request");
      channel.notificationCallbacks = {
        QueryInterface: XPCOMUtils.generateQI([Ci.nsIInterfaceRequestor,
                                               Ci.nsIAuthPromptProvider,
                                               Ci.nsIAuthPrompt2]),
        getInterface: XPCOMUtils.generateQI([Ci.nsIAuthPromptProvider,
                                             Ci.nsIAuthPrompt2]),
        promptAuth(channel, level, authInfo) {
          throw Cr.NS_ERROR_NO_INTERFACE;
        },
        getAuthPrompt(reason, iid) {
          return this;
        },
        asyncPromptAuth(channel, callback, context, level, authInfo) {
          // We just cancel here, we're only ensuring that non-webrequest
          // notificationcallbacks get called if webrequest doesn't handle it.
          Promise.resolve().then(() => {
            callback.onAuthCancelled(context, false);
            channel.cancel(Cr.NS_BINDING_ABORTED);
            sendAsyncMessage("callback-complete");
          });
        },
      };
    };
    Services.obs.addObserver(observer, "http-on-modify-request");
    sendAsyncMessage("chrome-ready");
  });
  await chromeScript.promiseOneMessage("chrome-ready");
  let callbackComplete = chromeScript.promiseOneMessage("callback-complete");

  let handlingExt = getAuthHandler();
  await handlingExt.startup();

  await Assert.rejects(testXHR(`${baseUrl}?realm=auth_nonblocking_forwardAuth&user=auth_nonblocking_forwardAuth&pass=auth_nonblocking_forwardAuth`), "caught rejected xhr");

  await callbackComplete;
  await handlingExt.awaitMessage("onAuthRequired");
  // We expect onErrorOccurred because the "default" authprompt above cancelled
  // the auth request to avoid a dialog.
  await handlingExt.awaitMessage("onErrorOccurred");
  await handlingExt.unload();
  chromeScript.destroy();
});

add_task(async function test_webRequest_auth_nonblocking_forwardAuthPrompt2() {
  // The chrome script sets up a default auth handler on the channel, the
  // extension does not return anything in the authRequred call.  We should
  // get the call in the extension first, then in the chrome code where we
  // cancel the request to avoid dealing with the prompt dialog here.  The test
  // is to ensure that WebRequest calls the previous notificationCallbacks
  // if the authorization is not handled by the onAuthRequired handler.

  let chromeScript = SpecialPowers.loadChromeScript(() => {
    ChromeUtils.import("resource://gre/modules/Services.jsm");
    ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");

    let observer = channel => {
      if (!(channel instanceof Ci.nsIHttpChannel && channel.URI.host === "mochi.test")) {
        return;
      }
      Services.obs.removeObserver(observer, "http-on-modify-request");
      channel.notificationCallbacks = {
        QueryInterface: XPCOMUtils.generateQI([Ci.nsIInterfaceRequestor,
                                               Ci.nsIAuthPrompt2]),
        getInterface: XPCOMUtils.generateQI([Ci.nsIAuthPrompt2]),
        promptAuth(channel, level, authInfo) {
          throw Cr.NS_ERROR_NO_INTERFACE;
        },
        asyncPromptAuth(channel, callback, context, level, authInfo) {
          // We just cancel here, we're only ensuring that non-webrequest
          // notificationcallbacks get called if webrequest doesn't handle it.
          Promise.resolve().then(() => {
            channel.cancel(Cr.NS_BINDING_ABORTED);
            sendAsyncMessage("callback-complete");
          });
        },
      };
    };
    Services.obs.addObserver(observer, "http-on-modify-request");
    sendAsyncMessage("chrome-ready");
  });
  await chromeScript.promiseOneMessage("chrome-ready");
  let callbackComplete = chromeScript.promiseOneMessage("callback-complete");

  let handlingExt = getAuthHandler();
  await handlingExt.startup();

  await Assert.rejects(testXHR(`${baseUrl}?realm=auth_nonblocking_forwardAuthPromptProvider&user=auth_nonblocking_forwardAuth&pass=auth_nonblocking_forwardAuth`), "caught rejected xhr");

  await callbackComplete;
  await handlingExt.awaitMessage("onAuthRequired");
  // We expect onErrorOccurred because the "default" authprompt above cancelled
  // the auth request to avoid a dialog.
  await handlingExt.awaitMessage("onErrorOccurred");
  await handlingExt.unload();
  chromeScript.destroy();
});

add_task(async function test_webRequest_duelingAuth() {
  let exNone = getAuthHandler();
  await exNone.startup();
  let authCredentials = {
    username: "testuser_da1",
    password: "testpass_da1",
  };
  let ex1 = getAuthHandler({authCredentials});
  await ex1.startup();
  let exEmpty = getAuthHandler({});
  await exEmpty.startup();
  let ex2 = getAuthHandler({authCredentials: {
    username: "testuser_da2",
    password: "testpass_da2",
  }});
  await ex2.startup();

  // XHR should succeed since the first credentials win, and they are correct.
  await testXHR(`${baseUrl}?realm=test_webRequest_duelingAuth&user=${authCredentials.username}&pass=${authCredentials.password}`);

  await Promise.all([
    exNone.awaitMessage("onAuthRequired"),
    exNone.awaitMessage("onCompleted"),
    exEmpty.awaitMessage("onAuthRequired"),
    exEmpty.awaitMessage("onCompleted"),
    ex1.awaitMessage("onAuthRequired"),
    ex1.awaitMessage("onCompleted"),
    ex2.awaitMessage("onAuthRequired"),
    ex2.awaitMessage("onCompleted"),
  ]);
  await Promise.all([
    exNone.unload(),
    exEmpty.unload(),
    ex1.unload(),
    ex2.unload(),
  ]);
});

add_task(async function test_webRequest_auth_proxy() {
  function background() {
    let proxyOk = false;
    browser.webRequest.onAuthRequired.addListener((details) => {
      browser.test.succeed(`handlingExt onAuthRequired called with ${details.requestId} ${details.url}`);
      if (details.isProxy) {
        browser.test.succeed("providing proxy authorization");
        proxyOk = true;
        return {authCredentials: {username: "puser", password: "ppass"}};
      }
      browser.test.assertTrue(proxyOk, "providing www authorization after proxy auth");
      browser.test.sendMessage("done");
      return {authCredentials: {username: "auser", password: "apass"}};
    }, {urls: ["*://mochi.test/*"]}, ["blocking"]);
  }

  let handlingExt = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: [
        "webRequest",
        "webRequestBlocking",
        "*://mochi.test/*",
      ],
    },
    background,
  });

  await handlingExt.startup();

  await testXHR(`${baseUrl}?realm=auth_proxy&user=auser&pass=apass&proxy_user=puser&proxy_pass=ppass`);

  await handlingExt.awaitMessage("done");
  await handlingExt.unload();
});
</script>
</head>
<body>
<div id="test">Authorization Test</div>

</body>
</html>