summaryrefslogtreecommitdiffstats
path: root/dom/security/test/referrer-policy/browser_referrer_disallow_cross_site_relaxing.js
blob: 84e79af3efb93e8f04365b7678ddac7c800fbf56 (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
/**
 * Bug 1720294 - Testing disallow relaxing default referrer policy for
 *               cross-site requests.
 */

"use strict";

requestLongerTimeout(6);

const TEST_DOMAIN = "https://example.com/";
const TEST_SAME_SITE_DOMAIN = "https://test1.example.com/";
const TEST_SAME_SITE_DOMAIN_HTTP = "http://test1.example.com/";
const TEST_CROSS_SITE_DOMAIN = "https://test1.example.org/";
const TEST_CROSS_SITE_DOMAIN_HTTP = "http://test1.example.org/";

const TEST_PATH = "browser/dom/security/test/referrer-policy/";

const TEST_PAGE = `${TEST_DOMAIN}${TEST_PATH}referrer_page.sjs`;
const TEST_SAME_SITE_PAGE = `${TEST_SAME_SITE_DOMAIN}${TEST_PATH}referrer_page.sjs`;
const TEST_SAME_SITE_PAGE_HTTP = `${TEST_SAME_SITE_DOMAIN_HTTP}${TEST_PATH}referrer_page.sjs`;
const TEST_CROSS_SITE_PAGE = `${TEST_CROSS_SITE_DOMAIN}${TEST_PATH}referrer_page.sjs`;
const TEST_CROSS_SITE_PAGE_HTTP = `${TEST_CROSS_SITE_DOMAIN_HTTP}${TEST_PATH}referrer_page.sjs`;

const REFERRER_FULL = 0;
const REFERRER_ORIGIN = 1;
const REFERRER_NONE = 2;

function getExpectedReferrer(referrer, type) {
  let res;

  switch (type) {
    case REFERRER_FULL:
      res = referrer;
      break;
    case REFERRER_ORIGIN:
      let url = new URL(referrer);
      res = `${url.origin}/`;
      break;
    case REFERRER_NONE:
      res = "";
      break;
    default:
      ok(false, "unknown type");
  }

  return res;
}

async function verifyResultInPage(browser, expected) {
  await SpecialPowers.spawn(browser, [expected], value => {
    is(content.document.referrer, value, "The document.referrer is correct.");

    let result = content.document.getElementById("result");
    is(result.textContent, value, "The referer header is correct");
  });
}

function getExpectedConsoleMessage(expected, isPrefOn, url) {
  let msg;

  if (isPrefOn) {
    msg =
      "Referrer Policy: Ignoring the less restricted referrer policy “" +
      expected +
      "” for the cross-site request: " +
      url;
  } else {
    msg =
      "Referrer Policy: Less restricted policies, including " +
      "‘no-referrer-when-downgrade’, ‘origin-when-cross-origin’ and " +
      "‘unsafe-url’, will be ignored soon for the cross-site request: " +
      url;
  }

  return msg;
}

function createConsoleMessageVerificationPromise(expected, isPrefOn, url) {
  if (!expected) {
    return Promise.resolve();
  }

  return new Promise(resolve => {
    let listener = {
      observe(msg) {
        let message = msg.QueryInterface(Ci.nsIScriptError);

        if (message.category.startsWith("Security")) {
          is(
            message.errorMessage,
            getExpectedConsoleMessage(expected, isPrefOn, url),
            "The console message is correct."
          );
          Services.console.unregisterListener(listener);
          resolve();
        }
      },
    };

    Services.console.registerListener(listener);
  });
}

function verifyNoConsoleMessage() {
  // Verify that there is no referrer policy console message.
  let allMessages = Services.console.getMessageArray();

  for (let msg of allMessages) {
    let message = msg.QueryInterface(Ci.nsIScriptError);
    if (
      message.category.startsWith("Security") &&
      message.errorMessage.startsWith("Referrer Policy:")
    ) {
      ok(false, "There should be no console message for referrer policy.");
    }
  }
}

const TEST_CASES = [
  // Testing that the referrer policy can be overridden with less restricted
  // policy in the same-origin scenario.
  {
    policy: "unsafe-url",
    referrer: TEST_PAGE,
    test_url: TEST_PAGE,
    expect: REFERRER_FULL,
    original: REFERRER_FULL,
  },
  // Testing that the referrer policy can be overridden with less restricted
  // policy in the same-site scenario.
  {
    policy: "unsafe-url",
    referrer: TEST_PAGE,
    test_url: TEST_SAME_SITE_PAGE,
    expect: REFERRER_FULL,
    original: REFERRER_FULL,
  },
  {
    policy: "no-referrer-when-downgrade",
    referrer: TEST_PAGE,
    test_url: TEST_SAME_SITE_PAGE,
    expect: REFERRER_FULL,
    original: REFERRER_FULL,
  },
  {
    policy: "origin-when-cross-origin",
    referrer: TEST_PAGE,
    test_url: TEST_SAME_SITE_PAGE_HTTP,
    expect: REFERRER_ORIGIN,
    original: REFERRER_ORIGIN,
  },
  // Testing that the referrer policy cannot be overridden with less restricted
  // policy in the cross-site scenario.
  {
    policy: "unsafe-url",
    referrer: TEST_PAGE,
    test_url: TEST_CROSS_SITE_PAGE,
    expect: REFERRER_ORIGIN,
    expect_console: "unsafe-url",
    original: REFERRER_FULL,
  },
  {
    policy: "no-referrer-when-downgrade",
    referrer: TEST_PAGE,
    test_url: TEST_CROSS_SITE_PAGE,
    expect: REFERRER_ORIGIN,
    expect_console: "no-referrer-when-downgrade",
    original: REFERRER_FULL,
  },
  {
    policy: "origin-when-cross-origin",
    referrer: TEST_PAGE,
    test_url: TEST_CROSS_SITE_PAGE_HTTP,
    expect: REFERRER_NONE,
    expect_console: "origin-when-cross-origin",
    original: REFERRER_ORIGIN,
  },
  // Testing that the referrer policy can still be overridden with more
  // restricted policy in the cross-site scenario.
  {
    policy: "no-referrer",
    referrer: TEST_PAGE,
    test_url: TEST_CROSS_SITE_PAGE,
    expect: REFERRER_NONE,
    original: REFERRER_NONE,
  },
];

add_setup(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      // Disable mixed content blocking to be able to test downgrade scenario.
      ["security.mixed_content.block_active_content", false],
      // Disable https-first since we are testing http and https referrers
      ["dom.security.https_first", false],
    ],
  });
});

