summaryrefslogtreecommitdiffstats
path: root/devtools/shared/network-observer/test/browser/browser_networkobserver_auth_listener.js
blob: e3492c10ad3b30fdcc7efba8bbcd55d13beb09c0 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

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

const TEST_URL = URL_ROOT + "doc_network-observer.html";
const AUTH_URL = URL_ROOT + `sjs_network-auth-listener-test-server.sjs`;

// Correct credentials for sjs_network-auth-listener-test-server.sjs.
const USERNAME = "guest";
const PASSWORD = "guest";
const BAD_PASSWORD = "bad";

// NetworkEventOwner which will cancel all auth prompt requests.
class AuthCancellingOwner extends NetworkEventOwner {
  hasAuthPrompt = false;

  onAuthPrompt(authDetails, authCallbacks) {
    this.hasAuthPrompt = true;
    authCallbacks.cancelAuthPrompt();
  }
}

// NetworkEventOwner which will forward all auth prompt requests to the browser.
class AuthForwardingOwner extends NetworkEventOwner {
  hasAuthPrompt = false;

  onAuthPrompt(authDetails, authCallbacks) {
    this.hasAuthPrompt = true;
    authCallbacks.forwardAuthPrompt();
  }
}

// NetworkEventOwner which will answer provided credentials to auth prompts.
class AuthCredentialsProvidingOwner extends NetworkEventOwner {
  hasAuthPrompt = false;

  constructor(channel, username, password) {
    super();

    this.channel = channel;
    this.username = username;
    this.password = password;
  }

  async onAuthPrompt(authDetails, authCallbacks) {
    this.hasAuthPrompt = true;

    // Providing credentials immediately can lead to intermittent failures.
    // TODO: Investigate and remove.
    // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
    await new Promise(r => setTimeout(r, 100));

    await authCallbacks.provideAuthCredentials(this.username, this.password);
  }

  addResponseContent(content) {
    super.addResponseContent();
    this.responseContent = content.text;
  }
}

add_task(async function testAuthRequestWithoutListener() {
  cleanupAuthManager();
  const tab = await addTab(TEST_URL);

  const events = [];
  const networkObserver = new NetworkObserver({
    ignoreChannelFunction: channel => channel.URI.spec !== AUTH_URL,
    onNetworkEvent: event => {
      const owner = new AuthForwardingOwner();
      events.push(owner);
      return owner;
    },
  });
  registerCleanupFunction(() => networkObserver.destroy());

  const onAuthPrompt = waitForAuthPrompt(tab);

  await SpecialPowers.spawn(gBrowser.selectedBrowser, [AUTH_URL], _url => {
    content.wrappedJSObject.fetch(_url);
  });

  info("Wait for a network event to be created");
  await BrowserTestUtils.waitForCondition(() => events.length >= 1);
  is(events.length, 1, "Received the expected number of network events");

  info("Wait for the auth prompt to be displayed");
  await onAuthPrompt;
  Assert.equal(
    getTabAuthPrompts(tab).length,
    1,
    "The auth prompt was not blocked by the network observer"
  );

  // The event owner should have been called for ResponseStart and EventTimings
  assertEventOwner(events[0], {
    hasResponseStart: true,
    hasEventTimings: true,
    hasServerTimings: true,
  });

  networkObserver.destroy();
  gBrowser.removeTab(tab);
});

