Bug 1525245 - Stabilize cookiePolicy/cookiePermission for live documents - part 14 - Test for cookies policy, r=Ehsan
authorAndrea Marchesini <amarchesini@mozilla.com>
Fri, 08 Mar 2019 09:04:57 +0000
changeset 523991 f7a3740e9d8e7315afadd6d938ab68218c30bf5e
parent 523990 9111c85dd89095d27a4f87e65156c07f6e76685d
child 523992 dd197c3722a035ec5788997590c91cd53b2eacad
push id2032
push userffxbld-merge
push dateMon, 13 May 2019 09:36:57 +0000
treeherdermozilla-release@455c1065dcbe [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersEhsan
bugs1525245
milestone67.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1525245 - Stabilize cookiePolicy/cookiePermission for live documents - part 14 - Test for cookies policy, r=Ehsan Differential Revision: https://phabricator.services.mozilla.com/D21697
browser/components/enterprisepolicies/tests/browser/browser_policy_cookie_settings.js
dom/xhr/tests/mochitest.ini
dom/xhr/tests/test_worker_xhr_3rdparty.html
dom/xhr/tests/window_worker_xhr_3rdparty.html
extensions/cookie/test/unit/test_cookies_privatebrowsing.js
extensions/cookie/test/unit/test_cookies_thirdparty_nonsecure_session.js
extensions/cookie/test/unit/test_cookies_thirdparty_session.js
netwerk/cookie/moz.build
netwerk/cookie/test/browser/browser.ini
netwerk/cookie/test/browser/browser_cookies.js
netwerk/cookie/test/browser/head.js
netwerk/cookie/test/browser/server.sjs
netwerk/cookie/test/mochitest/.eslintrc.js
netwerk/cookie/test/mochitest/cookie.sjs
netwerk/cookie/test/mochitest/cookiesHelper.js
netwerk/cookie/test/mochitest/mochitest.ini
netwerk/cookie/test/mochitest/test_document_cookie.html
netwerk/cookie/test/mochitest/test_fetch.html
netwerk/cookie/test/mochitest/test_image.html
netwerk/cookie/test/mochitest/test_script.html
netwerk/cookie/test/mochitest/test_sharedWorker.html
netwerk/cookie/test/mochitest/test_worker.html
netwerk/cookie/test/mochitest/test_xhr.html
netwerk/test/TestCookie.cpp
netwerk/test/unit/test_bug248970_cookie.js
netwerk/test/unit/test_bug528292.js
netwerk/test/unit/test_bug659569.js
netwerk/test/unit/test_cookie_header.js
netwerk/test/unit/test_cookiejars.js
netwerk/test/unit/test_cookiejars_safebrowsing.js
netwerk/test/unit/test_private_cookie_changed.js
netwerk/test/unit_ipc/test_bug528292_wrap.js
netwerk/test/unit_ipc/test_cookie_header_stripped.js
netwerk/test/unit_ipc/test_cookiejars_wrap.js
toolkit/components/downloads/test/unit/test_DownloadCore.js
toolkit/components/downloads/test/unit/test_DownloadLegacy.js
toolkit/mozapps/extensions/test/xpinstall/head.js
--- a/browser/components/enterprisepolicies/tests/browser/browser_policy_cookie_settings.js
+++ b/browser/components/enterprisepolicies/tests/browser/browser_policy_cookie_settings.js
@@ -8,17 +8,19 @@ XPCOMUtils.defineLazyServiceGetter(Servi
                                    "nsICookieService");
 XPCOMUtils.defineLazyServiceGetter(Services, "cookiemgr",
                                    "@mozilla.org/cookiemanager;1",
                                    "nsICookieManager");
 
 function restore_prefs() {
   Services.prefs.clearUserPref("network.cookie.cookieBehavior");
   Services.prefs.clearUserPref("network.cookie.lifetimePolicy");
+  Services.prefs.clearUserPref("network.cookieSettings.unblocked_for_testing");
 }
+
 registerCleanupFunction(restore_prefs);
 
 async function fake_profile_change() {
   await new Promise(resolve => {
     Services.obs.addObserver(function waitForDBClose() {
       Services.obs.removeObserver(waitForDBClose, "cookie-db-closed");
       resolve();
     }, "cookie-db-closed");
@@ -127,42 +129,45 @@ async function test_cookie_settings({
   }
 }
 
 add_task(async function prepare_tracker_tables() {
   await UrlClassifierTestUtils.addTestTrackers();
 });
 
 add_task(async function test_initial_state() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await test_cookie_settings({
     cookiesEnabled: true,
     thirdPartyCookiesEnabled: true,
     cookiesExpireAfterSession: false,
     cookieSettingsLocked: false,
   });
   restore_prefs();
 });
 
 add_task(async function test_undefined_unlocked() {
   Services.prefs.setIntPref("network.cookie.cookieBehavior", 3);
   Services.prefs.setIntPref("network.cookie.lifetimePolicy", 2);
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
       },
     },
   });
   is(Services.prefs.getIntPref("network.cookie.cookieBehavior", undefined), 3,
      "An empty cookie policy should not have changed the cookieBehavior preference");
   is(Services.prefs.getIntPref("network.cookie.lifetimePolicy", undefined), 2,
      "An empty cookie policy should not have changed the lifetimePolicy preference");
   restore_prefs();
 });
 
 add_task(async function test_disabled() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "Default": false,
       },
     },
   });
 
@@ -171,16 +176,17 @@ add_task(async function test_disabled() 
     thirdPartyCookiesEnabled: true,
     cookiesExpireAfterSession: false,
     cookieSettingsLocked: false,
   });
   restore_prefs();
 });
 
 add_task(async function test_third_party_disabled() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "AcceptThirdParty": "never",
       },
     },
   });
 
@@ -189,16 +195,17 @@ add_task(async function test_third_party
     thirdPartyCookiesEnabled: false,
     cookiesExpireAfterSession: false,
     cookieSettingsLocked: false,
   });
   restore_prefs();
 });
 
 add_task(async function test_disabled_and_third_party_disabled() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "Default": false,
         "AcceptThirdParty": "never",
       },
     },
   });
