<!DOCTYPE HTML>
<html>
<head>
  <title>Test for WebRequest urlClassification</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script 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 setup() {
  await SpecialPowers.pushPrefEnv({
    set: [["privacy.trackingprotection.enabled", true]],
  });

  let chromeScript = SpecialPowers.loadChromeScript(async _ => {
    /* eslint-env mozilla/chrome-script */
    const {UrlClassifierTestUtils} = ChromeUtils.import("resource://testing-common/UrlClassifierTestUtils.jsm");
    await UrlClassifierTestUtils.addTestTrackers();
    sendAsyncMessage("trackersLoaded");
  });
  await chromeScript.promiseOneMessage("trackersLoaded");
  chromeScript.destroy();
});

add_task(async function test_urlClassification() {
  await SpecialPowers.pushPrefEnv({
    set: [["dom.security.https_first", false]],
  });
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["webRequest", "webRequestBlocking", "proxy", "<all_urls>"],
    },
    background() {
      let expected = {
        "http://tracking.example.org/": {first: "tracking", thirdParty: false, },
        "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_third_party.html?domain=tracking.example.org": { thirdParty: false, },
        "http://tracking.example.org/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png": {third: "tracking", thirdParty: true, },
        "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_third_party.html?domain=example.net": { thirdParty: false, },
        "http://example.net/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png": { thirdParty: true, },
      };
      function testRequest(details) {
        let expect = expected[details.url];
        if (expect) {
          if (expect.first) {
            browser.test.assertTrue(details.urlClassification.firstParty.includes("tracking"), "tracking firstParty");
          } else {
            browser.test.assertEq(details.urlClassification.firstParty.length, 0, "not tracking firstParty");
          }
          if (expect.third) {
            browser.test.assertTrue(details.urlClassification.thirdParty.includes("tracking"), "tracking thirdParty");
          } else {
            browser.test.assertEq(details.urlClassification.thirdParty.length, 0, "not tracking thirdParty");
          }

          browser.test.assertEq(details.thirdParty, expect.thirdParty, "3rd party flag matches");
          return true;
        }
        return false;
      }

      browser.proxy.onRequest.addListener(details => {
        browser.test.log(`proxy.onRequest ${JSON.stringify(details)}`);
        testRequest(details);
      }, {urls: ["http://mochi.test/tests/*", "http://tracking.example.org/*", "http://example.net/*"]});
      browser.webRequest.onBeforeRequest.addListener(async (details) => {
        browser.test.log(`webRequest.onBeforeRequest ${JSON.stringify(details)}`);
        testRequest(details);
      }, {urls: ["http://mochi.test/tests/*", "http://tracking.example.org/*", "http://example.net/*"]}, ["blocking"]);
      browser.webRequest.onCompleted.addListener(async (details) => {
        browser.test.log(`webRequest.onCompleted ${JSON.stringify(details)}`);
        if (testRequest(details)) {
          browser.test.sendMessage("classification", details.url);
        }
      }, {urls: ["http://mochi.test/tests/*", "http://tracking.example.org/*", "http://example.net/*"]});
    },
  });
  await extension.startup();

  // Test first party tracking classification.
  let url = "http://tracking.example.org/";
  let win = window.open(url);
  is(await extension.awaitMessage("classification"), url, "request completed");
  win.close();

  // Test third party tracking classification, expecting two results.
  url = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_third_party.html?domain=tracking.example.org";
  win = window.open(url);
  is(await extension.awaitMessage("classification"), url);
  is(await extension.awaitMessage("classification"),
     "http://tracking.example.org/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png",
     "request completed");
  win.close();

  // Test third party tracking classification, expecting two results.
  url = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_third_party.html?domain=example.net";
  win = window.open(url);
  is(await extension.awaitMessage("classification"), url);
  is(await extension.awaitMessage("classification"),
     "http://example.net/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png",
     "request completed");
  win.close();

  await extension.unload();
});

add_task(async function teardown() {
  let chromeScript = SpecialPowers.loadChromeScript(async _ => {
    /* eslint-env mozilla/chrome-script */
    // Cleanup cache
    await new Promise(resolve => {
      Services.clearData.deleteData(Ci.nsIClearDataService.CLEAR_ALL, value => resolve());
    });

    const {UrlClassifierTestUtils} = ChromeUtils.import("resource://testing-common/UrlClassifierTestUtils.jsm");
    await UrlClassifierTestUtils.cleanupTestTrackers();
    sendAsyncMessage("trackersUnloaded");
  });
  await chromeScript.promiseOneMessage("trackersUnloaded");
  chromeScript.destroy();
});

</script>

</body>
</html>