add_task(async function testAuthRequestWithForwardingListener() {
  cleanupAuthManager();
  const tab = await addTab(TEST_URL);

  const events = [];
  const networkObserver = new NetworkObserver({
    ignoreChannelFunction: channel => channel.URI.spec !== AUTH_URL,
    onNetworkEvent: event => {
      info("waitForNetworkEvents received a new event");
      const owner = new AuthForwardingOwner();
      events.push(owner);
      return owner;
    },
  });
  registerCleanupFunction(() => networkObserver.destroy());

  info("Enable the auth prompt listener for this network observer");
  networkObserver.setAuthPromptListenerEnabled(true);

  const onAuthPrompt = waitForAuthPrompt(tab);

  await SpecialPowers.spawn(gBrowser.selectedBrowser, [AUTH_URL], _url => {
    content.wrappedJSObject.fetch(_url);
  });

  info("Wait for a network event to be received");
  await BrowserTestUtils.waitForCondition(() => events.length >= 1);
  is(events.length, 1, "Received the expected number of network events");

  // The auth prompt should still be displayed since the network event owner
  // forwards the auth notification immediately.
  info("Wait for the auth prompt to be displayed");
  await onAuthPrompt;
  Assert.equal(
    getTabAuthPrompts(tab).length,
    1,
    "The auth prompt was not blocked by the network observer"
  );

  // The event owner should have been called for ResponseStart, EventTimings and
  // AuthPrompt
  assertEventOwner(events[0], {
    hasResponseStart: true,
    hasEventTimings: true,
    hasAuthPrompt: true,
    hasServerTimings: true,
  });

  networkObserver.destroy();
  gBrowser.removeTab(tab);
});

add_task(async function testAuthRequestWithCancellingListener() {
  cleanupAuthManager();
  const tab = await addTab(TEST_URL);

  const events = [];
  const networkObserver = new NetworkObserver({
    ignoreChannelFunction: channel => channel.URI.spec !== AUTH_URL,
    onNetworkEvent: event => {
      const owner = new AuthCancellingOwner();
      events.push(owner);
      return owner;
    },
  });
  registerCleanupFunction(() => networkObserver.destroy());

  info("Enable the auth prompt listener for this network observer");
  networkObserver.setAuthPromptListenerEnabled(true);

  await SpecialPowers.spawn(gBrowser.selectedBrowser, [AUTH_URL], _url => {
    content.wrappedJSObject.fetch(_url);
  });

  info("Wait for a network event to be received");
  await BrowserTestUtils.waitForCondition(() => events.length >= 1);
  is(events.length, 1, "Received the expected number of network events");

  await BrowserTestUtils.waitForCondition(
    () => events[0].hasResponseContent && events[0].hasSecurityInfo
  );

  // The auth prompt should not be displayed since the authentication was
  // cancelled.
  ok(
    !getTabAuthPrompts(tab).length,
    "The auth prompt was cancelled by the network event owner"
  );

  assertEventOwner(events[0], {
    hasResponseStart: true,
    hasResponseContent: true,
    hasEventTimings: true,
    hasServerTimings: true,
    hasAuthPrompt: true,
    hasSecurityInfo: true,
  });

  networkObserver.destroy();
  gBrowser.removeTab(tab);
});

add_task(async function testAuthRequestWithWrongCredentialsListener() {
  cleanupAuthManager();
  const tab = await addTab(TEST_URL);

  const events = [];
  const networkObserver = new NetworkObserver({
    ignoreChannelFunction: channel => channel.URI.spec !== AUTH_URL,
    onNetworkEvent: (event, channel) => {
      const owner = new AuthCredentialsProvidingOwner(
        channel,
        USERNAME,
        BAD_PASSWORD
      );
      events.push(owner);
      return owner;
    },
  });
  registerCleanupFunction(() => networkObserver.destroy());

  info("Enable the auth prompt listener for this network observer");
  networkObserver.setAuthPromptListenerEnabled(true);

  await SpecialPowers.spawn(gBrowser.selectedBrowser, [AUTH_URL], _url => {
    content.wrappedJSObject.fetch(_url);
  });

  info("Wait for all network events to be received");
  await BrowserTestUtils.waitForCondition(() => events.length >= 1);
  is(events.length, 1, "Received the expected number of network events");

  // Wait for authPrompt to be handled
  await BrowserTestUtils.waitForCondition(() => events[0].hasAuthPrompt);

  // The auth prompt should not be displayed since the authentication was
  // fulfilled.
  ok(
    !getTabAuthPrompts(tab).length,
    "The auth prompt was handled by the network event owner"
  );

  assertEventOwner(events[0], {
    hasAuthPrompt: true,
    hasResponseStart: true,
    hasEventTimings: true,
    hasServerTimings: true,
  });

  networkObserver.destroy();
  gBrowser.removeTab(tab);
});