@@ -208,16 +215,17 @@ add_task(async function test_disabled_an
     thirdPartyCookiesEnabled: false,
     cookiesExpireAfterSession: false,
     cookieSettingsLocked: false,
   });
   restore_prefs();
 });
 
 add_task(async function test_disabled_and_third_party_disabled_locked() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "Default": false,
         "AcceptThirdParty": "never",
         "Locked": true,
       },
     },
@@ -228,16 +236,17 @@ add_task(async function test_disabled_an
     thirdPartyCookiesEnabled: false,
     cookiesExpireAfterSession: false,
     cookieSettingsLocked: true,
   });
   restore_prefs();
 });
 
 add_task(async function test_undefined_locked() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "Locked": true,
       },
     },
   });
 
@@ -246,16 +255,17 @@ add_task(async function test_undefined_l
     thirdPartyCookiesEnabled: true,
     cookiesExpireAfterSession: false,
     cookieSettingsLocked: true,
   });
   restore_prefs();
 });
 
 add_task(async function test_cookie_expire() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "ExpireAtSessionEnd": true,
       },
     },
   });
 
@@ -264,16 +274,17 @@ add_task(async function test_cookie_expi
     thirdPartyCookiesEnabled: true,
     cookiesExpireAfterSession: true,
     cookieSettingsLocked: false,
   });
   restore_prefs();
 });
 
 add_task(async function test_cookie_reject_trackers() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "RejectTracker": true,
       },
     },
   });
 
@@ -283,16 +294,17 @@ add_task(async function test_cookie_reje
     cookiesExpireAfterSession: false,
     rejectTrackers: true,
     cookieSettingsLocked: false,
   });
   restore_prefs();
 });
 
 add_task(async function test_cookie_expire_locked() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "ExpireAtSessionEnd": true,
         "Locked": true,
       },
     },
   });