async function runTestIniFrame(gBrowser, enabled, expectNoConsole) {
  await BrowserTestUtils.withNewTab(
    { gBrowser, url: "about:blank" },
    async browser => {
      for (let type of ["meta", "header"]) {
        for (let test of TEST_CASES) {
          info(`Test iframe: ${test.toSource()}`);
          let referrerURL = `${test.referrer}?${type}=${test.policy}`;
          let expected = enabled
            ? getExpectedReferrer(referrerURL, test.expect)
            : getExpectedReferrer(referrerURL, test.original);

          let expected_console = expectNoConsole
            ? undefined
            : test.expect_console;

          Services.console.reset();

          BrowserTestUtils.startLoadingURIString(browser, referrerURL);
          await BrowserTestUtils.browserLoaded(browser, false, referrerURL);

          let iframeURL = test.test_url + "?show";

          let consolePromise = createConsoleMessageVerificationPromise(
            expected_console,
            enabled,
            iframeURL
          );
          // Create an iframe and load the url.
          let bc = await SpecialPowers.spawn(
            browser,
            [iframeURL],
            async url => {
              let iframe = content.document.createElement("iframe");
              let loadPromise = ContentTaskUtils.waitForEvent(iframe, "load");
              iframe.src = url;
              content.document.body.appendChild(iframe);

              await loadPromise;

              return iframe.browsingContext;
            }
          );

          await verifyResultInPage(bc, expected);
          await consolePromise;
          if (!expected_console) {
            verifyNoConsoleMessage();
          }
        }
      }
    }
  );
}

async function runTestForLinkClick(gBrowser, enabled, expectNoConsole) {
  await BrowserTestUtils.withNewTab(
    { gBrowser, url: "about:blank" },
    async browser => {
      for (let type of ["meta", "header"]) {
        for (let test of TEST_CASES) {
          info(`Test link click: ${test.toSource()}`);
          let referrerURL = `${test.referrer}?${type}=${test.policy}`;
          let expected = enabled
            ? getExpectedReferrer(referrerURL, test.expect)
            : getExpectedReferrer(referrerURL, test.original);

          let expected_console = expectNoConsole
            ? undefined
            : test.expect_console;

          Services.console.reset();

          BrowserTestUtils.startLoadingURIString(browser, referrerURL);
          await BrowserTestUtils.browserLoaded(browser, false, referrerURL);

          let linkURL = test.test_url + "?show";

          let consolePromise = createConsoleMessageVerificationPromise(
            expected_console,
            enabled,
            linkURL
          );

          // Create the promise to wait for the navigation finishes.
          let loadedPromise = BrowserTestUtils.browserLoaded(
            browser,
            false,
            linkURL
          );

          // Generate the link and click it to navigate.
          await SpecialPowers.spawn(browser, [linkURL], async url => {
            let link = content.document.createElement("a");
            link.textContent = "Link";
            link.setAttribute("href", url);

            content.document.body.appendChild(link);
            link.click();
          });

          await loadedPromise;

          await verifyResultInPage(browser, expected);
          await consolePromise;
          if (!expected_console) {
            verifyNoConsoleMessage();
          }
        }
      }
    }
  );
}

