toolkit/components/extensions/test/mochitest/test_ext_webrequestblocking_set_cookie.html
author Peter Snyder <psnyde2@uic.edu>
Tue, 28 Nov 2017 18:00:42 -0600
changeset 704796 2f311f84c5c8b5d265dfc39156573c4d7b60b67e
parent 704775 8aff48ba6e7d3703c858d6d98cc6e7403c20ee98
permissions -rw-r--r--
Bug 1377689 - add test for replacing request set cookie with an extension set cookie, r=mixedpuppy MozReview-Commit-ID: 1UV6JO8GOTC

<!DOCTYPE HTML>
<html>
<head>
  <title>Testing modifying cookies in webRequest.onHeadersReceived</title>
  <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.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>

<script type="text/javascript">
"use strict";

add_task(async function test_modifying_cookies_from_onHeadersReceived() {
  let extension;

  async function background() {
    /**
     * Check that all the cookies described by `prefixes` are in the cookie jar.
     */
    async function checkCookies(...prefixes) {
      let numPrefixes = prefixes.length;
      let currentCookies = await browser.cookies.getAll({});
      browser.test.assertEq(numPrefixes, currentCookies.length, `${numPrefixes} cookies were set`);

      for (let cookiePrefix of prefixes) {
        let cookieName = `${cookiePrefix}cookie`;
        let expectedCookieValue = `${cookiePrefix}value`;
        let fetchedCookie = await browser.cookies.getAll({name: cookieName});
        browser.test.assertEq(1, fetchedCookie.length, `Found 1 cookie with name "${cookieName}"`);
        browser.test.assertEq(expectedCookieValue, fetchedCookie[0] && fetchedCookie[0].value, `Cookie "${cookieName}" has expected value of "${expectedCookieValue}"`);
      }
    }

    async function openWindowAndTab(filename) {
      const fileUrl = `http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/${filename}?nocache=${Math.random()}`;
      const tabReadyPromise = new Promise(resolve => {
        browser.webNavigation.onDOMContentLoaded.addListener(function listener({tabId}) {
          browser.webNavigation.onDOMContentLoaded.removeListener(listener);
          resolve(tabId);
        }, {
          url: [{
            urlPrefix: fileUrl,
          }],
        });
      });
      const {id: windowId} = await browser.windows.create({url: fileUrl});
      const tabId = await tabReadyPromise;
      return {windowId, tabId};
    }

    const requestFilter = {
      urls: ["<all_urls>"],
      types: ["main_frame", "sub_frame"],
    };

    const extraInfoSpec = ["blocking", "responseHeaders"];

    const onHeadersReceived = details => {
      details.responseHeaders.push({
        name: "Set-Cookie",
        value: "extcookie=extvalue",
      });

      return {
        responseHeaders: details.responseHeaders,
      };
    };
    browser.webRequest.onHeadersReceived.addListener(onHeadersReceived, requestFilter, extraInfoSpec);

    if (browser.windows) {
      // First, perform a request that should not set any cookies, and check
      // that the cookie the extension sets is the only cookie in the
      // cookie jar.
      await browser.browsingData.removeCookies({});
      const tabDetails = await openWindowAndTab("file_sample.html");
      await checkCookies("ext");
      await browser.windows.remove(tabDetails.windowId);

      // Next, preform a request that will set on cookie (reqcookie=reqvalue)
      // and check that two cookies wind up in the cookie jar (the request
      // set cookie, and the extension set cookie).
      await browser.browsingData.removeCookies({});
      const cookieSettingTabDetails = await openWindowAndTab("file_webrequestblocking_set_cookie.html");
      await checkCookies("ext", "req");
      await browser.windows.remove(cookieSettingTabDetails.windowId);

      // Third, register another onHeadersReceived handler that also
      // sets a cookie (thirdcookie=thirdvalue), to make sure modifications from
      // multiple onHeadersReceived listeners are merged correctly.
      const secondOnHeadersRecievedListiner = details => {
        details.responseHeaders.push({
          name: "Set-Cookie",
          value: "thirdcookie=thirdvalue",
        });

        return {
          responseHeaders: details.responseHeaders,
        };
      };
      browser.webRequest.onHeadersReceived.addListener(secondOnHeadersRecievedListiner, requestFilter, extraInfoSpec);

      await browser.browsingData.removeCookies({});
      const secondCookieSettingTabDetails = await openWindowAndTab("file_webrequestblocking_set_cookie.html");
      await checkCookies("ext", "req", "third");
      await browser.windows.remove(secondCookieSettingTabDetails.windowId);

      // Fourth, test to make sure that extensions can remove cookies
      // using onHeadersReceived too, by 1. making a request that
      // sets a cookie (reqcookie=reqvalue), 2. having the extension remove
      // that cookie by removing that header, and 3. adding a new cookie
      // (extcookie=extvalue).
      browser.webRequest.onHeadersReceived.removeListener(onHeadersReceived);
      browser.webRequest.onHeadersReceived.removeListener(secondOnHeadersRecievedListiner);

      const thirdOnHeadersRecievedListiner = details => {
        // Remove the cookie set by the request (reqcookie=reqvalue).
        const newHeaders = details.responseHeaders.filter(cookie => cookie.name !== "set-cookie");

        // And then add a new cookie in its place (extcookie=extvalue).
        newHeaders.push({
          name: "Set-Cookie",
          value: "extcookie=extvalue",
        });

        return {
          responseHeaders: newHeaders,
        };
      };
      browser.webRequest.onHeadersReceived.addListener(thirdOnHeadersRecievedListiner, requestFilter, extraInfoSpec);

      await browser.browsingData.removeCookies({});
      const thirdCookieSettingTabDetails = await openWindowAndTab("file_webrequestblocking_set_cookie.html");
      await checkCookies("ext");
      await browser.windows.remove(thirdCookieSettingTabDetails.windowId);
    }

    browser.test.notifyPass("cookie modifying extension");
  }

  extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: [
        "browsingData",
        "cookies",
        "webNavigation",
        "webRequest",
        "webRequestBlocking",
        "<all_urls>",
      ],
    },
    background,
  });

  await extension.startup();
  await extension.awaitFinish("cookie modifying extension");
  await extension.unload();
});

</script>
</body>
</html>