@@ -302,16 +314,17 @@ add_task(async function test_cookie_expi
     thirdPartyCookiesEnabled: true,
     cookiesExpireAfterSession: true,
     cookieSettingsLocked: true,
   });
   restore_prefs();
 });
 
 add_task(async function test_disabled_cookie_expire_locked() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   await setupPolicyEngineWithJson({
     "policies": {
       "Cookies": {
         "Default": false,
         "AcceptThirdParty": "never",
         "ExpireAtSessionEnd": true,
         "Locked": true,
       },
--- a/dom/xhr/tests/mochitest.ini
+++ b/dom/xhr/tests/mochitest.ini
@@ -74,16 +74,17 @@ support-files =
 [test_sync_xhr_timer.xhtml]
 skip-if = toolkit == 'android'
 [test_sync_xhr_unload.html]
 [test_temporaryFileBlob.html]
 [test_worker_terminateSyncXHR.html]
 [test_worker_xhr.html]
 [test_worker_xhr2.html]
 [test_worker_xhr_3rdparty.html]
+support-files = window_worker_xhr_3rdparty.html
 [test_worker_xhr_cors_redirect.html]
 [test_worker_xhr_headers.html]
 [test_worker_xhr_implicit_cancel.html]
 [test_worker_xhr_parameters.html]
 [test_worker_xhr_responseURL.html]
 [test_worker_xhr_system.html]
 [test_worker_xhr_timeout.html]
 [test_worker_xhrAbort.html]
--- a/dom/xhr/tests/test_worker_xhr_3rdparty.html
+++ b/dom/xhr/tests/test_worker_xhr_3rdparty.html
@@ -9,66 +9,41 @@ Tests of DOM Worker Threads XHR(Bug 4504
 -->
 <head>
   <title>Test for DOM Worker Threads XHR (Bug 450452 )</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=450452">DOM Worker Threads XHR (Bug 450452)</a>
-<p id="display"></p>
-<div id="content" style="display: none">
 
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
-  var worker = new Worker("xhr_worker.js");
+  document.cookie = "a=cookie_is_set";
 
-  var gotUploadLoad = false, gotLoadend = false;
+  SpecialPowers.pushPrefEnv({ set: [[ "network.cookie.cookieBehavior", 1 ]] },
+                            () => {
+    let w = window.open("window_worker_xhr_3rdparty.html");
 
-  worker.onmessage = function(event) {
-    is(event.target, worker);
-    var args = event.data;
-    switch (args.type) {
-      case "progress": {
-        ok(parseInt(args.current) <= parseInt(args.total));
-      } break;
-      case "error": {
-        ok(false, "XHR error: " + args.error);
-      } break;
-      case "upload.load": {
-        gotUploadLoad = true;
-      } break;
-      case "load": {
-        ok(gotUploadLoad, "Should have gotten upload load event");
-        gotLoadend = true;
-        is(args.data, "a=cookie_is_set", "correct data");
-        document.getElementById("content").textContent = args.data;
-      } break;
-      case "loadend": {
-        ok(gotLoadend, "Should have gotten load.");
+    onmessage = e => {
+      if (e.data.type == "finish") {
+        w.close();
         SimpleTest.finish();
-        break;
+        return;
       }
-      default: {
-        ok(false, "Unexpected message");
-        SimpleTest.finish();
-      }
-    }
-  };
 
-  worker.onerror = function(event) {
-    is(event.target, worker);
-    ok(false, "Worker had an error:" + event.message);
-    SimpleTest.finish();
-  }
+      if (e.data.type == "test") {
+        ok(e.data.test, e.data.msg);
+        return;
+      }
 
-  document.cookie = "a=cookie_is_set";
-  SpecialPowers.pushPrefEnv({ set: [[ "network.cookie.cookieBehavior", 1 ]] },
-                            () => worker.postMessage("worker_file_getcookie.sjs"));
+      ok(false, "Invalid message.");
+    }
+  });
 
   SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/dom/xhr/tests/window_worker_xhr_3rdparty.html
@@ -0,0 +1,71 @@
+<!--
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<!DOCTYPE HTML>
+<html>
+<!--
+Tests of DOM Worker Threads XHR(Bug 450452 )
+-->
+<body>
+<div id="content" style="display: none"></div>
+<script class="testbody" type="text/javascript">
+
+  function ok(a, msg) {
+    opener.postMessage({type: "test", test: !!a, msg }, "*");
+  }
+
+  function is(a, b, msg) {
+    ok(a === b, msg);
+  }
+
+  function finish() {
+    opener.postMessage({type: "finish" }, "*");
+  }
+
+  var worker = new Worker("xhr_worker.js");
+
+  var gotUploadLoad = false, gotLoadend = false;
+
+  worker.onmessage = function(event) {
+    is(event.target, worker);
+    var args = event.data;
+    switch (args.type) {
+      case "progress": {
+        ok(parseInt(args.current) <= parseInt(args.total));
+      } break;
+      case "error": {
+        ok(false, "XHR error: " + args.error);
+      } break;
+      case "upload.load": {
+        gotUploadLoad = true;
+      } break;
+      case "load": {
+        ok(gotUploadLoad, "Should have gotten upload load event");
+        gotLoadend = true;
+        is(args.data, "a=cookie_is_set", "correct data");
+        document.getElementById("content").textContent = args.data;
+      } break;
+      case "loadend": {
+        ok(gotLoadend, "Should have gotten load.");
+        finish();
+        break;
+      }
+      default: {
+        ok(false, "Unexpected message");
+        finish();
+      }
+    }
+  };
+
+  worker.onerror = function(event) {
+    is(event.target, worker);
+    ok(false, "Worker had an error:" + event.message);
+    finish();
+  }
+
+  worker.postMessage("worker_file_getcookie.sjs");
+
+</script>
+</body>
+</html>
--- a/extensions/cookie/test/unit/test_cookies_privatebrowsing.js
+++ b/extensions/cookie/test/unit/test_cookies_privatebrowsing.js
@@ -21,16 +21,19 @@ function make_channel(url) {
   return NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true})
                 .QueryInterface(Ci.nsIHttpChannel);
 }
 
 function* do_run_test() {
   // Set up a profile.
   let profile = do_get_profile();
 
+  // We don't want to have CookieSettings blocking this test.
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+
   // Test with cookies enabled.
   Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
 
   // Create URIs pointing to foo.com and bar.com.
   let uri1 = NetUtil.newURI("http://foo.com/foo.html");
   let uri2 = NetUtil.newURI("http://bar.com/bar.html");
 
   // Set a cookie for host 1.
--- a/extensions/cookie/test/unit/test_cookies_thirdparty_nonsecure_session.js
+++ b/extensions/cookie/test/unit/test_cookies_thirdparty_nonsecure_session.js
@@ -20,16 +20,19 @@ function finish_test() {
     do_test_finished();
   });
 }
 
 function* do_run_test() {
   // Set up a profile.
   let profile = do_get_profile();
 
+  // We don't want to have CookieSettings blocking this test.
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+
   // Create URIs and channels pointing to foo.com and bar.com.
   // We will use these to put foo.com into first and third party contexts.
   var spec1 = "http://foo.com/foo.html";
   var spec2 = "https://bar.com/bar.html";
   var uri1 = NetUtil.newURI(spec1);
   var uri2 = NetUtil.newURI(spec2);
   var channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
   var channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
--- a/extensions/cookie/test/unit/test_cookies_thirdparty_session.js
+++ b/extensions/cookie/test/unit/test_cookies_thirdparty_session.js
@@ -18,16 +18,19 @@ function finish_test() {
     do_test_finished();
   });
 }
 
 function* do_run_test() {
   // Set up a profile.
   let profile = do_get_profile();
 
+  // We don't want to have CookieSettings blocking this test.
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+
   // Create URIs and channels pointing to foo.com and bar.com.
   // We will use these to put foo.com into first and third party contexts.
   var spec1 = "http://foo.com/foo.html";
   var spec2 = "http://bar.com/bar.html";
   var uri1 = NetUtil.newURI(spec1);
   var uri2 = NetUtil.newURI(spec2);
   var channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
   var channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
--- a/netwerk/cookie/moz.build
+++ b/netwerk/cookie/moz.build
@@ -45,16 +45,20 @@ if CONFIG['NECKO_COOKIES']:
     XPCSHELL_TESTS_MANIFESTS += [
         'test/unit/xpcshell.ini',
     ]
 
     BROWSER_CHROME_MANIFESTS += [
         'test/browser/browser.ini',
     ]
 
+    MOCHITEST_MANIFESTS += [
+        'test/mochitest/mochitest.ini',
+    ]
+
 IPDL_SOURCES = [
     'PCookieService.ipdl',
 ]
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
 
--- a/netwerk/cookie/test/browser/browser.ini
+++ b/netwerk/cookie/test/browser/browser.ini
@@ -1,13 +1,15 @@
 [DEFAULT]
 support-files =
   file_empty.html
   file_empty.js
   head.js
 
 [browser_broadcastChannel.js]
+[browser_cookies.js]
+support-files = server.sjs
 [browser_domCache.js]
 [browser_indexedDB.js]
 [browser_originattributes.js]
 [browser_storage.js]
 [browser_serviceWorker.js]
 [browser_sharedWorker.js]
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/browser/browser_cookies.js
@@ -0,0 +1,35 @@
+CookiePolicyHelper.runTest("document.cookies", {
+  cookieJarAccessAllowed: async _ => {
+    let hasCookie = !!content.document.cookie.length;
+
+    await content.fetch("server.sjs").then(r => r.text()).then(text => {
+      is(text, hasCookie ? "cookie-present" : "cookie-not-present", "document.cookie is consistent with fetch requests");
+    });
+
+    content.document.cookie = "name=value";
+    ok(content.document.cookie.includes("name=value"), "Some cookies for me");
+    ok(content.document.cookie.includes("foopy=1"), "Some cookies for me");
+
+    await content.fetch("server.sjs").then(r => r.text()).then(text => {
+      is(text, "cookie-present", "We should have cookies");
+    });
+
+    ok(!!content.document.cookie.length, "Some Cookies for me");
+  },
+
+  cookieJarAccessDenied: async _ => {
+    is(content.document.cookie, "", "No cookies for me");
+    content.document.cookie = "name=value";
+    is(content.document.cookie, "", "No cookies for me");
+
+    await content.fetch("server.sjs").then(r => r.text()).then(text => {
+      is(text, "cookie-not-present", "We should not have cookies");
+    });
+    // Let's do it twice.
+    await content.fetch("server.sjs").then(r => r.text()).then(text => {
+      is(text, "cookie-not-present", "We should not have cookies");
+    });
+
+    is(content.document.cookie, "", "Still no cookies for me");
+  }
+});
--- a/netwerk/cookie/test/browser/head.js
+++ b/netwerk/cookie/test/browser/head.js
@@ -18,66 +18,62 @@ const TEST_TOP_PAGE = TEST_DOMAIN + TEST
 // ContentTask.spawn frame-script context, use content to access the underlying
 // page.
 this.CookiePolicyHelper = {
   runTest(testName, config) {
     // Testing allowed to blocked by cookie behavior
     this._createTest(testName,
                      config.cookieJarAccessAllowed,
                      config.cookieJarAccessDenied,
-                     config.cleanup,
                      config.prefs,
                      {
                        fromBehavior: BEHAVIOR_ACCEPT,
                        toBehavior: BEHAVIOR_REJECT,
                        fromPermission: PERM_DEFAULT,
                        toPermission: PERM_DEFAULT,
                      });
 
     // Testing blocked to allowed by cookie behavior
     this._createTest(testName,
                      config.cookieJarAccessDenied,
                      config.cookieJarAccessAllowed,
-                     config.cleanup,
                      config.prefs,
                      {
                        fromBehavior: BEHAVIOR_REJECT,
                        toBehavior: BEHAVIOR_ACCEPT,
                        fromPermission: PERM_DEFAULT,
                        toPermission: PERM_DEFAULT,
                      });
 
     // Testing allowed to blocked by cookie permission
     this._createTest(testName,
                      config.cookieJarAccessAllowed,
                      config.cookieJarAccessDenied,
-                     config.cleanup,
                      config.prefs,
                      {
                        fromBehavior: BEHAVIOR_REJECT,
                        toBehavior: BEHAVIOR_REJECT,
                        fromPermission: PERM_ALLOW,
                        toPermission: PERM_DEFAULT,
                      });
 
     // Testing blocked to allowed by cookie permission
     this._createTest(testName,
                      config.cookieJarAccessDenied,
                      config.cookieJarAccessAllowed,
-                     config.cleanup,
                      config.prefs,
                      {
                        fromBehavior: BEHAVIOR_ACCEPT,
                        toBehavior: BEHAVIOR_ACCEPT,
                        fromPermission: PERM_DENY,
                        toPermission: PERM_DEFAULT,
                      });
   },
 
-  _createTest(testName, goodCb, badCb, cleanupCb, prefs, config) {
+  _createTest(testName, goodCb, badCb, prefs, config) {
     add_task(async _ => {
       info("Starting " + testName + ": " + config.toSource());
 
       await SpecialPowers.flushPrefEnv();
 
       if (prefs) {
         await SpecialPowers.pushPrefEnv({"set": prefs });
       }
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/browser/server.sjs
@@ -0,0 +1,9 @@
+function handleRequest(aRequest, aResponse) {
+  aResponse.setStatusLine(aRequest.httpVersion, 200);
+  if (aRequest.hasHeader('Cookie')) {
+    aResponse.write("cookie-present");
+  } else {
+    aResponse.setHeader("Set-Cookie", "foopy=1");
+    aResponse.write("cookie-not-present");
+  }
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/.eslintrc.js
@@ -0,0 +1,7 @@
+"use strict";
+
+module.exports = {
+  "extends": [
+    "plugin:mozilla/mochitest-test",
+  ]
+};
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/cookie.sjs
@@ -0,0 +1,124 @@
+function handleRequest(aRequest, aResponse) {
+  let parts = aRequest.queryString.split("&");
+  if (parts.includes("window")) {
+    aResponse.setStatusLine(aRequest.httpVersion, 200);
+    aResponse.setHeader("Content-Type", "text/html");
+    aResponse.setHeader("Clear-Site-Data", '"cache", "cookies", "storage"');
+    aResponse.write("<body><h1>Welcome</h1></body>");
+    return;
+  }
+
+  if (parts.includes("fetch")) {
+    setState("data", JSON.stringify({type: "fetch", hasCookie: aRequest.hasHeader("Cookie") }));
+    aResponse.write("Hello world!");
+    return;
+  }
+
+  if (parts.includes("xhr")) {
+    setState("data", JSON.stringify({type: "xhr", hasCookie: aRequest.hasHeader("Cookie") }));
+    aResponse.write("Hello world!");
+    return;
+  }
+
+  if (parts.includes("image")) {
+    setState("data", JSON.stringify({type: "image", hasCookie: aRequest.hasHeader("Cookie") }));
+
+    // A 1x1 PNG image.
+    // Source: https://commons.wikimedia.org/wiki/File:1x1.png (Public Domain)
+    const IMAGE = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
+                       "ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=");
+
+    aResponse.setHeader("Content-Type", "image/png", false);
+    aResponse.write(IMAGE);
+    return;
+  }
+
+  if (parts.includes("script")) {
+    setState("data", JSON.stringify({type: "script", hasCookie: aRequest.hasHeader("Cookie") }));
+
+    aResponse.setHeader("Content-Type", "text/javascript", false);
+    aResponse.write("window.scriptLoaded();");
+    return;
+  }
+
+  if (parts.includes("worker")) {
+    setState("data", JSON.stringify({type: "worker", hasCookie: aRequest.hasHeader("Cookie") }));
+
+    function w() {
+      onmessage = e => {
+        if (e.data == "subworker") {
+          importScripts("cookie.sjs?subworker&" + Math.random());
+          postMessage(42);
+          return;
+        }
+
+        if (e.data == "fetch") {
+          fetch("cookie.sjs?fetch&" + Math.random()).then(r => r.text()).then(_ => postMessage(42));
+          return;
+        }
+
+        if (e.data == "xhr") {
+          let xhr = new XMLHttpRequest();
+          xhr.open("GET", "cookie.sjs?xhr&" + Math.random());
+          xhr.send();
+          xhr.onload = _ => postMessage(42);
+        }
+      };
+      postMessage(42);
+    };
+
+    aResponse.setHeader("Content-Type", "text/javascript", false);
+    aResponse.write(w.toString() + "; w();");
+    return;
+  }
+
+  if (parts.includes("subworker")) {
+    setState("data", JSON.stringify({type: "subworker", hasCookie: aRequest.hasHeader("Cookie") }));
+    aResponse.setHeader("Content-Type", "text/javascript", false);
+    aResponse.write("42");
+    return;
+  }
+
+  if (parts.includes("sharedworker")) {
+    setState("data", JSON.stringify({type: "sharedworker", hasCookie: aRequest.hasHeader("Cookie") }));
+
+    function w() {
+      onconnect = e => {
+        e.ports[0].onmessage = evt => {
+          if (evt.data == "subworker") {
+            importScripts("cookie.sjs?subworker&" + Math.random());
+            e.ports[0].postMessage(42);
+            return;
+          }
+
+          if (evt.data == "fetch") {
+            fetch("cookie.sjs?fetch&" + Math.random()).then(r => r.text()).then(_ => e.ports[0].postMessage(42));
+            return;
+          }
+
+          if (evt.data == "xhr") {
+            let xhr = new XMLHttpRequest();
+            xhr.open("GET", "cookie.sjs?xhr&" + Math.random());
+            xhr.send();
+            xhr.onload = _ => e.ports[0].postMessage(42);
+          }
+        };
+        e.ports[0].postMessage(42);
+      };
+    };
+
+    aResponse.setHeader("Content-Type", "text/javascript", false);
+    aResponse.write(w.toString() + "; w();");
+    return;
+  }
+
+  if (parts.includes("last")) {
+    let data = getState("data");
+    setState("data", "");
+    aResponse.write(data);
+    return;
+  }
+
+  aResponse.setStatusLine(aRequest.httpVersion, 400);
+  aResponse.write("Invalid request");
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/cookiesHelper.js
@@ -0,0 +1,52 @@
+const ALLOWED = 0;
+const BLOCKED = 1;
+
+async function cleanupData() {
+  await new Promise(resolve => {
+    const chromeScript = SpecialPowers.loadChromeScript(_ => {
+      // eslint-disable-next-line no-undef
+      addMessageListener("go", __ => {
+        const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
+        Services.clearData.deleteData(Services.clearData.CLEAR_COOKIES |
+                                      Services.clearData.CLEAR_ALL_CACHES |
+                                      Services.clearData.CLEAR_DOM_STORAGES, ___ => {
+          // eslint-disable-next-line no-undef
+          sendAsyncMessage("done");
+        });
+      });
+    });
+
+    chromeScript.addMessageListener("done", _ => {
+      chromeScript.destroy();
+      resolve();
+    });
+
+    chromeScript.sendAsyncMessage("go");
+  });
+}
+
+async function checkLastRequest(type, state) {
+  let json = await fetch("cookie.sjs?last&" + Math.random()).then(r => r.json());
+  is(json.type, type, "Type: " + type);
+  is(json.hasCookie, state == ALLOWED, "Fetch has cookies");
+}
+
+async function runTests(currentTest) {
+  await cleanupData();
+  await SpecialPowers.pushPrefEnv({ set: [["network.cookie.cookieBehavior", 2]] });
+  let windowBlocked = window.open("cookie.sjs?window&" + Math.random());
+  await new Promise(resolve => { windowBlocked.onload = resolve; });
+  await currentTest(windowBlocked, BLOCKED);
+  windowBlocked.close();
+
+  await cleanupData();
+  await SpecialPowers.pushPrefEnv({ set: [["network.cookie.cookieBehavior", 1]] });
+  let windowAllowed = window.open("cookie.sjs?window&" + Math.random());
+  await new Promise(resolve => { windowAllowed.onload = resolve; });
+  await currentTest(windowAllowed, ALLOWED);
+  windowAllowed.close();
+
+  SimpleTest.finish();
+}
+
+SimpleTest.waitForExplicitFinish();
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/mochitest.ini
@@ -0,0 +1,13 @@
+[DEFAULT]
+scheme=https
+support-files =
+  cookie.sjs
+  cookiesHelper.js
+
+[test_document_cookie.html]
+[test_fetch.html]
+[test_image.html]
+[test_script.html]
+[test_sharedWorker.html]
+[test_worker.html]
+[test_xhr.html]
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/test_document_cookie.html
@@ -0,0 +1,20 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for document.cookie when the policy changes</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="cookiesHelper.js"></script>
+</head>
+<body>
+<script type="application/javascript">
+
+runTests(async (w, state) => {
+  is(w.document.cookie.length, 0, "No cookie to start!");
+  w.document.cookie = "name=value";
+  is(w.document.cookie.includes("name=value"), state == ALLOWED, "Some cookies for me");
+});
+
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/test_fetch.html
@@ -0,0 +1,20 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for cookies + fetch when the policy changes</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="cookiesHelper.js"></script>
+</head>
+<body>
+<script type="application/javascript">
+
+runTests(async (w, state) => {
+  w.document.cookie = "name=value";
+  await w.fetch("cookie.sjs?fetch&" + Math.random()).then(r => r.text());
+  await checkLastRequest("fetch", state);
+});
+
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/test_image.html
@@ -0,0 +1,24 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for cookies and image loading when the policy changes</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="cookiesHelper.js"></script>
+</head>
+<body>
+<script type="application/javascript">
+
+runTests(async (w, state) => {
+  w.document.cookie = "name=value";
+
+  let image = new w.Image();
+  image.src = "cookie.sjs?image&" + Math.random();
+  w.document.body.appendChild(image);
+  await new w.Promise(resolve => { image.onload = resolve; });
+  await checkLastRequest("image", state);
+});
+
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/test_script.html
@@ -0,0 +1,25 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for cookies + script loading when the policy changes</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="cookiesHelper.js"></script>
+</head>
+<body>
+<script type="application/javascript">
+
+runTests(async (w, state) => {
+  w.document.cookie = "name=value";
+
+  let p = new w.Promise(resolve => { w.scriptLoaded = resolve; });
+  let script = document.createElement("script");
+  script.src = "cookie.sjs?script&" + Math.random();
+  w.document.body.appendChild(script);
+  await p;
+  await checkLastRequest("script", state);
+});
+
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/test_sharedWorker.html
@@ -0,0 +1,50 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for cookies + SharedWorker loading when the policy changes</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="cookiesHelper.js"></script>
+</head>
+<body>
+<script type="application/javascript">
+
+runTests(async (w, state) => {
+  w.document.cookie = "name=value";
+
+  if (state == BLOCKED) {
+    try {
+      new w.SharedWorker("cookie.sjs?sharedworker&" + Math.random());
+      ok(false, "SharedWorker should not be allowed!");
+    } catch (ex) {
+      ok(true, "SharedWorker should not be allowed!");
+    }
+    return;
+  }
+
+  let p = new w.SharedWorker("cookie.sjs?sharedworker&" + Math.random());
+  await new w.Promise(resolve => { p.port.onmessage = resolve; });
+  await checkLastRequest("sharedworker", state);
+
+  await new w.Promise(resolve => {
+    p.port.postMessage("subworker");
+    p.port.onmessage = resolve;
+  });
+  await checkLastRequest("subworker", state);
+
+  await new w.Promise(resolve => {
+    p.port.postMessage("fetch");
+    p.port.onmessage = resolve;
+  });
+  await checkLastRequest("fetch", state);
+
+  await new w.Promise(resolve => {
+    p.port.postMessage("xhr");
+    p.port.onmessage = resolve;
+  });
+  await checkLastRequest("xhr", state);
+});
+
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/test_worker.html
@@ -0,0 +1,31 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for cookies + worker loading when the policy changes</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="cookiesHelper.js"></script>
+</head>
+<body>
+<script type="application/javascript">
+
+runTests(async (w, state) => {
+  w.document.cookie = "name=value";
+
+  let p = new w.Worker("cookie.sjs?worker&" + Math.random());
+  await new w.Promise(resolve => { p.onmessage = resolve; });
+  await checkLastRequest("worker", state);
+
+  await new w.Promise(resolve => { p.postMessage("subworker"); p.onmessage = resolve; });
+  await checkLastRequest("subworker", state);
+
+  await new w.Promise(resolve => { p.postMessage("fetch"); p.onmessage = resolve; });
+  await checkLastRequest("fetch", state);
+
+  await new w.Promise(resolve => { p.postMessage("xhr"); p.onmessage = resolve; });
+  await checkLastRequest("xhr", state);
+});
+
+</script>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/netwerk/cookie/test/mochitest/test_xhr.html
@@ -0,0 +1,25 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for cookies + XHR when the policy changes</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="cookiesHelper.js"></script>
+</head>
+<body>
+<script type="application/javascript">
+
+runTests(async (w, state) => {
+  w.document.cookie = "name=value";
+  await new w.Promise(resolve => {
+    let xhr = new w.XMLHttpRequest();
+    xhr.open("GET", "cookie.sjs?xhr&" + Math.random());
+    xhr.send();
+    xhr.onload = resolve;
+  });
+  await checkLastRequest("xhr", state);
+});
+
+</script>
+</body>
+</html>
--- a/netwerk/test/TestCookie.cpp
+++ b/netwerk/test/TestCookie.cpp
@@ -16,16 +16,17 @@
 #include "nsIPrincipal.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsISimpleEnumerator.h"
 #include "nsServiceManagerUtils.h"
 #include "nsNetCID.h"
 #include "nsIPrefBranch.h"
 #include "nsIPrefService.h"
 #include "mozilla/Unused.h"
+#include "mozilla/net/CookieSettings.h"
 #include "nsIURI.h"
 
 using mozilla::Unused;
 
 static NS_DEFINE_CID(kCookieServiceCID, NS_COOKIESERVICE_CID);
 static NS_DEFINE_CID(kPrefServiceCID, NS_PREFSERVICE_CID);
 
 // various pref strings
@@ -75,17 +76,17 @@ void SetACookie(nsICookieService *aCooki
       uri1, uri2, nullptr, (char *)aCookieString, aServerTime, nullptr);
   EXPECT_TRUE(NS_SUCCEEDED(rv));
 }
 
 // Custom Cookie Generator specifically for the needs of same-site cookies!
 // Hands off unless you know exactly what you are doing!
 void SetASameSiteCookie(nsICookieService *aCookieService, const char *aSpec1,
                         const char *aSpec2, const char *aCookieString,
-                        const char *aServerTime) {
+                        const char *aServerTime, bool aAllowed) {
   nsCOMPtr<nsIURI> uri1, uri2;
   NS_NewURI(getter_AddRefs(uri1), aSpec1);
   if (aSpec2) NS_NewURI(getter_AddRefs(uri2), aSpec2);
 
   // We create a dummy channel using the aSpec1 to simulate same-siteness
   nsresult rv0;
   nsCOMPtr<nsIScriptSecurityManager> ssm =
       do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv0);
@@ -95,16 +96,23 @@ void SetASameSiteCookie(nsICookieService
   ssm->CreateCodebasePrincipalFromOrigin(tmpString,
                                          getter_AddRefs(spec1Principal));
 
   nsCOMPtr<nsIChannel> dummyChannel;
   NS_NewChannel(getter_AddRefs(dummyChannel), uri1, spec1Principal,
                 nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK,
                 nsIContentPolicy::TYPE_OTHER);
 
+  nsCOMPtr<nsICookieSettings> cookieSettings =
+      aAllowed ? CookieSettings::Create() : CookieSettings::CreateBlockingAll();
+  MOZ_ASSERT(cookieSettings);
+
+  nsCOMPtr<nsILoadInfo> loadInfo = dummyChannel->LoadInfo();
+  loadInfo->SetCookieSettings(cookieSettings);
+
   nsresult rv = aCookieService->SetCookieStringFromHttp(
       uri1, uri2, nullptr, (char *)aCookieString, aServerTime, dummyChannel);
   EXPECT_TRUE(NS_SUCCEEDED(rv));
 }
 
 void SetACookieNoHttp(nsICookieService *aCookieService, const char *aSpec,
                       const char *aCookieString) {
   nsCOMPtr<nsIURI> uri;
@@ -999,35 +1007,63 @@ TEST(TestCookie, TestCookieMain) {
   GetACookie(cookieService, "http://creation.ordering.tests/", nullptr, cookie);
 
   EXPECT_TRUE(CheckResult(cookie.get(), MUST_BE_NULL));
 
   // *** SameSite attribute - parsing and cookie storage tests
   // Clear the cookies
   EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->RemoveAll()));
 
+  // None of these cookies will be set because using
+  // CookieSettings::CreateBlockingAll().
+  SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
+                     "unset=yes", nullptr, false);
+  SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
+                     "unspecified=yes; samesite", nullptr, false);
+  SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
+                     "empty=yes; samesite=", nullptr, false);
+  SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
+                     "bogus=yes; samesite=bogus", nullptr, false);
+  SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
+                     "strict=yes; samesite=strict", nullptr, false);
+  SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
+                     "lax=yes; samesite=lax", nullptr, false);
+
+  EXPECT_TRUE(
+      NS_SUCCEEDED(cookieMgr->GetEnumerator(getter_AddRefs(enumerator))));
+  i = 0;
+
+  // check the cookies for the required samesite value
+  while (NS_SUCCEEDED(enumerator->HasMoreElements(&more)) && more) {
+    nsCOMPtr<nsISupports> cookie;
+    if (NS_FAILED(enumerator->GetNext(getter_AddRefs(cookie)))) break;
+    ++i;
+  }
+
+  EXPECT_TRUE(i == 0);
+
   // Set cookies with various incantations of the samesite attribute:
   // No same site attribute present
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "unset=yes", nullptr);
+                     "unset=yes", nullptr, true);
   // samesite attribute present but with no value
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "unspecified=yes; samesite", nullptr);
+                     "unspecified=yes; samesite", nullptr, true);
   // samesite attribute present but with an empty value
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "empty=yes; samesite=", nullptr);
+                     "empty=yes; samesite=", nullptr, true);
   // samesite attribute present but with an invalid value
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "bogus=yes; samesite=bogus", nullptr);
+                     "bogus=yes; samesite=bogus", nullptr, true);
   // samesite=strict
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "strict=yes; samesite=strict", nullptr);
+                     "strict=yes; samesite=strict", nullptr, true);
   // samesite=lax
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "lax=yes; samesite=lax", nullptr);
+                     "lax=yes; samesite=lax", nullptr, true);
 
   EXPECT_TRUE(
       NS_SUCCEEDED(cookieMgr->GetEnumerator(getter_AddRefs(enumerator))));
   i = 0;
 
   // check the cookies for the required samesite value
   while (NS_SUCCEEDED(enumerator->HasMoreElements(&more)) && more) {
     nsCOMPtr<nsISupports> cookie;
--- a/netwerk/test/unit/test_bug248970_cookie.js
+++ b/netwerk/test/unit/test_bug248970_cookie.js
@@ -58,18 +58,20 @@ function setHandler(metadata, response) 
   var match = /cookie=([^&]*)/.exec(metadata.queryString);
   if (match) {
     response.setHeader("Set-Cookie", match[1]);
   }
 }
 
 function run_test() {
   // Allow all cookies if the pref service is available in this process.
-  if (!inChildProcess())
+  if (!inChildProcess()) {
     Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
+    Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+  }
 
   httpserver = new HttpServer();
   httpserver.registerPathHandler("/set", setHandler);
   httpserver.registerPathHandler("/present", presentHandler);
   httpserver.start(-1);
   
   do_test_pending();
   
--- a/netwerk/test/unit/test_bug528292.js
+++ b/netwerk/test/unit/test_bug528292.js
@@ -50,16 +50,18 @@ function run_test()
   httpServer.registerPathHandler(preRedirectPath, preRedirectHandler);
   httpServer.registerPathHandler(postRedirectPath, postRedirectHandler);
   httpServer.start(-1);
 
   if (!inChildProcess()) {
     // Disable third-party cookies in general.
     Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch).
       setIntPref("network.cookie.cookieBehavior", 1);
+    Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch).
+      setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   }
 
   var ioService = Cc["@mozilla.org/network/io-service;1"].
                   getService(Ci.nsIIOService);
 
   // Set up a channel with forceAllowThirdPartyCookie set to true.  We'll use
   // the channel both to set a cookie (since nsICookieService::setCookieString
   // requires such a channel in order to successfully set a cookie) and then