add_task(async function testAuthRequestWithCredentialsListener() {
  cleanupAuthManager();
  const tab = await addTab(TEST_URL);

  const events = [];
  const networkObserver = new NetworkObserver({
    ignoreChannelFunction: channel => channel.URI.spec !== AUTH_URL,
    onNetworkEvent: (event, channel) => {
      const owner = new AuthCredentialsProvidingOwner(
        channel,
        USERNAME,
        PASSWORD
      );
      events.push(owner);
      return owner;
    },
  });
  registerCleanupFunction(() => networkObserver.destroy());

  info("Enable the auth prompt listener for this network observer");
  networkObserver.setAuthPromptListenerEnabled(true);

  await SpecialPowers.spawn(gBrowser.selectedBrowser, [AUTH_URL], _url => {
    content.wrappedJSObject.fetch(_url);
  });

  // TODO: At the moment, providing credentials will result in additional
  // network events collected by the NetworkObserver, whereas we would expect
  // to keep the same event.
  // For successful auth prompts, we receive an additional event.
  // The last event will contain the responseContent flag.
  info("Wait for all network events to be received");
  await BrowserTestUtils.waitForCondition(() => events.length >= 2);
  is(events.length, 2, "Received the expected number of network events");

  // Since the auth prompt was canceled we should also receive the security
  // information and the response content.
  await BrowserTestUtils.waitForCondition(
    () => events[1].hasResponseContent && events[1].hasSecurityInfo
  );

  // The auth prompt should not be displayed since the authentication was
  // fulfilled.
  ok(
    !getTabAuthPrompts(tab).length,
    "The auth prompt was handled by the network event owner"
  );

  assertEventOwner(events[1], {
    hasResponseStart: true,
    hasEventTimings: true,
    hasSecurityInfo: true,
    hasServerTimings: true,
    hasResponseContent: true,
  });

  is(events[1].responseContent, "success", "Auth prompt was successful");

  networkObserver.destroy();
  gBrowser.removeTab(tab);
});

function assertEventOwner(event, expectedFlags) {
  is(
    event.hasResponseStart,
    !!expectedFlags.hasResponseStart,
    "network event has the expected ResponseStart flag"
  );
  is(
    event.hasEventTimings,
    !!expectedFlags.hasEventTimings,
    "network event has the expected EventTimings flag"
  );
  is(
    event.hasAuthPrompt,
    !!expectedFlags.hasAuthPrompt,
    "network event has the expected AuthPrompt flag"
  );
  is(
    event.hasResponseCache,
    !!expectedFlags.hasResponseCache,
    "network event has the expected ResponseCache flag"
  );
  is(
    event.hasResponseContent,
    !!expectedFlags.hasResponseContent,
    "network event has the expected ResponseContent flag"
  );
  is(
    event.hasSecurityInfo,
    !!expectedFlags.hasSecurityInfo,
    "network event has the expected SecurityInfo flag"
  );
  is(
    event.hasServerTimings,
    !!expectedFlags.hasServerTimings,
    "network event has the expected ServerTimings flag"
  );
}

function getTabAuthPrompts(tab) {
  const tabDialogBox = gBrowser.getTabDialogBox(tab.linkedBrowser);
  return tabDialogBox
    .getTabDialogManager()
    ._dialogs.filter(
      d => d.frameContentWindow?.Dialog.args.promptType == "promptUserAndPass"
    );
}

function waitForAuthPrompt(tab) {
  return PromptTestUtils.waitForPrompt(tab.linkedBrowser, {
    modalType: Services.prompt.MODAL_TYPE_TAB,
    promptType: "promptUserAndPass",
  });
}

// Cleanup potentially stored credentials before running any test.
function cleanupAuthManager() {
  const authManager = SpecialPowers.Cc[
    "@mozilla.org/network/http-auth-manager;1"
  ].getService(SpecialPowers.Ci.nsIHttpAuthManager);
  authManager.clearAll();
}