async function toggleETPForPage(gBrowser, url, toggle) {
  let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, url);

  // First, Toggle ETP off for the test page.
  let browserLoadedPromise = BrowserTestUtils.browserLoaded(
    tab.linkedBrowser,
    false,
    url
  );

  if (toggle) {
    gProtectionsHandler.enableForCurrentPage();
  } else {
    gProtectionsHandler.disableForCurrentPage();
  }

  await browserLoadedPromise;
  BrowserTestUtils.removeTab(tab);
}

add_task(async function test_iframe() {
  for (let enabled of [true, false]) {
    await SpecialPowers.pushPrefEnv({
      set: [["network.http.referer.disallowCrossSiteRelaxingDefault", enabled]],
    });

    await runTestIniFrame(gBrowser, enabled);
  }
});

add_task(async function test_iframe_pbmode() {
  let win = await BrowserTestUtils.openNewBrowserWindow({ private: true });

  for (let enabled of [true, false]) {
    await SpecialPowers.pushPrefEnv({
      set: [
        [
          "network.http.referer.disallowCrossSiteRelaxingDefault.pbmode",
          enabled,
        ],
      ],
    });

    await runTestIniFrame(win.gBrowser, enabled);
  }

  await BrowserTestUtils.closeWindow(win);
});

add_task(async function test_link_click() {
  for (let enabled of [true, false]) {
    for (let enabled_top of [true, false]) {
      await SpecialPowers.pushPrefEnv({
        set: [
          ["network.http.referer.disallowCrossSiteRelaxingDefault", enabled],
          [
            "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation",
            enabled_top,
          ],
        ],
      });

      // We won't show the console message if the strict rule is disabled for
      // the top navigation.
      await runTestForLinkClick(gBrowser, enabled && enabled_top, !enabled_top);
    }
  }
});

add_task(async function test_link_click_pbmode() {
  let win = await BrowserTestUtils.openNewBrowserWindow({ private: true });

  for (let enabled of [true, false]) {
    for (let enabled_top of [true, false]) {
      await SpecialPowers.pushPrefEnv({
        set: [
          [
            "network.http.referer.disallowCrossSiteRelaxingDefault.pbmode",
            enabled,
          ],
          [
            "network.http.referer.disallowCrossSiteRelaxingDefault.pbmode.top_navigation",
            enabled_top,
          ],
          // Disable https first mode for private browsing mode to test downgrade
          // cases.
          ["dom.security.https_first_pbm", false],
        ],
      });

      // We won't show the console message if the strict rule is disabled for
      // the top navigation in the private browsing window.
      await runTestForLinkClick(
        win.gBrowser,
        enabled && enabled_top,
        !enabled_top
      );
    }
  }

  await BrowserTestUtils.closeWindow(win);
});

add_task(async function test_iframe_etp_toggle_off() {
  await SpecialPowers.pushPrefEnv({
    set: [["network.http.referer.disallowCrossSiteRelaxingDefault", true]],
  });

  // Open a new tab for the test page and toggle ETP off.
  await toggleETPForPage(gBrowser, TEST_PAGE, false);

  // Run the test to see if the protection is disabled. We won't send console
  // message if the protection was disabled by the ETP toggle.
  await runTestIniFrame(gBrowser, false, true);

  // toggle ETP on again.
  await toggleETPForPage(gBrowser, TEST_PAGE, true);

  // Run the test again to see if the protection is enabled.
  await runTestIniFrame(gBrowser, true);
});

add_task(async function test_link_click_etp_toggle_off() {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["network.http.referer.disallowCrossSiteRelaxingDefault", true],
      [
        "network.http.referer.disallowCrossSiteRelaxingDefault.top_navigation",
        true,
      ],
    ],
  });

  // Toggle ETP off for the cross site. Note that the cross site is the place
  // where we test against the ETP permission for top navigation.
  await toggleETPForPage(gBrowser, TEST_CROSS_SITE_PAGE, false);

  // Run the test to see if the protection is disabled. We won't send console
  // message if the protection was disabled by the ETP toggle.
  await runTestForLinkClick(gBrowser, false, true);

  // toggle ETP on again.
  await toggleETPForPage(gBrowser, TEST_CROSS_SITE_PAGE, true);

  // Run the test again to see if the protection is enabled.
  await runTestForLinkClick(gBrowser, true);
});