--- a/netwerk/test/unit/test_bug659569.js
+++ b/netwerk/test/unit/test_bug659569.js
@@ -14,16 +14,19 @@ function setupChannel(suffix)
 function checkValueAndTrigger(request, data, ctx)
 {
     Assert.equal("Ok", data);
     httpserver.stop(do_test_finished);
 }
 
 function run_test()
 {
+    // We don't want to have CookieSettings blocking this test.
+    Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+
     // Allow all cookies.
     Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
 
     httpserver.registerPathHandler("/redirect1", redirectHandler1);
     httpserver.registerPathHandler("/redirect2", redirectHandler2);
     httpserver.start(-1);
 
     // clear cache
--- a/netwerk/test/unit/test_cookie_header.js
+++ b/netwerk/test/unit/test_cookie_header.js
@@ -59,18 +59,20 @@ function makeChan() {
   return NetUtil.newChannel({uri: URL, loadUsingSystemPrincipal: true})
                 .QueryInterface(Ci.nsIHttpChannel);
 }
 
 var httpserv = null;
 
 function run_test() {
   // Allow all cookies if the pref service is available in this process.
-  if (!inChildProcess())
+  if (!inChildProcess()) {
     Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
+    Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+  }
 
   httpserv = new HttpServer();
   httpserv.start(-1);
 
   var chan = makeChan();
 
   chan.setRequestHeader("Cookie", cookieVal, false);
 
--- a/netwerk/test/unit/test_cookiejars.js
+++ b/netwerk/test/unit/test_cookiejars.js
@@ -110,18 +110,20 @@ function completeCheckCookie(request, da
   } else {
     checkCookie();
   }
 }
 
 function run_test()
 {
   // Allow all cookies if the pref service is available in this process.
-  if (!inChildProcess())
+  if (!inChildProcess()) {
     Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
+    Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+  }
 
   httpserver.registerPathHandler(cookieSetPath, cookieSetHandler);
   httpserver.registerPathHandler(cookieCheckPath, cookieCheckHandler);
   httpserver.start(-1);
 
   setCookie();
   do_test_pending();
 }
--- a/netwerk/test/unit/test_cookiejars_safebrowsing.js
+++ b/netwerk/test/unit/test_cookiejars_safebrowsing.js
@@ -87,18 +87,20 @@ function setupChannel(path, originAttrib
 }
 
 function run_test() {
 
   // Set up a profile
   do_get_profile();
 
   // Allow all cookies if the pref service is available in this process.
-  if (!inChildProcess())
+  if (!inChildProcess()) {
     Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
+    Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+  }
 
   httpserver = new HttpServer();
   httpserver.registerPathHandler(setCookiePath, cookieSetHandler);
   httpserver.registerPathHandler(checkCookiePath, cookieCheckHandler);
   httpserver.registerPathHandler(safebrowsingUpdatePath, safebrowsingUpdateHandler);
   httpserver.registerPathHandler(safebrowsingGethashPath, safebrowsingGethashHandler);
 
   httpserver.start(-1);
--- a/netwerk/test/unit/test_private_cookie_changed.js
+++ b/netwerk/test/unit/test_private_cookie_changed.js
@@ -9,16 +9,19 @@ function makeChan(uri, isPrivate) {
     loadUsingSystemPrincipal: true
   }).QueryInterface(Ci.nsIHttpChannel);
 
   chan.QueryInterface(Ci.nsIPrivateBrowsingChannel).setPrivate(isPrivate);
   return chan;
 }
 
 function run_test() {
+  // We don't want to have CookieSettings blocking this test.
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
+
   // Allow all cookies.
   Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
   
   let publicNotifications = 0;
   let privateNotifications = 0;
   Services.obs.addObserver(function() {publicNotifications++;}, "cookie-changed");
   Services.obs.addObserver(function() {privateNotifications++;}, "private-cookie-changed");
 
--- a/netwerk/test/unit_ipc/test_bug528292_wrap.js
+++ b/netwerk/test/unit_ipc/test_bug528292_wrap.js
@@ -1,6 +1,7 @@
 const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 function run_test() {
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   Services.prefs.setIntPref("network.cookie.cookieBehavior", 1);
   run_test_in_child("../unit/test_bug528292.js");
 }
--- a/netwerk/test/unit_ipc/test_cookie_header_stripped.js
+++ b/netwerk/test/unit_ipc/test_cookie_header_stripped.js
@@ -24,21 +24,23 @@ function run_test() {
   httpserv.registerPathHandler("/path", requestHandler);
   httpserv.start(-1);
   httpserv.identity.add("http", TEST_DOMAIN, httpserv.identity.primaryPort);
 
   registerCleanupFunction(() => {
     Services.cookies.removeCookiesWithOriginAttributes("{}", TEST_DOMAIN);
     Services.prefs.clearUserPref("network.dns.localDomains");
     Services.prefs.clearUserPref("network.cookie.cookieBehavior");
+    Services.prefs.clearUserPref("network.cookieSettings.unblocked_for_testing");
 
     httpserv.stop();
     httpserv = null;
   });
 
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   Services.prefs.setCharPref("network.dns.localDomains", TEST_DOMAIN);
   Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
   Services.cookies.removeCookiesWithOriginAttributes("{}", TEST_DOMAIN);
 
   // Sends back the URL to the child script
   do_await_remote_message("start-test").then(() => {
     do_send_remote_message("start-test-done", URL);
   });
--- a/netwerk/test/unit_ipc/test_cookiejars_wrap.js
+++ b/netwerk/test/unit_ipc/test_cookiejars_wrap.js
@@ -1,7 +1,8 @@
 const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 function run_test() {
   // Allow all cookies.
+  Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
   Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
   run_test_in_child("../unit/test_cookiejars.js");
 }
--- a/toolkit/components/downloads/test/unit/test_DownloadCore.js
+++ b/toolkit/components/downloads/test/unit/test_DownloadCore.js
@@ -13,16 +13,17 @@ ChromeUtils.defineModuleGetter(this, "Do
                                "resource://gre/modules/DownloadCore.jsm");
 
 // Execution of common tests
 
 var gUseLegacySaver = false;
 
 var scriptFile = do_get_file("common_test_Download.js");
 Services.scriptloader.loadSubScript(NetUtil.newURI(scriptFile).spec);
+Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
 
 // Tests
 
 /**
  * The download should fail early if the source and the target are the same.
  */
 add_task(async function test_error_target_downloadingToSameFile() {
   let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
--- a/toolkit/components/downloads/test/unit/test_DownloadLegacy.js
+++ b/toolkit/components/downloads/test/unit/test_DownloadLegacy.js
@@ -10,16 +10,17 @@
 "use strict";
 
 // Execution of common tests
 
 var gUseLegacySaver = true;
 
 var scriptFile = do_get_file("common_test_Download.js");
 Services.scriptloader.loadSubScript(NetUtil.newURI(scriptFile).spec);
+Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
 
 /**
  * Checks the referrer for restart downloads.
  * If the legacy download is stopped and restarted, the saving method
  * is changed from DownloadLegacySaver to the DownloadCopySaver.
  * The referrer header should be passed correctly.
  */
 add_task(async function test_referrer_restart() {
--- a/toolkit/mozapps/extensions/test/xpinstall/head.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/head.js
@@ -92,18 +92,19 @@ var Harness = {
 
   // Setup and tear down functions
   setup() {
     if (!this.waitingForFinish) {
       waitForExplicitFinish();
       this.waitingForFinish = true;
 
       Services.prefs.setBoolPref(PREF_INSTALL_REQUIRESECUREORIGIN, false);
+      Services.prefs.setBoolPref(PREF_LOGGING_ENABLED, true);
+      Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
 
-      Services.prefs.setBoolPref(PREF_LOGGING_ENABLED, true);
       Services.obs.addObserver(this, "addon-install-started");
       Services.obs.addObserver(this, "addon-install-disabled");
       // XXX this breaks a bunch of stuff, see comment in onInstallCancelled
       // Services.obs.addObserver(this, "addon-install-cancelled", false);
       Services.obs.addObserver(this, "addon-install-origin-blocked");
       Services.obs.addObserver(this, "addon-install-blocked");
       Services.obs.addObserver(this, "addon-install-failed");
       Services.obs.addObserver(this, "addon-install-complete");
@@ -114,16 +115,18 @@ var Harness = {
 
       window.addEventListener("popupshown", this);
       PanelUI.notificationPanel.addEventListener("popupshown", this);
 
       var self = this;
       registerCleanupFunction(async function() {
         Services.prefs.clearUserPref(PREF_LOGGING_ENABLED);
         Services.prefs.clearUserPref(PREF_INSTALL_REQUIRESECUREORIGIN);
+        Services.prefs.clearUserPref("network.cookieSettings.unblocked_for_testing");
+
         Services.obs.removeObserver(self, "addon-install-started");
         Services.obs.removeObserver(self, "addon-install-disabled");
         // Services.obs.removeObserver(self, "addon-install-cancelled");
         Services.obs.removeObserver(self, "addon-install-origin-blocked");
         Services.obs.removeObserver(self, "addon-install-blocked");
         Services.obs.removeObserver(self, "addon-install-failed");
         Services.obs.removeObserver(self, "addon-install-complete");