Backed out 16 changesets (bug 1525245) for Android failures. CLOSED TREE
authorDorel Luca <dluca@mozilla.com>
Wed, 06 Mar 2019 21:07:49 +0200
changeset 462686 32412e6eb5511f3f551aad5be3e38ec1acbb2f3f
parent 462685 007f59cfee3b8ab36730b7ee50d658fa714b663c
child 462687 60c03f3c8c5b67e337887eaf22191c71127687dc
push id79790
push userdluca@mozilla.com
push dateWed, 06 Mar 2019 19:08:22 +0000
treeherderautoland@32412e6eb551 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs1525245
milestone67.0a1
backs out9f8a1b41032052121d45540b57db45710011820e
0ef284a9a1d5ae82ec404a6935fc7272eb3484df
835e5f642a03df66f2240dd174a42fe203e4d372
362f5a8d033c44cbdc0b84d47774b908a2eac5dc
9da3ab33cf679f8a11cbfcd87e93fc5826fe95cd
6aacd2d6e835af4012ad206fdfec7909c5d7bd45
8ff9e8f45e02c5a46473df098e5a4aff2c971236
2020227181ccbe32dd3e8cddf6860cf32634344e
fc3c64c330b914adc88eb115c2175c84314a6c85
2762bf88e05093071dab3f59e1020127b1135f59
ffc10fdc50a684725ab5d380fd039b7cefd1e559
bb6ade1207d75ebe630e991d8a120ca786b30506
1875eb5085e45bb5654881a0d7240472922201ab
7e4f67a6d6f1fd077ed660e932e7f643ca4e5229
e671fc9581eb49239b9c620499ae28cafa0416cb
b89f5def8d0dced7c93c59a0640fd0e1a399f90d
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
Backed out 16 changesets (bug 1525245) for Android failures. CLOSED TREE Backed out changeset 9f8a1b410320 (bug 1525245) Backed out changeset 0ef284a9a1d5 (bug 1525245) Backed out changeset 835e5f642a03 (bug 1525245) Backed out changeset 362f5a8d033c (bug 1525245) Backed out changeset 9da3ab33cf67 (bug 1525245) Backed out changeset 6aacd2d6e835 (bug 1525245) Backed out changeset 8ff9e8f45e02 (bug 1525245) Backed out changeset 2020227181cc (bug 1525245) Backed out changeset fc3c64c330b9 (bug 1525245) Backed out changeset 2762bf88e050 (bug 1525245) Backed out changeset ffc10fdc50a6 (bug 1525245) Backed out changeset bb6ade1207d7 (bug 1525245) Backed out changeset 1875eb5085e4 (bug 1525245) Backed out changeset 7e4f67a6d6f1 (bug 1525245) Backed out changeset e671fc9581eb (bug 1525245) Backed out changeset b89f5def8d0d (bug 1525245)
browser/components/enterprisepolicies/tests/browser/browser_policy_cookie_settings.js
dom/base/Document.cpp
dom/base/Document.h
dom/base/EventSource.cpp
dom/base/EventSource.h
dom/base/nsContentUtils.cpp
dom/base/nsContentUtils.h
dom/base/nsGlobalWindowInner.cpp
dom/base/nsGlobalWindowOuter.cpp
dom/base/nsSyncLoadService.cpp
dom/base/nsSyncLoadService.h
dom/broadcastchannel/BroadcastChannel.cpp
dom/fetch/Fetch.cpp
dom/fetch/FetchDriver.cpp
dom/fetch/FetchDriver.h
dom/indexedDB/test/mochitest.ini
dom/indexedDB/test/test_third_party.html
dom/indexedDB/test/third_party_window.html
dom/security/nsCSPContext.cpp
dom/serviceworkers/ServiceWorkerPrivate.cpp
dom/serviceworkers/ServiceWorkerScriptCache.cpp
dom/serviceworkers/test/mochitest.ini
dom/serviceworkers/test/test_third_party_iframes.html
dom/serviceworkers/test/window_party_iframes.html
dom/storage/LocalStorageCache.cpp
dom/storage/LocalStorageCache.h
dom/storage/SessionStorage.cpp
dom/storage/SessionStorage.h
dom/storage/SessionStorageCache.cpp
dom/storage/SessionStorageCache.h
dom/storage/Storage.cpp
dom/storage/Storage.h
dom/tests/mochitest/bugs/mochitest.ini
dom/tests/mochitest/bugs/test_bug1171215.html
dom/tests/mochitest/bugs/window_bug1171215.html
dom/tests/mochitest/general/mochitest.ini
dom/tests/mochitest/general/storagePermissionsUtils.js
dom/tests/mochitest/general/test_storagePermissionsAccept.html
dom/tests/mochitest/general/test_storagePermissionsLimitForeign.html
dom/tests/mochitest/general/test_storagePermissionsReject.html
dom/tests/mochitest/general/test_storagePermissionsRejectForeign.html
dom/tests/mochitest/general/window_storagePermissions.html
dom/tests/mochitest/localstorage/frameLocalStorageCookieSettings.html
dom/tests/mochitest/localstorage/mochitest.ini
dom/tests/mochitest/localstorage/test_cookieBlock.html
dom/tests/mochitest/localstorage/test_cookieSession.html
dom/tests/mochitest/localstorage/test_localStorageCookieSettings.html
dom/tests/mochitest/localstorage/test_localStorageSessionPrefOverride.html
dom/tests/mochitest/localstorage/windowProxy.html
dom/tests/mochitest/sessionstorage/mochitest.ini
dom/tests/mochitest/sessionstorage/test_cookieSession.html
dom/webbrowserpersist/nsWebBrowserPersist.cpp
dom/workers/RuntimeService.cpp
dom/workers/ScriptLoader.cpp
dom/workers/ScriptLoader.h
dom/workers/WorkerLoadInfo.h
dom/workers/WorkerPrivate.cpp
dom/workers/WorkerPrivate.h
dom/workers/remoteworkers/RemoteWorkerChild.cpp
dom/workers/test/mochitest.ini
dom/workers/test/sharedWorker_thirdparty_window.html
dom/workers/test/test_sharedWorker_thirdparty.html
dom/xbl/nsXBLService.cpp
dom/xhr/XMLHttpRequest.cpp
dom/xhr/XMLHttpRequestMainThread.cpp
dom/xhr/XMLHttpRequestMainThread.h
dom/xhr/XMLHttpRequestWorker.cpp
dom/xhr/tests/mochitest.ini
dom/xhr/tests/test_worker_xhr_3rdparty.html
dom/xhr/tests/window_worker_xhr_3rdparty.html
dom/xml/nsXMLPrettyPrinter.cpp
dom/xslt/xml/txXMLParser.cpp
dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
extensions/cookie/test/unit/test_cookies_privatebrowsing.js
extensions/cookie/test/unit/test_cookies_thirdparty.js
extensions/cookie/test/unit/test_cookies_thirdparty_nonsecure_session.js
extensions/cookie/test/unit/test_cookies_thirdparty_session.js
extensions/pref/autoconfig/src/nsAutoConfig.cpp
image/imgLoader.cpp
ipc/glue/BackgroundUtils.cpp
js/xpconnect/loader/mozJSComponentLoader.cpp
js/xpconnect/loader/mozJSSubScriptLoader.cpp
layout/style/Loader.cpp
modules/libpref/init/StaticPrefList.h
netwerk/base/LoadInfo.cpp
netwerk/base/LoadInfo.h
netwerk/base/NetworkConnectivityService.cpp
netwerk/base/Predictor.cpp
netwerk/base/nsILoadInfo.idl
netwerk/base/nsIncrementalDownload.cpp
netwerk/base/nsNetUtil.cpp
netwerk/base/nsNetUtil.h
netwerk/base/nsPACMan.cpp
netwerk/cookie/CookieServiceChild.cpp
netwerk/cookie/CookieServiceChild.h
netwerk/cookie/CookieServiceParent.cpp
netwerk/cookie/CookieServiceParent.h
netwerk/cookie/CookieSettings.cpp
netwerk/cookie/CookieSettings.h
netwerk/cookie/PCookieService.ipdl
netwerk/cookie/moz.build
netwerk/cookie/nsCookieService.cpp
netwerk/cookie/nsCookieService.h
netwerk/cookie/nsICookieSettings.idl
netwerk/cookie/test/browser/browser.ini
netwerk/cookie/test/browser/browser_broadcastChannel.js
netwerk/cookie/test/browser/browser_cookies.js
netwerk/cookie/test/browser/browser_domCache.js
netwerk/cookie/test/browser/browser_indexedDB.js
netwerk/cookie/test/browser/browser_serviceWorker.js
netwerk/cookie/test/browser/browser_sharedWorker.js
netwerk/cookie/test/browser/browser_storage.js
netwerk/cookie/test/browser/file_empty.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/dns/TRR.cpp
netwerk/ipc/NeckoChannelParams.ipdlh
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/antitracking/AntiTrackingCommon.cpp
toolkit/components/antitracking/test/browser/browser_storageAccessWithHeuristics.js
toolkit/components/downloads/test/unit/test_DownloadCore.js
toolkit/components/downloads/test/unit/test_DownloadLegacy.js
toolkit/components/url-classifier/nsUrlClassifierDBService.cpp
toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp
toolkit/mozapps/extensions/test/xpinstall/head.js
uriloader/prefetch/nsOfflineCacheUpdate.cpp
uriloader/prefetch/nsPrefetchService.cpp
widget/windows/nsDataObj.cpp
--- a/browser/components/enterprisepolicies/tests/browser/browser_policy_cookie_settings.js
+++ b/browser/components/enterprisepolicies/tests/browser/browser_policy_cookie_settings.js
@@ -8,19 +8,17 @@ 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");
@@ -129,45 +127,42 @@ 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,
       },
     },
   });
 
@@ -176,17 +171,16 @@ 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",
       },
     },
   });
 
@@ -195,17 +189,16 @@ 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",
       },
     },
   });
@@ -215,17 +208,16 @@ 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,
       },
     },
@@ -236,17 +228,16 @@ 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,
       },
     },
   });
 
@@ -255,17 +246,16 @@ 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,
       },
     },
   });
 
@@ -274,17 +264,16 @@ 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,
       },
     },
   });
 
@@ -294,17 +283,16 @@ 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,
       },
     },
   });
@@ -314,17 +302,16 @@ 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/base/Document.cpp
+++ b/dom/base/Document.cpp
@@ -73,17 +73,16 @@
 #include "mozilla/dom/HTMLSharedElement.h"
 #include "mozilla/dom/Navigator.h"
 #include "mozilla/dom/Performance.h"
 #include "mozilla/dom/ServiceWorkerContainer.h"
 #include "mozilla/dom/ScriptLoader.h"
 #include "mozilla/dom/ShadowIncludingTreeIterator.h"
 #include "mozilla/dom/StyleSheetList.h"
 #include "mozilla/dom/SVGUseElement.h"
-#include "mozilla/net/CookieSettings.h"
 #include "nsGenericHTMLElement.h"
 #include "mozilla/dom/CDATASection.h"
 #include "mozilla/dom/ProcessingInstruction.h"
 #include "nsDOMString.h"
 #include "nsNodeUtils.h"
 #include "nsLayoutUtils.h"  // for GetFrameForPoint
 #include "nsIFrame.h"
 #include "nsITabChild.h"
@@ -124,17 +123,16 @@
 #include "nsIPermissionManager.h"
 #include "nsIPrincipal.h"
 #include "ExpandedPrincipal.h"
 #include "mozilla/NullPrincipal.h"
 
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsFocusManager.h"
-#include "nsICookiePermission.h"
 #include "nsICookieService.h"
 
 #include "nsBidiUtils.h"
 
 #include "nsContentCreatorFunctions.h"
 
 #include "nsIScriptContext.h"
 #include "nsBindingManager.h"
@@ -2556,28 +2554,16 @@ nsresult Document::StartDocumentLoad(con
   // the CSP defines frame-ancestors.
   if (!FramingChecker::CheckFrameOptions(aChannel, docShell, NodePrincipal())) {
     MOZ_LOG(gCspPRLog, LogLevel::Debug,
             ("XFO doesn't like frame's ancestry, not loading."));
     // stop!  ERROR page!
     aChannel->Cancel(NS_ERROR_CSP_FRAME_ANCESTOR_VIOLATION);
   }
 
-  // Let's take the CookieSettings from the loadInfo or from the parent
-  // document.
-  if (loadInfo) {
-    rv = loadInfo->GetCookieSettings(getter_AddRefs(mCookieSettings));
-    NS_ENSURE_SUCCESS(rv, rv);
-  } else {
-    nsCOMPtr<Document> parentDocument = GetParentDocument();
-    if (parentDocument) {
-      mCookieSettings = parentDocument->CookieSettings();
-    }
-  }
-
   return NS_OK;
 }
 
 void Document::SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages) {
   for (uint32_t i = 0; i < aMessages.Length(); ++i) {
     nsAutoString messageTag;
     aMessages[i]->GetTag(messageTag);
 
@@ -11800,17 +11786,17 @@ void Document::SetDocTreeHadPlayRevoked(
   }
 }
 
 DocumentAutoplayPolicy Document::AutoplayPolicy() const {
   return AutoplayPolicy::IsAllowedToPlay(*this);
 }
 
 void Document::MaybeAllowStorageForOpenerAfterUserInteraction() {
-  if (mCookieSettings->GetCookieBehavior() !=
+  if (StaticPrefs::network_cookie_cookieBehavior() !=
       nsICookieService::BEHAVIOR_REJECT_TRACKER) {
     return;
   }
 
   // This will probably change for project fission, but currently this document
   // and the opener are on the same process. In the future, we should make this
   // part async.
 
@@ -12316,18 +12302,18 @@ already_AddRefed<mozilla::dom::Promise> 
 
   // Step 2. If the document has a null origin, reject.
   if (NodePrincipal()->GetIsNullPrincipal()) {
     promise->MaybeRejectWithUndefined();
     return promise.forget();
   }
 
   // Only enforce third-party checks when there is a reason to enforce them.
-  if (mCookieSettings->GetCookieBehavior() !=
-      nsICookieService::BEHAVIOR_REJECT_TRACKER) {
+  if (StaticPrefs::network_cookie_cookieBehavior() !=
+      nsICookieService::BEHAVIOR_ACCEPT) {
     // Step 3. If the document's frame is the main frame, resolve.
     if (IsTopLevelContentDocument()) {
       promise->MaybeResolveWithUndefined();
       return promise.forget();
     }
 
     // Step 4. If the sub frame's origin is equal to the main frame's, resolve.
     nsCOMPtr<Document> topLevelDoc = GetTopLevelContentDocument();
@@ -12369,17 +12355,17 @@ already_AddRefed<mozilla::dom::Promise> 
 
   if (nsContentUtils::IsInPrivateBrowsing(this)) {
     // If the document is in PB mode, it doesn't have access to its persistent
     // cookie jar, so reject the promise here.
     promise->MaybeRejectWithUndefined();
     return promise.forget();
   }
 
-  if (mCookieSettings->GetCookieBehavior() ==
+  if (StaticPrefs::network_cookie_cookieBehavior() ==
           nsICookieService::BEHAVIOR_REJECT_TRACKER &&
       inner) {
     // Only do something special for third-party tracking content.
     if (nsContentUtils::StorageDisabledByAntiTracking(this, nullptr)) {
       // Note: If this has returned true, the top-level document is guaranteed
       // to not be on the Content Blocking allow list.
       DebugOnly<bool> isOnAllowList = false;
       // If we have a parent document, it has to be non-private since we
@@ -12627,20 +12613,10 @@ void Document::RecomputeLanguageFromChar
   if (language == mLanguageFromCharset) {
     return;
   }
 
   ResetLangPrefs();
   mLanguageFromCharset = language.forget();
 }
 
-nsICookieSettings* Document::CookieSettings() {
-  // If we are here, this is probably a javascript: URL document. In any case,
-  // we must have a nsCookieSettings. Let's create it.
-  if (!mCookieSettings) {
-    mCookieSettings = net::CookieSettings::Create();
-  }
-
-  return mCookieSettings;
-}
-
 }  // namespace dom
 }  // namespace mozilla
--- a/dom/base/Document.h
+++ b/dom/base/Document.h
@@ -7,18 +7,17 @@
 #define mozilla_dom_Document_h___
 
 #include "mozilla/FlushType.h"  // for enum
 #include "mozilla/Pair.h"       // for Pair
 #include "nsAutoPtr.h"          // for member
 #include "nsCOMArray.h"         // for member
 #include "nsCompatibility.h"    // for member
 #include "nsCOMPtr.h"           // for member
-#include "nsICookieSettings.h"
-#include "nsGkAtoms.h"  // for static class members
+#include "nsGkAtoms.h"          // for static class members
 #include "nsIApplicationCache.h"
 #include "nsIApplicationCacheContainer.h"
 #include "nsIContentViewer.h"
 #include "nsIDOMXULCommandDispatcher.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsILoadContext.h"
 #include "nsILoadGroup.h"  // for member (in nsCOMPtr)
 #include "nsINode.h"       // for base class
@@ -1484,19 +1483,16 @@ class Document : public nsINode,
   // canceled by the URL classifier (Safebrowsing).
   //
   already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
 
   // Helper method that returns true if the document has storage-access sandbox
   // flag.
   bool StorageAccessSandboxed() const;
 
-  // Returns the cookie settings for this and sub contexts.
-  nsICookieSettings* CookieSettings();
-
   // Increments the document generation.
   inline void Changed() { ++mGeneration; }
 
   // Returns the current generation.
   inline int32_t GetGeneration() const { return mGeneration; }
 
   // Adds cached sizes values to aSizes if there's any
   // cached value and if the document generation hasn't
@@ -4689,18 +4685,16 @@ class Document : public nsINode,
   // :-moz-lwtheme-brighttext and :-moz-lwtheme-darktext
   DocumentTheme mDocLWTheme;
 
   // Pres shell resolution saved before entering fullscreen mode.
   float mSavedResolution;
 
   bool mPendingInitialTranslation;
 
-  nsCOMPtr<nsICookieSettings> mCookieSettings;
-
   // Document generation. Gets incremented everytime it changes.
   int32_t mGeneration;
 
   // Cached TabSizes values for the document.
   int32_t mCachedTabSizeGeneration;
   nsTabSizes mCachedTabSizes;
 
  public:
--- a/dom/base/EventSource.cpp
+++ b/dom/base/EventSource.cpp
@@ -77,18 +77,17 @@ class EventSourceImpl final : public nsI
   NS_DECL_NSIOBSERVER
   NS_DECL_NSIREQUESTOBSERVER
   NS_DECL_NSISTREAMLISTENER
   NS_DECL_NSICHANNELEVENTSINK
   NS_DECL_NSIINTERFACEREQUESTOR
   NS_DECL_NSIEVENTTARGET_FULL
   NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
 
-  EventSourceImpl(EventSource* aEventSource,
-                  nsICookieSettings* aCookieSettings);
+  explicit EventSourceImpl(EventSource* aEventSource);
 
   enum { CONNECTING = 0U, OPEN = 1U, CLOSED = 2U };
 
   void Close();
 
   void Init(nsIPrincipal* aPrincipal, const nsAString& aURL, ErrorResult& aRv);
 
   nsresult GetBaseURI(nsIURI** aBaseURI);
@@ -287,18 +286,16 @@ class EventSourceImpl final : public nsI
   // These attributes are used for error reporting. Should only be accessed on
   // target thread
   nsString mScriptFile;
   uint32_t mScriptLine;
   uint32_t mScriptColumn;
   uint64_t mInnerWindowID;
 
  private:
-  nsCOMPtr<nsICookieSettings> mCookieSettings;
-
   // Pointer to the target thread for checking whether we are
   // on the target thread. This is intentionally a non-owning
   // pointer in order not to affect the thread destruction
   // sequence. This pointer must only be compared for equality
   // and must not be dereferenced.
   nsIThread* mTargetThread;
 
   // prevent bad usage
@@ -314,30 +311,28 @@ class EventSourceImpl final : public nsI
   }
 };
 
 NS_IMPL_ISUPPORTS(EventSourceImpl, nsIObserver, nsIStreamListener,
                   nsIRequestObserver, nsIChannelEventSink,
                   nsIInterfaceRequestor, nsISupportsWeakReference,
                   nsIEventTarget, nsIThreadRetargetableStreamListener)
 
-EventSourceImpl::EventSourceImpl(EventSource* aEventSource,
-                                 nsICookieSettings* aCookieSettings)
+EventSourceImpl::EventSourceImpl(EventSource* aEventSource)
     : mEventSource(aEventSource),
       mReconnectionTime(0),
       mStatus(PARSE_STATE_OFF),
       mMutex("EventSourceImpl::mMutex"),
       mFrozen(false),
       mGoingToDispatchAllMessages(false),
       mIsMainThread(NS_IsMainThread()),
       mIsShutDown(false),
       mScriptLine(0),
       mScriptColumn(0),
       mInnerWindowID(0),
-      mCookieSettings(aCookieSettings),
       mTargetThread(NS_GetCurrentThread()) {
   MOZ_ASSERT(mEventSource);
   if (!mIsMainThread) {
     mEventSource->mIsMainThread = false;
   }
   SetReadyState(CONNECTING);
 }
 
@@ -971,30 +966,27 @@ nsresult EventSourceImpl::InitChannelAnd
 
   if (mEventSource->mWithCredentials) {
     securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
   }
 
   nsCOMPtr<nsIChannel> channel;
   // If we have the document, use it
   if (doc) {
-    MOZ_ASSERT(mCookieSettings == doc->CookieSettings());
-
     nsCOMPtr<nsILoadGroup> loadGroup = doc->GetDocumentLoadGroup();
     rv = NS_NewChannel(getter_AddRefs(channel), mSrc, doc, securityFlags,
                        nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE,
                        nullptr,  // aPerformanceStorage
                        loadGroup,
                        nullptr,     // aCallbacks
                        loadFlags);  // aLoadFlags
   } else {
     // otherwise use the principal
     rv = NS_NewChannel(getter_AddRefs(channel), mSrc, mPrincipal, securityFlags,
                        nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE,
-                       mCookieSettings,
                        nullptr,     // aPerformanceStorage
                        nullptr,     // loadGroup
                        nullptr,     // aCallbacks
                        loadFlags);  // aLoadFlags
   }
 
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1780,24 +1772,22 @@ EventSourceImpl::CheckListenerChain() {
   MOZ_ASSERT(NS_IsMainThread(), "Should be on the main thread!");
   return NS_OK;
 }
 ////////////////////////////////////////////////////////////////////////////////
 // EventSource
 ////////////////////////////////////////////////////////////////////////////////
 
 EventSource::EventSource(nsPIDOMWindowInner* aOwnerWindow,
-                         nsICookieSettings* aCookieSettings,
                          bool aWithCredentials)
     : DOMEventTargetHelper(aOwnerWindow),
       mWithCredentials(aWithCredentials),
       mIsMainThread(true),
       mKeepingAlive(false) {
-  MOZ_ASSERT(aCookieSettings);
-  mImpl = new EventSourceImpl(this, aCookieSettings);
+  mImpl = new EventSourceImpl(this);
 }
 
 EventSource::~EventSource() {}
 
 nsresult EventSource::CreateAndDispatchSimpleEvent(const nsAString& aName) {
   RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
   // it doesn't bubble, and it isn't cancelable
   event->InitEvent(aName, false, false);
@@ -1811,34 +1801,18 @@ nsresult EventSource::CreateAndDispatchS
 already_AddRefed<EventSource> EventSource::Constructor(
     const GlobalObject& aGlobal, const nsAString& aURL,
     const EventSourceInit& aEventSourceInitDict, ErrorResult& aRv) {
   nsCOMPtr<nsPIDOMWindowInner> ownerWindow =
       do_QueryInterface(aGlobal.GetAsSupports());
 
   MOZ_ASSERT(!NS_IsMainThread() || ownerWindow);
 
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  if (ownerWindow) {
-    Document* doc = ownerWindow->GetExtantDoc();
-    if (NS_WARN_IF(!doc)) {
-      aRv.Throw(NS_ERROR_FAILURE);
-      return nullptr;
-    }
-
-    cookieSettings = doc->CookieSettings();
-  } else {
-    // Worker side.
-    WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
-    MOZ_ASSERT(workerPrivate);
-    cookieSettings = workerPrivate->CookieSettings();
-  }
-
-  RefPtr<EventSource> eventSource = new EventSource(
-      ownerWindow, cookieSettings, aEventSourceInitDict.mWithCredentials);
+  RefPtr<EventSource> eventSource =
+      new EventSource(ownerWindow, aEventSourceInitDict.mWithCredentials);
   RefPtr<EventSourceImpl> eventSourceImp = eventSource->mImpl;
 
   if (NS_IsMainThread()) {
     // Get principal from document and init EventSourceImpl
     nsCOMPtr<nsIScriptObjectPrincipal> scriptPrincipal =
         do_QueryInterface(aGlobal.GetAsSupports());
     if (!scriptPrincipal) {
       aRv.Throw(NS_ERROR_FAILURE);
--- a/dom/base/EventSource.h
+++ b/dom/base/EventSource.h
@@ -20,17 +20,16 @@
 #include "nsIStreamListener.h"
 #include "nsIChannelEventSink.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsITimer.h"
 #include "nsIHttpChannel.h"
 #include "nsDeque.h"
 
 class nsPIDOMWindowInner;
-class nsICookieSettings;
 
 namespace mozilla {
 
 class ErrorResult;
 
 namespace dom {
 
 struct EventSourceInit;
@@ -76,18 +75,17 @@ class EventSource final : public DOMEven
 
   IMPL_EVENT_HANDLER(open)
   IMPL_EVENT_HANDLER(message)
   IMPL_EVENT_HANDLER(error)
 
   void Close();
 
  private:
-  EventSource(nsPIDOMWindowInner* aOwnerWindow,
-              nsICookieSettings* aCookieSettings, bool aWithCredentials);
+  EventSource(nsPIDOMWindowInner* aOwnerWindow, bool aWithCredentials);
   virtual ~EventSource();
   // prevent bad usage
   EventSource(const EventSource& x) = delete;
   EventSource& operator=(const EventSource& x) = delete;
 
   void AssertIsOnTargetThread() const {
     MOZ_ASSERT(NS_IsMainThread() == mIsMainThread);
   }
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -8221,40 +8221,41 @@ nsContentUtils::StorageAccess nsContentU
 nsContentUtils::StorageAccess nsContentUtils::StorageAllowedForServiceWorker(
     nsIPrincipal* aPrincipal) {
   uint32_t rejectedReason = 0;
   return InternalStorageAllowedCheck(aPrincipal, nullptr, nullptr, nullptr,
                                      rejectedReason);
 }
 
 // static, private
-void nsContentUtils::GetCookieLifetimePolicyFromCookieSettings(
-    nsICookieSettings* aCookieSettings, nsIPrincipal* aPrincipal,
-    uint32_t* aLifetimePolicy) {
+void nsContentUtils::GetCookieLifetimePolicyForPrincipal(
+    nsIPrincipal* aPrincipal, uint32_t* aLifetimePolicy) {
   *aLifetimePolicy = sCookiesLifetimePolicy;
 
-  if (aCookieSettings) {
-    uint32_t cookiePermission = 0;
-    nsresult rv =
-        aCookieSettings->CookiePermission(aPrincipal, &cookiePermission);
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      return;
-    }
-
-    switch (cookiePermission) {
-      case nsICookiePermission::ACCESS_ALLOW:
-        *aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
-        break;
-      case nsICookiePermission::ACCESS_DENY:
-        *aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
-        break;
-      case nsICookiePermission::ACCESS_SESSION:
-        *aLifetimePolicy = nsICookieService::ACCEPT_SESSION;
-        break;
-    }
+  // Any permissions set for the given principal will override our default
+  // settings from preferences.
+  nsCOMPtr<nsIPermissionManager> permissionManager =
+      services::GetPermissionManager();
+  if (!permissionManager) {
+    return;
+  }
+
+  uint32_t perm;
+  permissionManager->TestPermissionFromPrincipal(
+      aPrincipal, NS_LITERAL_CSTRING("cookie"), &perm);
+  switch (perm) {
+    case nsICookiePermission::ACCESS_ALLOW:
+      *aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
+      break;
+    case nsICookiePermission::ACCESS_DENY:
+      *aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
+      break;
+    case nsICookiePermission::ACCESS_SESSION:
+      *aLifetimePolicy = nsICookieService::ACCEPT_SESSION;
+      break;
   }
 }
 
 // static public
 bool nsContentUtils::IsThirdPartyWindowOrChannel(nsPIDOMWindowInner* aWindow,
                                                  nsIChannel* aChannel,
                                                  nsIURI* aURI) {
   MOZ_ASSERT(!aWindow || !aChannel,
@@ -8415,17 +8416,16 @@ bool nsContentUtils::StorageDisabledByAn
 nsContentUtils::StorageAccess nsContentUtils::InternalStorageAllowedCheck(
     nsIPrincipal* aPrincipal, nsPIDOMWindowInner* aWindow, nsIURI* aURI,
     nsIChannel* aChannel, uint32_t& aRejectedReason) {
   MOZ_ASSERT(aPrincipal);
 
   aRejectedReason = 0;
 
   StorageAccess access = StorageAccess::eAllow;
-  nsCOMPtr<nsICookieSettings> cookieSettings;
 
   // We don't allow storage on the null principal, in general. Even if the
   // calling context is chrome.
   if (aPrincipal->GetIsNullPrincipal()) {
     return StorageAccess::eDeny;
   }
 
   if (aWindow) {
@@ -8434,38 +8434,28 @@ nsContentUtils::StorageAccess nsContentU
     if (document && document->GetSandboxFlags() & SANDBOXED_ORIGIN) {
       return StorageAccess::eDeny;
     }
 
     // Check if we are in private browsing, and record that fact
     if (IsInPrivateBrowsing(document)) {
       access = StorageAccess::ePrivateBrowsing;
     }
-
-    if (document) {
-      cookieSettings = document->CookieSettings();
-    }
-  }
-
-  if (aChannel) {
-    nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
-    loadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
   }
 
   uint32_t lifetimePolicy;
 
   // WebExtensions principals always get BEHAVIOR_ACCEPT as cookieBehavior
   // and ACCEPT_NORMALLY as lifetimePolicy (See Bug 1406675 for rationale).
   auto policy = BasePrincipal::Cast(aPrincipal)->AddonPolicy();
 
   if (policy) {
     lifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
   } else {
-    GetCookieLifetimePolicyFromCookieSettings(cookieSettings, aPrincipal,
-                                              &lifetimePolicy);
+    GetCookieLifetimePolicyForPrincipal(aPrincipal, &lifetimePolicy);
   }
 
   // Check if we should only allow storage for the session, and record that fact
   if (lifetimePolicy == nsICookieService::ACCEPT_SESSION) {
     // Storage could be StorageAccess::ePrivateBrowsing or StorageAccess::eAllow
     // so perform a std::min comparison to make sure we preserve
     // ePrivateBrowsing if it has been set.
     access = std::min(StorageAccess::eSessionScoped, access);
--- a/dom/base/nsContentUtils.h
+++ b/dom/base/nsContentUtils.h
@@ -3378,24 +3378,23 @@ class nsContentUtils {
       const nsAttrValue* aAttrVal, mozilla::dom::AutocompleteInfo& aInfo,
       bool aGrantAllValidValue = false);
 
   static bool CallOnAllRemoteChildren(
       mozilla::dom::MessageBroadcaster* aManager,
       CallOnRemoteChildFunction aCallback, void* aArg);
 
   /**
-   * Gets the cookie lifetime policy for a given cookieSettings and a given
-   * principal by checking the permission value.
+   * Gets the current cookie lifetime policy for a given principal by checking
+   * with preferences and the permission manager.
    *
    * Used in the implementation of InternalStorageAllowedCheck.
    */
-  static void GetCookieLifetimePolicyFromCookieSettings(
-      nsICookieSettings* aCookieSettings, nsIPrincipal* aPrincipal,
-      uint32_t* aLifetimePolicy);
+  static void GetCookieLifetimePolicyForPrincipal(nsIPrincipal* aPrincipal,
+                                                  uint32_t* aLifetimePolicy);
 
   /*
    * Checks if storage for a given principal is permitted by the user's
    * preferences. If aWindow is non-null, its principal must be passed as
    * aPrincipal, and the third-party iframe and sandboxing status of the window
    * are also checked.  If aURI is non-null, then it is used as the comparison
    * against aWindow to determine if this is a third-party load.  We also
    * allow a channel instead of the window reference when determining 3rd party
--- a/dom/base/nsGlobalWindowInner.cpp
+++ b/dom/base/nsGlobalWindowInner.cpp
@@ -4260,58 +4260,16 @@ Storage* nsGlobalWindowInner::GetSession
       return nullptr;
     }
 
     if (mDoc->GetSandboxFlags() & SANDBOXED_ORIGIN) {
       aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
       return nullptr;
     }
 
-    uint32_t rejectedReason = 0;
-    nsContentUtils::StorageAccess access =
-        nsContentUtils::StorageAllowedForWindow(this, &rejectedReason);
-
-    // SessionStorage is an ephemeral per-tab per-origin storage that only lives
-    // as long as the tab is open, although it may survive browser restarts
-    // thanks to the session store. So we interpret storage access differently
-    // than we would for persistent per-origin storage like LocalStorage and so
-    // it may be okay to provide SessionStorage even when we receive a value of
-    // eDeny.
-    //
-    // AntiTrackingCommon::IsFirstPartyStorageAccessGranted will return false
-    // for 3 main reasons.
-    //
-    // 1. Cookies are entirely blocked due to a per-origin permission
-    // (nsICookiePermission::ACCESS_DENY for the top-level principal or this
-    // window's principal) or the very broad BEHAVIOR_REJECT. This will return
-    // eDeny with a reason of STATE_COOKIES_BLOCKED_BY_PERMISSION or
-    // STATE_COOKIES_BLOCKED_ALL.
-    //
-    // 2. Third-party cookies are limited via BEHAVIOR_REJECT_FOREIGN and
-    // BEHAVIOR_LIMIT_FOREIGN and this is a third-party window. This will return
-    // eDeny with a reason of STATE_COOKIES_BLOCKED_FOREIGN.
-    //
-    // 3. Tracking protection (BEHAVIOR_REJECT_TRACKER) is in effect and
-    // IsThirdPartyTrackingResourceWindow() returned true and there wasn't a
-    // permission that allows it. This will return ePartitionedOrDeny with a
-    // reason of STATE_COOKIES_BLOCKED_TRACKER.
-    //
-    // In the 1st case, the user has explicitly indicated that they don't want
-    // to allow any storage to the origin or all origins and so we throw an
-    // error and deny access to SessionStorage. In the 2nd case, a legacy
-    // decision reasoned that there's no harm in providing SessionStorage
-    // because the information is not durable and cannot escape the current tab.
-    // The rationale is similar for the 3rd case.
-    if (access == nsContentUtils::StorageAccess::eDeny &&
-        rejectedReason !=
-            nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN) {
-      aError.Throw(NS_ERROR_DOM_SECURITY_ERR);
-      return nullptr;
-    }
-
     nsresult rv;
 
     nsCOMPtr<nsIDOMStorageManager> storageManager =
         do_QueryInterface(docShell, &rv);
     if (NS_FAILED(rv)) {
       aError.Throw(rv);
       return nullptr;
     }
--- a/dom/base/nsGlobalWindowOuter.cpp
+++ b/dom/base/nsGlobalWindowOuter.cpp
@@ -1253,16 +1253,20 @@ nsGlobalWindowOuter::~nsGlobalWindowOute
 
   nsCOMPtr<nsIDeviceSensors> ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID);
   if (ac) ac->RemoveWindowAsListener(this);
 
   nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
   if (obs) {
     obs->RemoveObserver(this, PERM_CHANGE_NOTIFICATION);
   }
+  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
+  if (prefBranch) {
+    prefBranch->RemoveObserver("network.cookie.cookieBehavior", this);
+  }
 
   nsLayoutStatics::Release();
 }
 
 // static
 void nsGlobalWindowOuter::ShutDown() {
   AssertIsOnMainThread();
 
@@ -2282,28 +2286,30 @@ nsresult nsGlobalWindowOuter::SetNewDocu
 
   // If we have a recorded interesting Large-Allocation header status, report it
   // to the newly attached document.
   ReportLargeAllocStatus();
   mLargeAllocStatus = LargeAllocStatus::NONE;
 
   mHasStorageAccess = false;
   nsIURI* uri = aDocument->GetDocumentURI();
-  if (newInnerWindow &&
-      aDocument->CookieSettings()->GetCookieBehavior() ==
-          nsICookieService::BEHAVIOR_REJECT_TRACKER &&
-      nsContentUtils::IsThirdPartyWindowOrChannel(newInnerWindow, nullptr,
-                                                  uri) &&
-      nsContentUtils::IsTrackingResourceWindow(newInnerWindow)) {
-    // Grant storage access by default if the first-party storage access
-    // permission has been granted already.
-    // Don't notify in this case, since we would be notifying the user
-    // needlessly.
-    mHasStorageAccess = AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
-        newInnerWindow, uri, nullptr);
+  if (newInnerWindow) {
+    if (StaticPrefs::network_cookie_cookieBehavior() ==
+            nsICookieService::BEHAVIOR_REJECT_TRACKER &&
+        nsContentUtils::IsThirdPartyWindowOrChannel(newInnerWindow, nullptr,
+                                                    uri) &&
+        nsContentUtils::IsTrackingResourceWindow(newInnerWindow)) {
+      // Grant storage access by default if the first-party storage access
+      // permission has been granted already.
+      // Don't notify in this case, since we would be notifying the user
+      // needlessly.
+      mHasStorageAccess =
+          AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
+              newInnerWindow, uri, nullptr);
+    }
   }
 
   return NS_OK;
 }
 
 void nsGlobalWindowOuter::PreloadLocalStorage() {
   if (!Storage::StoragePrefIsEnabled()) {
     return;
@@ -6933,16 +6939,21 @@ nsGlobalWindowOuter::GetInterface(const 
 //*****************************************************************************
 // nsGlobalWindowOuter::nsIObserver
 //*****************************************************************************
 
 NS_IMETHODIMP
 nsGlobalWindowOuter::Observe(nsISupports* aSupports, const char* aTopic,
                              const char16_t* aData) {
   if (!nsCRT::strcmp(aTopic, PERM_CHANGE_NOTIFICATION)) {
+    if (!nsCRT::strcmp(aData, u"cleared") && !aSupports) {
+      // All permissions have been cleared.
+      mHasStorageAccess = false;
+      return NS_OK;
+    }
     nsCOMPtr<nsIPermission> permission = do_QueryInterface(aSupports);
     if (!permission) {
       return NS_OK;
     }
     nsIPrincipal* principal = GetPrincipal();
     if (!principal) {
       return NS_OK;
     }
@@ -6964,16 +6975,20 @@ nsGlobalWindowOuter::Observe(nsISupports
            expireTime >= PR_Now() / 1000) ||
           (expireType == nsIPermissionManager::EXPIRE_SESSION &&
            expireTime != 0)) {
         // Permission hasn't expired yet.
         mHasStorageAccess = true;
         return NS_OK;
       }
     }
+  } else if (!nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
+    // Reset the storage access permission when our cookie policy changes.
+    mHasStorageAccess = false;
+    return NS_OK;
   }
   return NS_OK;
 }
 
 bool nsGlobalWindowOuter::IsSuspended() const {
   MOZ_ASSERT(NS_IsMainThread());
   // No inner means we are effectively suspended
   if (!mInnerWindow) {
@@ -7761,16 +7776,20 @@ already_AddRefed<nsGlobalWindowOuter> ns
   if (obs) {
     // Delay calling AddObserver until we hit the event loop, in case we may be
     // in the middle of modifying the observer list somehow.
     NS_DispatchToMainThread(
         NS_NewRunnableFunction("PermChangeDelayRunnable", [obs, window] {
           obs->AddObserver(window, PERM_CHANGE_NOTIFICATION, true);
         }));
   }
+  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
+  if (prefBranch) {
+    prefBranch->AddObserver("network.cookie.cookieBehavior", window, true);
+  }
   return window.forget();
 }
 
 nsIURI* nsPIDOMWindowOuter::GetDocumentURI() const {
   return mDoc ? mDoc->GetDocumentURI() : mDocumentURI.get();
 }
 
 void nsPIDOMWindowOuter::MaybeCreateDoc() {
--- a/dom/base/nsSyncLoadService.cpp
+++ b/dom/base/nsSyncLoadService.cpp
@@ -274,24 +274,23 @@ NS_IMETHODIMP
 nsSyncLoader::GetInterface(const nsIID &aIID, void **aResult) {
   return QueryInterface(aIID, aResult);
 }
 
 /* static */
 nsresult nsSyncLoadService::LoadDocument(
     nsIURI *aURI, nsContentPolicyType aContentPolicyType,
     nsIPrincipal *aLoaderPrincipal, nsSecurityFlags aSecurityFlags,
-    nsILoadGroup *aLoadGroup, nsICookieSettings *aCookieSettings,
-    bool aForceToXML, ReferrerPolicy aReferrerPolicy, Document **aResult) {
+    nsILoadGroup *aLoadGroup, bool aForceToXML, ReferrerPolicy aReferrerPolicy,
+    Document **aResult) {
   nsCOMPtr<nsIChannel> channel;
-  nsresult rv =
-      NS_NewChannel(getter_AddRefs(channel), aURI, aLoaderPrincipal,
-                    aSecurityFlags, aContentPolicyType, aCookieSettings,
-                    nullptr,  // PerformanceStorage
-                    aLoadGroup);
+  nsresult rv = NS_NewChannel(getter_AddRefs(channel), aURI, aLoaderPrincipal,
+                              aSecurityFlags, aContentPolicyType,
+                              nullptr,  // PerformanceStorage
+                              aLoadGroup);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!aForceToXML) {
     channel->SetContentType(NS_LITERAL_CSTRING("text/xml"));
   }
 
   bool isChrome = false, isResource = false;
   // if the load needs to enforce CORS, then force the load to be async
--- a/dom/base/nsSyncLoadService.h
+++ b/dom/base/nsSyncLoadService.h
@@ -10,17 +10,16 @@
  */
 
 #ifndef nsSyncLoadService_h__
 #define nsSyncLoadService_h__
 
 #include "nscore.h"
 #include "mozilla/net/ReferrerPolicy.h"
 
-class nsICookieSettings;
 class nsIInputStream;
 class nsILoadGroup;
 class nsIStreamListener;
 class nsIURI;
 class nsIPrincipal;
 class nsIChannel;
 
 namespace mozilla {
@@ -40,22 +39,23 @@ class nsSyncLoadService {
    *                         checks and referrer header.
    * @param aSecurityFlags securityFlags to be set on the channel
    * @param aLoadGroup The loadgroup to use for loading the document.
    * @param aForceToXML Whether to parse the document as XML, regardless of
    *                    content type.
    * @param referrerPolicy Referrer policy.
    * @param aResult [out] The document loaded from the URI.
    */
-  static nsresult LoadDocument(
-      nsIURI* aURI, nsContentPolicyType aContentPolicyType,
-      nsIPrincipal* aLoaderPrincipal, nsSecurityFlags aSecurityFlags,
-      nsILoadGroup* aLoadGroup, nsICookieSettings* aCookieSettings,
-      bool aForceToXML, mozilla::net::ReferrerPolicy aReferrerPolicy,
-      mozilla::dom::Document** aResult);
+  static nsresult LoadDocument(nsIURI* aURI,
+                               nsContentPolicyType aContentPolicyType,
+                               nsIPrincipal* aLoaderPrincipal,
+                               nsSecurityFlags aSecurityFlags,
+                               nsILoadGroup* aLoadGroup, bool aForceToXML,
+                               mozilla::net::ReferrerPolicy aReferrerPolicy,
+                               mozilla::dom::Document** aResult);
 
   /**
    * Read input stream aIn in chunks and deliver synchronously to aListener.
    *
    * @param aIn The stream to be read. The ownership of this stream is taken.
    * @param aListener The listener that will receive
    *                  OnStartRequest/OnDataAvailable/OnStopRequest
    *                  notifications.
--- a/dom/broadcastchannel/BroadcastChannel.cpp
+++ b/dom/broadcastchannel/BroadcastChannel.cpp
@@ -62,23 +62,25 @@ nsIPrincipal* GetPrincipalFromThreadSafe
   }
 
   return wp->GetPrincipal();
 }
 
 class InitializeRunnable final : public WorkerMainThreadRunnable {
  public:
   InitializeRunnable(ThreadSafeWorkerRef* aWorkerRef, nsACString& aOrigin,
-                     PrincipalInfo& aPrincipalInfo, ErrorResult& aRv)
+                     PrincipalInfo& aPrincipalInfo, bool* aThirdPartyWindow,
+                     ErrorResult& aRv)
       : WorkerMainThreadRunnable(
             aWorkerRef->Private(),
             NS_LITERAL_CSTRING("BroadcastChannel :: Initialize")),
         mWorkerRef(aWorkerRef),
         mOrigin(aOrigin),
         mPrincipalInfo(aPrincipalInfo),
+        mThirdPartyWindow(aThirdPartyWindow),
         mRv(aRv) {
     MOZ_ASSERT(mWorkerRef);
   }
 
   bool MainThreadRun() override {
     MOZ_ASSERT(NS_IsMainThread());
 
     nsIPrincipal* principal = GetPrincipalFromThreadSafeWorkerRef(mWorkerRef);
@@ -104,23 +106,27 @@ class InitializeRunnable final : public 
     }
 
     // Window doesn't exist for some kind of workers (eg: SharedWorkers)
     nsPIDOMWindowInner* window = wp->GetWindow();
     if (!window) {
       return true;
     }
 
+    *mThirdPartyWindow =
+        nsContentUtils::IsThirdPartyWindowOrChannel(window, nullptr, nullptr);
+
     return true;
   }
 
  private:
   RefPtr<ThreadSafeWorkerRef> mWorkerRef;
   nsACString& mOrigin;
   PrincipalInfo& mPrincipalInfo;
+  bool* mThirdPartyWindow;
   ErrorResult& mRv;
 };
 
 class CloseRunnable final : public nsIRunnable, public nsICancelableRunnable {
  public:
   NS_DECL_ISUPPORTS
 
   explicit CloseRunnable(BroadcastChannel* aBC) : mBC(aBC) { MOZ_ASSERT(mBC); }
@@ -237,33 +243,32 @@ already_AddRefed<BroadcastChannel> Broad
     }
 
     nsIPrincipal* principal = incumbent->PrincipalOrNull();
     if (!principal) {
       aRv.Throw(NS_ERROR_UNEXPECTED);
       return nullptr;
     }
 
-    // We want to allow opaque origins.
-    if (!principal->GetIsNullPrincipal() &&
-        nsContentUtils::StorageAllowedForWindow(window) <=
-            nsContentUtils::StorageAccess::eDeny) {
-      aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
-      return nullptr;
-    }
-
     aRv = principal->GetOrigin(origin);
     if (NS_WARN_IF(aRv.Failed())) {
       return nullptr;
     }
 
     aRv = PrincipalToPrincipalInfo(principal, &principalInfo);
     if (NS_WARN_IF(aRv.Failed())) {
       return nullptr;
     }
+
+    if (nsContentUtils::IsThirdPartyWindowOrChannel(window, nullptr, nullptr) &&
+        nsContentUtils::StorageAllowedForWindow(window) !=
+            nsContentUtils::StorageAccess::eAllow) {
+      aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
+      return nullptr;
+    }
   } else {
     JSContext* cx = aGlobal.Context();
 
     WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(cx);
     MOZ_ASSERT(workerPrivate);
 
     RefPtr<StrongWorkerRef> workerRef = StrongWorkerRef::Create(
         workerPrivate, "BroadcastChannel", [bc]() { bc->Shutdown(); });
@@ -271,25 +276,26 @@ already_AddRefed<BroadcastChannel> Broad
     // object.
     if (NS_WARN_IF(!workerRef)) {
       aRv.Throw(NS_ERROR_FAILURE);
       return nullptr;
     }
 
     RefPtr<ThreadSafeWorkerRef> tsr = new ThreadSafeWorkerRef(workerRef);
 
-    RefPtr<InitializeRunnable> runnable =
-        new InitializeRunnable(tsr, origin, principalInfo, aRv);
+    bool thirdPartyWindow = false;
+
+    RefPtr<InitializeRunnable> runnable = new InitializeRunnable(
+        tsr, origin, principalInfo, &thirdPartyWindow, aRv);
     runnable->Dispatch(Canceling, aRv);
     if (aRv.Failed()) {
       return nullptr;
     }
 
-    if (principalInfo.type() != PrincipalInfo::TNullPrincipalInfo &&
-        !workerPrivate->IsStorageAllowed()) {
+    if (thirdPartyWindow && !workerPrivate->IsStorageAllowed()) {
       aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
       return nullptr;
     }
 
     bc->mWorkerRef = std::move(workerRef);
   }
 
   // Register this component to PBackground.
--- a/dom/fetch/Fetch.cpp
+++ b/dom/fetch/Fetch.cpp
@@ -33,17 +33,16 @@
 #include "mozilla/dom/MutableBlobStreamListener.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/PromiseWorkerProxy.h"
 #include "mozilla/dom/RemoteWorkerChild.h"
 #include "mozilla/dom/Request.h"
 #include "mozilla/dom/Response.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "mozilla/dom/URLSearchParams.h"
-#include "mozilla/net/CookieSettings.h"
 #include "mozilla/Telemetry.h"
 
 #include "BodyExtractor.h"
 #include "EmptyBody.h"
 #include "FetchObserver.h"
 #include "InternalRequest.h"
 #include "InternalResponse.h"
 
@@ -385,17 +384,16 @@ class MainThreadFetchRunnable : public R
       nsCOMPtr<nsIPrincipal> principal = workerPrivate->GetPrincipal();
       MOZ_ASSERT(principal);
       nsCOMPtr<nsILoadGroup> loadGroup = workerPrivate->GetLoadGroup();
       MOZ_ASSERT(loadGroup);
       // We don't track if a worker is spawned from a tracking script for now,
       // so pass false as the last argument to FetchDriver().
       fetch = new FetchDriver(mRequest, principal, loadGroup,
                               workerPrivate->MainThreadEventTarget(),
-                              workerPrivate->CookieSettings(),
                               workerPrivate->GetPerformanceStorage(), false);
       nsAutoCString spec;
       if (proxy->GetWorkerPrivate()->GetBaseURI()) {
         proxy->GetWorkerPrivate()->GetBaseURI()->GetAsciiSpec(spec);
       }
       fetch->SetWorkerScript(spec);
 
       fetch->SetClientInfo(mClientInfo);
@@ -459,55 +457,51 @@ already_AddRefed<Promise> FetchRequest(n
     observer = new FetchObserver(aGlobal, signalImpl);
     aInit.mObserve.Value().HandleEvent(*observer);
   }
 
   if (NS_IsMainThread()) {
     nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(aGlobal);
     nsCOMPtr<Document> doc;
     nsCOMPtr<nsILoadGroup> loadGroup;
-    nsCOMPtr<nsICookieSettings> cookieSettings;
     nsIPrincipal* principal;
     bool isTrackingFetch = false;
     if (window) {
       doc = window->GetExtantDoc();
       if (!doc) {
         aRv.Throw(NS_ERROR_FAILURE);
         return nullptr;
       }
       principal = doc->NodePrincipal();
       loadGroup = doc->GetDocumentLoadGroup();
-      cookieSettings = doc->CookieSettings();
 
       nsAutoCString fileNameString;
       if (nsJSUtils::GetCallingLocation(cx, fileNameString)) {
         isTrackingFetch = doc->IsScriptTracking(fileNameString);
       }
     } else {
       principal = aGlobal->PrincipalOrNull();
       if (NS_WARN_IF(!principal)) {
         aRv.Throw(NS_ERROR_FAILURE);
         return nullptr;
       }
       nsresult rv = NS_NewLoadGroup(getter_AddRefs(loadGroup), principal);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         aRv.Throw(rv);
         return nullptr;
       }
-
-      cookieSettings = mozilla::net::CookieSettings::Create();
     }
 
     Telemetry::Accumulate(Telemetry::FETCH_IS_MAINTHREAD, 1);
 
     RefPtr<MainThreadFetchResolver> resolver = new MainThreadFetchResolver(
         p, observer, signalImpl, request->MozErrors());
     RefPtr<FetchDriver> fetch = new FetchDriver(
         r, principal, loadGroup, aGlobal->EventTargetFor(TaskCategory::Other),
-        cookieSettings, nullptr,  // PerformanceStorage
+        nullptr,  // PerformanceStorage
         isTrackingFetch);
     fetch->SetDocument(doc);
     resolver->SetLoadGroup(loadGroup);
     aRv = fetch->Fetch(signalImpl, resolver);
     if (NS_WARN_IF(aRv.Failed())) {
       return nullptr;
     }
   } else {
--- a/dom/fetch/FetchDriver.cpp
+++ b/dom/fetch/FetchDriver.cpp
@@ -318,24 +318,22 @@ AlternativeDataStreamListener::CheckList
 //-----------------------------------------------------------------------------
 
 NS_IMPL_ISUPPORTS(FetchDriver, nsIStreamListener, nsIChannelEventSink,
                   nsIInterfaceRequestor, nsIThreadRetargetableStreamListener)
 
 FetchDriver::FetchDriver(InternalRequest* aRequest, nsIPrincipal* aPrincipal,
                          nsILoadGroup* aLoadGroup,
                          nsIEventTarget* aMainThreadEventTarget,
-                         nsICookieSettings* aCookieSettings,
                          PerformanceStorage* aPerformanceStorage,
                          bool aIsTrackingFetch)
     : mPrincipal(aPrincipal),
       mLoadGroup(aLoadGroup),
       mRequest(aRequest),
       mMainThreadEventTarget(aMainThreadEventTarget),
-      mCookieSettings(aCookieSettings),
       mPerformanceStorage(aPerformanceStorage),
       mNeedToObserveOnDataAvailable(false),
       mIsTrackingFetch(aIsTrackingFetch),
       mOnStopRequestCalled(false)
 #ifdef DEBUG
       ,
       mResponseAvailableCalled(false),
       mFetchCalled(false)
@@ -506,34 +504,32 @@ nsresult FetchDriver::HttpFetch(
   // information from the InternalRequest. This is an implementation detail.
   MOZ_ASSERT(mLoadGroup);
   nsCOMPtr<nsIChannel> chan;
 
   nsLoadFlags loadFlags =
       nsIRequest::LOAD_BACKGROUND | bypassFlag | nsIChannel::LOAD_CLASSIFY_URI;
   if (mDocument) {
     MOZ_ASSERT(mDocument->NodePrincipal() == mPrincipal);
-    MOZ_ASSERT(mDocument->CookieSettings() == mCookieSettings);
     rv = NS_NewChannel(getter_AddRefs(chan), uri, mDocument, secFlags,
                        mRequest->ContentPolicyType(),
                        nullptr,             /* aPerformanceStorage */
                        mLoadGroup, nullptr, /* aCallbacks */
                        loadFlags, ios);
   } else if (mClientInfo.isSome()) {
-    rv = NS_NewChannel(getter_AddRefs(chan), uri, mPrincipal, mClientInfo.ref(),
-                       mController, secFlags, mRequest->ContentPolicyType(),
-                       mCookieSettings, mPerformanceStorage, mLoadGroup,
-                       nullptr, /* aCallbacks */
-                       loadFlags, ios);
-  } else {
     rv =
-        NS_NewChannel(getter_AddRefs(chan), uri, mPrincipal, secFlags,
-                      mRequest->ContentPolicyType(), mCookieSettings,
+        NS_NewChannel(getter_AddRefs(chan), uri, mPrincipal, mClientInfo.ref(),
+                      mController, secFlags, mRequest->ContentPolicyType(),
                       mPerformanceStorage, mLoadGroup, nullptr, /* aCallbacks */
                       loadFlags, ios);
+  } else {
+    rv = NS_NewChannel(getter_AddRefs(chan), uri, mPrincipal, secFlags,
+                       mRequest->ContentPolicyType(), mPerformanceStorage,
+                       mLoadGroup, nullptr, /* aCallbacks */
+                       loadFlags, ios);
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (mCSPEventListener) {
     nsCOMPtr<nsILoadInfo> loadInfo = chan->LoadInfo();
     rv = loadInfo->SetCspEventListener(mCSPEventListener);
     NS_ENSURE_SUCCESS(rv, rv);
   }
--- a/dom/fetch/FetchDriver.h
+++ b/dom/fetch/FetchDriver.h
@@ -16,17 +16,16 @@
 #include "mozilla/dom/AbortSignal.h"
 #include "mozilla/dom/SRIMetadata.h"
 #include "mozilla/RefPtr.h"
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/net/ReferrerPolicy.h"
 
 class nsIConsoleReportCollector;
-class nsICookieSettings;
 class nsICSPEventListener;
 class nsIEventTarget;
 class nsIOutputStream;
 class nsILoadGroup;
 class nsIPrincipal;
 
 namespace mozilla {
 namespace dom {
@@ -97,17 +96,16 @@ class FetchDriver final : public nsIStre
   NS_DECL_NSIREQUESTOBSERVER
   NS_DECL_NSISTREAMLISTENER
   NS_DECL_NSICHANNELEVENTSINK
   NS_DECL_NSIINTERFACEREQUESTOR
   NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
 
   FetchDriver(InternalRequest* aRequest, nsIPrincipal* aPrincipal,
               nsILoadGroup* aLoadGroup, nsIEventTarget* aMainThreadEventTarget,
-              nsICookieSettings* aCookieSettings,
               PerformanceStorage* aPerformanceStorage, bool aIsTrackingFetch);
 
   nsresult Fetch(AbortSignalImpl* aSignalImpl, FetchDriverObserver* aObserver);
 
   void SetDocument(Document* aDocument);
 
   void SetCSPEventListener(nsICSPEventListener* aCSPEventListener);
 
@@ -133,18 +131,16 @@ class FetchDriver final : public nsIStre
   RefPtr<Document> mDocument;
   nsCOMPtr<nsICSPEventListener> mCSPEventListener;
   Maybe<ClientInfo> mClientInfo;
   Maybe<ServiceWorkerDescriptor> mController;
   nsCOMPtr<nsIChannel> mChannel;
   nsAutoPtr<SRICheckDataVerifier> mSRIDataVerifier;
   nsCOMPtr<nsIEventTarget> mMainThreadEventTarget;
 
-  nsCOMPtr<nsICookieSettings> mCookieSettings;
-
   // This is set only when Fetch is used in workers.
   RefPtr<PerformanceStorage> mPerformanceStorage;
 
   SRIMetadata mSRIMetadata;
   nsCString mWorkerScript;
 
   // This is written once in OnStartRequest on the main thread and then
   // written/read in OnDataAvailable() on any thread.  Necko guarantees
--- a/dom/indexedDB/test/mochitest.ini
+++ b/dom/indexedDB/test/mochitest.ini
@@ -11,16 +11,18 @@ support-files =
   blob_worker_crash_iframe.html
   !/dom/events/test/event_leak_utils.js
   error_events_abort_transactions_iframe.html
   event_propagation_iframe.html
   exceptions_in_events_iframe.html
   file.js
   helpers.js
   leaving_page_iframe.html
+  third_party_iframe1.html
+  third_party_iframe2.html
   unit/test_abort_deleted_index.js
   unit/test_abort_deleted_objectStore.js
   unit/test_add_put.js
   unit/test_add_twice_failure.js
   unit/test_advance.js
   unit/test_autoIncrement.js
   unit/test_autoIncrement_indexes.js
   unit/test_blob_file_backed.js
@@ -249,20 +251,16 @@ skip-if = verify
 [test_setVersion_exclusion.html]
 [test_setVersion_throw.html]
 [test_storage_manager_estimate.html]
 scheme=https
 [test_success_events_after_abort.html]
 [test_table_locks.html]
 [test_table_rollback.html]
 [test_third_party.html]
-support-files =
-  third_party_window.html
-  third_party_iframe1.html
-  third_party_iframe2.html
 skip-if = (os == 'android' && debug) # Bug 1311590
 [test_traffic_jam.html]
 [test_transaction_abort.html]
 [test_transaction_abort_hang.html]
 [test_transaction_duplicate_store_names.html]
 [test_transaction_error.html]
 [test_transaction_lifetimes.html]
 [test_transaction_lifetimes_nested.html]
--- a/dom/indexedDB/test/test_third_party.html
+++ b/dom/indexedDB/test/test_third_party.html
@@ -41,63 +41,66 @@
       window.location.pathname.replace("test_third_party.html",
                                        "third_party_iframe1.html");
     const iframe2URL =
       "http://" + window.location.host +
       window.location.pathname.replace("test_third_party.html",
                                        "third_party_iframe2.html");
 
     let testIndex = 0;
-    let openedWindow;
+    let testRunning = false;
+
+    function iframeLoaded() {
+      let message = { source: "parent", href: iframe2URL };
+      let iframe = document.getElementById("iframe1");
+      iframe.contentWindow.postMessage(message.toSource(), "*");
+    }
 
-    // Cookie preference changes are only applied to top-level tabs/windows
-    // when they are loaded. We need a window-proxy to continue the test.
-    function openWindow() {
+    function setiframe() {
+      let iframe = document.getElementById("iframe1");
+
+      if (!testRunning) {
+        testRunning = true;
+        iframe.addEventListener("load", iframeLoaded);
+      }
       SpecialPowers.pushPrefEnv({
         "set": [
           ["network.cookie.cookieBehavior", testData[testIndex].cookieBehavior],
         ],
       }, () => {
-        openedWindow = window.open("third_party_window.html");
-        openedWindow.onload = _ => {
-          openedWindow.postMessage({
-            source: "parent",
-            href: iframe2URL,
-            iframeUrl: testData[testIndex].host + iframe1Path,
-          }, "*");
-        };
+        iframe.src = testData[testIndex].host + iframe1Path;
       });
+      // SpecialPowers.setIntPref("network.cookie.cookieBehavior", testData[testIndex].cookieBehavior);
     }
 
     function messageListener(event) {
       // eslint-disable-next-line no-eval
       let message = eval(event.data);
 
       is(message.source, "iframe", "Good source");
       is(message.result, testData[testIndex].expectedResult, "Good result");
 
-      openedWindow.close();
-
       if (testIndex < testData.length - 1) {
         testIndex++;
-        openWindow();
+        setiframe();
         return;
       }
 
       SimpleTest.finish();
     }
 
     function runTest() {
       SimpleTest.waitForExplicitFinish();
 
       SpecialPowers.addPermission("indexedDB", true, document);
 
       window.addEventListener("message", messageListener);
-      openWindow();
+      setiframe();
     }
   </script>
 
 </head>
 
 <body onload="runTest();">
+  <iframe id="iframe1"></iframe>
 </body>
 
 </html>
deleted file mode 100644
--- a/dom/indexedDB/test/third_party_window.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<!--
-  Any copyright is dedicated to the Public Domain.
-  http://creativecommons.org/publicdomain/zero/1.0/
--->
-<html>
-<head>
-  <title>Indexed Database Test</title>
-  <script type="text/javascript">
-    let init = false;
-    onmessage = evt => {
-      if (!init) {
-        init = true;
-
-        let iframe = document.getElementById("iframe1");
-        iframe.src = evt.data.iframeUrl;
-
-        iframe.addEventListener("load", e => {
-          iframe.contentWindow.postMessage(evt.data.toSource(), "*");
-        });
-
-        return;
-      }
-
-      opener.postMessage(evt.data, "*");
-    };
-  </script>
-</head>
-
-<body>
-  <iframe id="iframe1"></iframe>
-</body>
-
-</html>
--- a/dom/security/nsCSPContext.cpp
+++ b/dom/security/nsCSPContext.cpp
@@ -1011,17 +1011,16 @@ nsresult nsCSPContext::SendReports(
                          nullptr,  // aLoadGroup
                          nullptr,  // aCallbacks
                          loadFlags);
     } else {
       rv = NS_NewChannel(getter_AddRefs(reportChannel), reportURI,
                          mLoadingPrincipal,
                          nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                          nsIContentPolicy::TYPE_CSP_REPORT,
-                         nullptr,  // nsICookieSettings
                          nullptr,  // PerformanceStorage
                          nullptr,  // aLoadGroup
                          nullptr,  // aCallbacks
                          loadFlags);
     }
 
     if (NS_FAILED(rv)) {
       CSPCONTEXTLOG(("Could not create new channel for report URI %s",
--- a/dom/serviceworkers/ServiceWorkerPrivate.cpp
+++ b/dom/serviceworkers/ServiceWorkerPrivate.cpp
@@ -35,17 +35,16 @@
 #include "mozilla/dom/PromiseNativeHandler.h"
 #include "mozilla/dom/PushEventBinding.h"
 #include "mozilla/dom/RequestBinding.h"
 #include "mozilla/dom/WorkerDebugger.h"
 #include "mozilla/dom/WorkerRef.h"
 #include "mozilla/dom/WorkerRunnable.h"
 #include "mozilla/dom/WorkerScope.h"
 #include "mozilla/dom/ipc/StructuredCloneData.h"
-#include "mozilla/net/CookieSettings.h"
 #include "mozilla/net/NeckoChannelParams.h"
 #include "mozilla/StaticPrefs.h"
 #include "mozilla/Unused.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 namespace mozilla {
@@ -1723,20 +1722,16 @@ nsresult ServiceWorkerPrivate::SpawnWork
     return NS_ERROR_FAILURE;
   }
   info.mLoadingPrincipal = info.mPrincipal;
 
   nsContentUtils::StorageAccess access =
       nsContentUtils::StorageAllowedForServiceWorker(info.mPrincipal);
   info.mStorageAllowed =
       access > nsContentUtils::StorageAccess::ePrivateBrowsing;
-
-  info.mCookieSettings = mozilla::net::CookieSettings::Create();
-  MOZ_ASSERT(info.mCookieSettings);
-
   info.mOriginAttributes = mInfo->GetOriginAttributes();
 
   // Verify that we don't have any CSP on pristine principal.
 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
   nsCOMPtr<nsIContentSecurityPolicy> csp;
   Unused << info.mPrincipal->GetCsp(getter_AddRefs(csp));
   MOZ_DIAGNOSTIC_ASSERT(!csp);
 #endif
--- a/dom/serviceworkers/ServiceWorkerScriptCache.cpp
+++ b/dom/serviceworkers/ServiceWorkerScriptCache.cpp
@@ -11,17 +11,16 @@
 #include "mozilla/dom/cache/CacheStorage.h"
 #include "mozilla/dom/cache/Cache.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/PromiseWorkerProxy.h"
 #include "mozilla/dom/ScriptLoader.h"
 #include "mozilla/dom/WorkerCommon.h"
 #include "mozilla/ipc/BackgroundUtils.h"
 #include "mozilla/ipc/PBackgroundSharedTypes.h"
-#include "mozilla/net/CookieSettings.h"
 #include "nsICacheInfoChannel.h"
 #include "nsIHttpChannelInternal.h"
 #include "nsIStreamLoader.h"
 #include "nsIThreadRetargetableRequest.h"
 
 #include "nsIInputStreamPump.h"
 #include "nsIPrincipal.h"
 #include "nsIScriptError.h"
@@ -653,27 +652,22 @@ nsresult CompareNetwork::Initialize(nsIP
   uint32_t secFlags = mIsMainScript
                           ? nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED
                           : nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS;
 
   nsContentPolicyType contentPolicyType =
       mIsMainScript ? nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER
                     : nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS;
 
-  // Create a new cookieSettings.
-  nsCOMPtr<nsICookieSettings> cookieSettings =
-      mozilla::net::CookieSettings::Create();
-
   // Note that because there is no "serviceworker" RequestContext type, we can
   // use the TYPE_INTERNAL_SCRIPT content policy types when loading a service
   // worker.
   rv = NS_NewChannel(getter_AddRefs(mChannel), uri, aPrincipal, secFlags,
-                     contentPolicyType, cookieSettings,
-                     nullptr /* aPerformanceStorage */, loadGroup,
-                     nullptr /* aCallbacks */, mLoadFlags);
+                     contentPolicyType, nullptr, /* aPerformanceStorage */
+                     loadGroup, nullptr /* aCallbacks */, mLoadFlags);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel);
   if (httpChannel) {
     // Spec says no redirects allowed for top-level SW scripts.
     if (mIsMainScript) {
--- a/dom/serviceworkers/test/mochitest.ini
+++ b/dom/serviceworkers/test/mochitest.ini
@@ -303,18 +303,16 @@ skip-if = serviceworker_e10s
 [test_serviceworker.html]
 [test_service_worker_allowed.html]
 [test_serviceworker_header.html]
 [test_serviceworker_interfaces.html]
 [test_serviceworker_not_sharedworker.html]
 [test_skip_waiting.html]
 [test_strict_mode_warning.html]
 [test_third_party_iframes.html]
-support-files =
-  window_party_iframes.html
 [test_unregister.html]
 [test_unresolved_fetch_interception.html]
 skip-if = verify || serviceworker_e10s
 [test_workerUnregister.html]
 [test_workerUpdate.html]
 [test_workerupdatefoundevent.html]
 [test_xslt.html]
 [test_async_waituntil.html]
--- a/dom/serviceworkers/test/test_third_party_iframes.html
+++ b/dom/serviceworkers/test/test_third_party_iframes.html
@@ -6,16 +6,21 @@
 <html>
 <head>
   <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
   <title>Bug 1152899 - Disallow the interception of third-party iframes using service workers when the third-party cookie preference is set</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
+<p id="display"></p>
+<div id="content" style="display: none">
+<iframe></iframe>
+</div>
+<pre id="test"></pre>
 <script class="testbody" type="text/javascript">
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.requestLongerTimeout(2);
 
 let index = 0;
 function next() {
   info("Step " + index);
@@ -29,17 +34,16 @@ function next() {
   } catch(ex) {
     ok(false, "Caught exception", ex);
   }
 }
 
 onload = next;
 
 let iframe;
-let proxyWindow;
 let basePath = "/tests/dom/serviceworkers/test/thirdparty/";
 let origin = window.location.protocol + "//" + window.location.host;
 let thirdPartyOrigin = "https://example.com";
 
 function testIframeLoaded() {
   ok(true, "Iframe loaded");
   iframe.removeEventListener("load", testIframeLoaded);
   let message = {
@@ -53,36 +57,32 @@ function loadThirdPartyIframe() {
   let message = {
     source: "parent",
     href: thirdPartyOrigin + basePath + "iframe2.html"
   }
   iframe.contentWindow.postMessage(message.toSource(), "*");
 }
 
 function runTest(aExpectedResponses) {
-  // Let's use a proxy window to have the new cookie policy applied.
-  proxyWindow = window.open("window_party_iframes.html");
-  proxyWindow.onload = _ => {
-    iframe = proxyWindow.document.querySelector("iframe");
-    iframe.src = thirdPartyOrigin + basePath + "register.html";
-    let responsesIndex = 0;
-    window.onmessage = function(e) {
-      let status = e.data.status;
-      let expected = aExpectedResponses[responsesIndex];
-      if (status == expected.status) {
-        ok(true, "Received expected " + expected.status);
-        if (expected.next) {
-          expected.next();
-        }
-      } else {
-        ok(false, "Expected " + expected.status + " got " + status);
+  iframe = document.querySelector("iframe");
+  iframe.src = thirdPartyOrigin + basePath + "register.html";
+  let responsesIndex = 0;
+  window.onmessage = function(e) {
+    let status = e.data.status;
+    let expected = aExpectedResponses[responsesIndex];
+    if (status == expected.status) {
+      ok(true, "Received expected " + expected.status);
+      if (expected.next) {
+        expected.next();
       }
-      responsesIndex++;
-    };
-  }
+    } else {
+      ok(false, "Expected " + expected.status + " got " + status);
+    }
+    responsesIndex++;
+  };
 }
 
 // Verify that we can register and intercept a 3rd party iframe with
 // the given cookie policy.
 function testShouldIntercept(behavior, lifetime, done) {
   SpecialPowers.pushPrefEnv({"set": [
       ["network.cookie.cookieBehavior", behavior],
       ["network.cookie.lifetimePolicy", lifetime],
@@ -108,17 +108,16 @@ function testShouldIntercept(behavior, l
         iframe.src = thirdPartyOrigin + basePath + "unregister.html";
       }
     }, {
       status: "controlled",
     }, {
       status: "unregistrationdone",
       next: function() {
         window.onmessage = null;
-        proxyWindow.close();
         ok(true, "Test finished successfully");
         done();
       }
     }]);
   });
 }
 
 // Verify that we cannot register a service worker in a 3rd party
@@ -140,17 +139,16 @@ function testShouldNotRegister(behavior,
       status: "worker-networkresponse",
       next: loadThirdPartyIframe
     }, {
       status: "networkresponse",
     }, {
       status: "worker-networkresponse",
       next: function() {
         window.onmessage = null;
-        proxyWindow.close();
         ok(true, "Test finished successfully");
         done();
       }
     }]);
   });
 }
 
 // Verify that if a service worker is already registered a 3rd
@@ -161,27 +159,22 @@ function testShouldNotIntercept(behavior
     ["network.cookie.cookieBehavior", BEHAVIOR_ACCEPT],
     ["network.cookie.lifetimePolicy", LIFETIME_EXPIRE],
   ]}, function() {
     runTest([{
       status: "ok"
     }, {
       status: "registrationdone",
       next: function() {
+        iframe.addEventListener("load", testIframeLoaded);
         SpecialPowers.pushPrefEnv({"set": [
             ["network.cookie.cookieBehavior", behavior],
             ["network.cookie.lifetimePolicy", lifetime],
           ]}, function() {
-            proxyWindow.close();
-            proxyWindow = window.open("window_party_iframes.html");
-            proxyWindow.onload = _ => {
-              iframe = proxyWindow.document.querySelector("iframe");
-              iframe.addEventListener("load", testIframeLoaded);
-              iframe.src = origin + basePath + "iframe1.html";
-            }
+            iframe.src = origin + basePath + "iframe1.html";
           });
       }
     }, {
       status: "networkresponse",
     }, {
       status: "worker-networkresponse",
       next: loadThirdPartyIframe
     }, {
@@ -195,32 +188,25 @@ function testShouldNotIntercept(behavior
       status: "uncontrolled",
     }, {
       status: "getregistrationfailed",
       next: function() {
         SpecialPowers.pushPrefEnv({"set": [
             ["network.cookie.cookieBehavior", BEHAVIOR_ACCEPT],
             ["network.cookie.lifetimePolicy", LIFETIME_EXPIRE],
           ]}, function() {
-            proxyWindow.close();
-            proxyWindow = window.open("window_party_iframes.html");
-            proxyWindow.onload = _ => {
-              iframe = proxyWindow.document.querySelector("iframe");
-              iframe.addEventListener("load", testIframeLoaded);
-              iframe.src = thirdPartyOrigin + basePath + "unregister.html";
-            }
+            iframe.src = thirdPartyOrigin + basePath + "unregister.html";
           });
       }
     }, {
       status: "controlled",
     }, {
       status: "unregistrationdone",
       next: function() {
         window.onmessage = null;
-        proxyWindow.close();
         ok(true, "Test finished successfully");
         done();
       }
     }]);
   });
 }
 
 const BEHAVIOR_ACCEPT        = 0;
deleted file mode 100644
--- a/dom/serviceworkers/test/window_party_iframes.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!--
-  Any copyright is dedicated to the Public Domain.
-  http://creativecommons.org/publicdomain/zero/1.0/
--->
-<!DOCTYPE HTML>
-<html>
-<head>
-  <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
-</head>
-<body>
-<iframe></iframe>
-<script>
-window.onmessage = e => {
-  opener.postMessage(e.data, "*");
-}
-</script>
-</body>
-</html>
--- a/dom/storage/LocalStorageCache.cpp
+++ b/dom/storage/LocalStorageCache.cpp
@@ -72,16 +72,17 @@ NS_IMETHODIMP_(void) LocalStorageCacheBr
 LocalStorageCache::LocalStorageCache(const nsACString* aOriginNoSuffix)
     : mActor(nullptr),
       mOriginNoSuffix(*aOriginNoSuffix),
       mMonitor("LocalStorageCache"),
       mLoaded(false),
       mLoadResult(NS_OK),
       mInitialized(false),
       mPersistent(false),
+      mSessionOnlyDataSetActive(false),
       mPreloadTelemetryRecorded(false) {
   MOZ_COUNT_CTOR(LocalStorageCache);
 }
 
 LocalStorageCache::~LocalStorageCache() {
   if (mActor) {
     mActor->SendDeleteMeInternal();
     MOZ_ASSERT(!mActor, "SendDeleteMeInternal should have cleared!");
@@ -177,17 +178,39 @@ inline bool LocalStorageCache::Persist(c
 }
 
 const nsCString LocalStorageCache::Origin() const {
   return LocalStorageManager::CreateOrigin(mOriginSuffix, mOriginNoSuffix);
 }
 
 LocalStorageCache::Data& LocalStorageCache::DataSet(
     const LocalStorage* aStorage) {
-  return mData[GetDataSetIndex(aStorage)];
+  uint32_t index = GetDataSetIndex(aStorage);
+
+  if (index == kSessionSet && !mSessionOnlyDataSetActive) {
+    // Session only data set is demanded but not filled with
+    // current data set, copy to session only set now.
+
+    WaitForPreload(Telemetry::LOCALDOMSTORAGE_SESSIONONLY_PRELOAD_BLOCKING_MS);
+
+    Data& defaultSet = mData[kDefaultSet];
+    Data& sessionSet = mData[kSessionSet];
+
+    for (auto iter = defaultSet.mKeys.Iter(); !iter.Done(); iter.Next()) {
+      sessionSet.mKeys.Put(iter.Key(), iter.UserData());
+    }
+
+    mSessionOnlyDataSetActive = true;
+
+    // This updates sessionSet.mOriginQuotaUsage and also updates global usage
+    // for all session only data
+    ProcessUsageDelta(kSessionSet, defaultSet.mOriginQuotaUsage);
+  }
+
+  return mData[index];
 }
 
 bool LocalStorageCache::ProcessUsageDelta(const LocalStorage* aStorage,
                                           int64_t aDelta,
                                           const MutationSource aSource) {
   return ProcessUsageDelta(GetDataSetIndex(aStorage), aDelta, aSource);
 }
 
@@ -513,16 +536,17 @@ void LocalStorageCache::UnloadItems(uint
   if (aUnloadFlags & kUnloadPrivate) {
     mData[kPrivateSet].mKeys.Clear();
     ProcessUsageDelta(kPrivateSet, -mData[kPrivateSet].mOriginQuotaUsage);
   }
 
   if (aUnloadFlags & kUnloadSession) {
     mData[kSessionSet].mKeys.Clear();
     ProcessUsageDelta(kSessionSet, -mData[kSessionSet].mOriginQuotaUsage);
+    mSessionOnlyDataSetActive = false;
   }
 
 #ifdef DOM_STORAGE_TESTS
   if (aUnloadFlags & kTestReload) {
     WaitForPreload(Telemetry::LOCALDOMSTORAGE_UNLOAD_BLOCKING_MS);
 
     mData[kDefaultSet].mKeys.Clear();
     mLoaded = false;  // This is only used in testing code
--- a/dom/storage/LocalStorageCache.h
+++ b/dom/storage/LocalStorageCache.h
@@ -262,16 +262,22 @@ class LocalStorageCache : public LocalSt
   // Init() method has been called
   bool mInitialized : 1;
 
   // This cache is about to be bound with the database (i.e. it has
   // to load from the DB first and has to persist when modifying the
   // default data set.)
   bool mPersistent : 1;
 
+  // - False when the session-only data set was never used.
+  // - True after access to session-only data has been made for the first time.
+  // We also fill session-only data set with the default one at that moment.
+  // Drops back to false when session-only data are cleared from chrome.
+  bool mSessionOnlyDataSetActive : 1;
+
   // Whether we have already captured state of the cache preload on our first
   // access.
   bool mPreloadTelemetryRecorded : 1;
 };
 
 // StorageUsage
 // Infrastructure to manage and check eTLD+1 quota
 class StorageUsageBridge {
--- a/dom/storage/SessionStorage.cpp
+++ b/dom/storage/SessionStorage.cpp
@@ -159,10 +159,16 @@ bool SessionStorage::IsForkOf(const Stor
   MOZ_ASSERT(aOther);
   if (aOther->Type() != eSessionStorage) {
     return false;
   }
 
   return mCache == static_cast<const SessionStorage*>(aOther)->mCache;
 }
 
+bool SessionStorage::ShouldThrowWhenStorageAccessDenied(
+    uint32_t aRejectedReason) {
+  return aRejectedReason !=
+         nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN;
+}
+
 }  // namespace dom
 }  // namespace mozilla
--- a/dom/storage/SessionStorage.h
+++ b/dom/storage/SessionStorage.h
@@ -60,16 +60,18 @@ class SessionStorage final : public Stor
 
  private:
   ~SessionStorage();
 
   void BroadcastChangeNotification(const nsAString& aKey,
                                    const nsAString& aOldValue,
                                    const nsAString& aNewValue);
 
+  bool ShouldThrowWhenStorageAccessDenied(uint32_t aRejectedReason) override;
+
   RefPtr<SessionStorageCache> mCache;
   RefPtr<SessionStorageManager> mManager;
 
   nsString mDocumentURI;
   bool mIsPrivate;
 };
 
 }  // namespace dom
--- a/dom/storage/SessionStorageCache.cpp
+++ b/dom/storage/SessionStorageCache.cpp
@@ -4,26 +4,36 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "SessionStorageCache.h"
 
 namespace mozilla {
 namespace dom {
 
-SessionStorageCache::SessionStorageCache() = default;
+SessionStorageCache::SessionStorageCache() : mSessionDataSetActive(false) {}
 
 SessionStorageCache::DataSet* SessionStorageCache::Set(
     DataSetType aDataSetType) {
   if (aDataSetType == eDefaultSetType) {
     return &mDefaultSet;
   }
 
   MOZ_ASSERT(aDataSetType == eSessionSetType);
 
+  if (!mSessionDataSetActive) {
+    mSessionSet.mOriginQuotaUsage = mDefaultSet.mOriginQuotaUsage;
+
+    for (auto iter = mDefaultSet.mKeys.ConstIter(); !iter.Done(); iter.Next()) {
+      mSessionSet.mKeys.Put(iter.Key(), iter.Data());
+    }
+
+    mSessionDataSetActive = true;
+  }
+
   return &mSessionSet;
 }
 
 int64_t SessionStorageCache::GetOriginQuotaUsage(DataSetType aDataSetType) {
   return Set(aDataSetType)->mOriginQuotaUsage;
 }
 
 uint32_t SessionStorageCache::Length(DataSetType aDataSetType) {
@@ -106,21 +116,27 @@ nsresult SessionStorageCache::RemoveItem
   return NS_OK;
 }
 
 void SessionStorageCache::Clear(DataSetType aDataSetType,
                                 bool aByUserInteraction) {
   DataSet* dataSet = Set(aDataSetType);
   dataSet->ProcessUsageDelta(-dataSet->mOriginQuotaUsage);
   dataSet->mKeys.Clear();
+
+  if (!aByUserInteraction && aDataSetType == eSessionSetType) {
+    mSessionDataSetActive = false;
+  }
 }
 
 already_AddRefed<SessionStorageCache> SessionStorageCache::Clone() const {
   RefPtr<SessionStorageCache> cache = new SessionStorageCache();
 
+  cache->mSessionDataSetActive = mSessionDataSetActive;
+
   cache->mDefaultSet.mOriginQuotaUsage = mDefaultSet.mOriginQuotaUsage;
   for (auto iter = mDefaultSet.mKeys.ConstIter(); !iter.Done(); iter.Next()) {
     cache->mDefaultSet.mKeys.Put(iter.Key(), iter.Data());
   }
 
   cache->mSessionSet.mOriginQuotaUsage = mSessionSet.mOriginQuotaUsage;
   for (auto iter = mSessionSet.mKeys.ConstIter(); !iter.Done(); iter.Next()) {
     cache->mSessionSet.mKeys.Put(iter.Key(), iter.Data());
--- a/dom/storage/SessionStorageCache.h
+++ b/dom/storage/SessionStorageCache.h
@@ -55,14 +55,15 @@ class SessionStorageCache final {
     int64_t mOriginQuotaUsage;
     nsDataHashtable<nsStringHashKey, nsString> mKeys;
   };
 
   DataSet* Set(DataSetType aDataSetType);
 
   DataSet mDefaultSet;
   DataSet mSessionSet;
+  bool mSessionDataSetActive;
 };
 
 }  // namespace dom
 }  // namespace mozilla
 
 #endif  // mozilla_dom_SessionStorageCache_h
--- a/dom/storage/Storage.cpp
+++ b/dom/storage/Storage.cpp
@@ -24,44 +24,48 @@ NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_LA
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Storage)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 Storage::Storage(nsPIDOMWindowInner* aWindow, nsIPrincipal* aPrincipal)
     : mWindow(aWindow), mPrincipal(aPrincipal), mIsSessionOnly(false) {
   MOZ_ASSERT(aPrincipal);
-
-  if (nsContentUtils::IsSystemPrincipal(mPrincipal)) {
-    mIsSessionOnly = false;
-  } else if (mWindow) {
-    uint32_t rejectedReason = 0;
-    nsContentUtils::StorageAccess access =
-        nsContentUtils::StorageAllowedForWindow(mWindow, &rejectedReason);
-
-    MOZ_ASSERT(access != nsContentUtils::StorageAccess::eDeny ||
-               rejectedReason ==
-                   nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN);
-
-    mIsSessionOnly = access <= nsContentUtils::StorageAccess::eSessionScoped;
-  }
 }
 
 Storage::~Storage() {}
 
 /* static */
 bool Storage::StoragePrefIsEnabled() {
   return mozilla::Preferences::GetBool(kStorageEnabled);
 }
 
 bool Storage::CanUseStorage(nsIPrincipal& aSubjectPrincipal) {
+  // This method is responsible for correct setting of mIsSessionOnly.
   if (!StoragePrefIsEnabled()) {
     return false;
   }
 
+  if (nsContentUtils::IsSystemPrincipal(mPrincipal)) {
+    mIsSessionOnly = false;
+  } else if (mWindow) {
+    uint32_t rejectedReason = 0;
+    nsContentUtils::StorageAccess access =
+        nsContentUtils::StorageAllowedForWindow(mWindow, &rejectedReason);
+
+    // Note that we allow StorageAccess::ePartitionedOrDeny because we want
+    // tracker to have access to their sessionStorage.
+    if (access == nsContentUtils::StorageAccess::eDeny &&
+        ShouldThrowWhenStorageAccessDenied(rejectedReason)) {
+      return false;
+    }
+
+    mIsSessionOnly = access <= nsContentUtils::StorageAccess::eSessionScoped;
+  }
+
   return aSubjectPrincipal.Subsumes(mPrincipal);
 }
 
 /* virtual */
 JSObject* Storage::WrapObject(JSContext* aCx,
                               JS::Handle<JSObject*> aGivenProto) {
   return Storage_Binding::Wrap(aCx, this, aGivenProto);
 }
--- a/dom/storage/Storage.h
+++ b/dom/storage/Storage.h
@@ -129,20 +129,33 @@ class Storage : public nsISupports, publ
                            const char16_t* aStorageType,
                            const nsAString& aDocumentURI, bool aIsPrivate,
                            bool aImmediateDispatch);
 
  protected:
   virtual ~Storage();
 
   // The method checks whether the caller can use a storage.
+  // CanUseStorage is called before any DOM initiated operation
+  // on a storage is about to happen and ensures that the storage's
+  // session-only flag is properly set according the current settings.
+  // It is an optimization since the privileges check and session only
+  // state determination are complex and share the code (comes hand in
+  // hand together).
   bool CanUseStorage(nsIPrincipal& aSubjectPrincipal);
 
   virtual void LastRelease() {}
 
+  // This method is called when StorageAccess is not granted for the owning
+  // window. aRejectedReason is one of the possible blocking states from
+  // nsIWebProgressListener.
+  virtual bool ShouldThrowWhenStorageAccessDenied(uint32_t aRejectedReason) {
+    return true;
+  }
+
  private:
   nsCOMPtr<nsPIDOMWindowInner> mWindow;
   nsCOMPtr<nsIPrincipal> mPrincipal;
 
   // Whether storage is set to persist data only per session, may change
   // dynamically and is set by CanUseStorage function that is called
   // before any operation on the storage.
   bool mIsSessionOnly : 1;
--- a/dom/tests/mochitest/bugs/mochitest.ini
+++ b/dom/tests/mochitest/bugs/mochitest.ini
@@ -144,12 +144,11 @@ skip-if = toolkit == 'android' || os == 
 skip-if = toolkit == 'android' #Windows can't change size on Android
 [test_toJSON.html]
 [test_window_bar.html]
 skip-if = toolkit == 'android'
 [test_bug1022869.html]
 [test_bug1112040.html]
 [test_bug1160342_marquee.html]
 [test_bug1171215.html]
-support-files = window_bug1171215.html
 [test_bug1530292.html]
 [test_no_find_showDialog.html]
 skip-if = toolkit == 'android' # Bug 1358633 - window.find doesn't work for Android
--- a/dom/tests/mochitest/bugs/test_bug1171215.html
+++ b/dom/tests/mochitest/bugs/test_bug1171215.html
@@ -4,46 +4,86 @@
 https://bugzilla.mozilla.org/show_bug.cgi?id=1022869
 -->
 <head>
   <meta charset="utf-8">
   <title>Test for Bug 1022869</title>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/AddTask.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <iframe src="about:blank"></iframe>
   <script type="text/javascript">
 
+  var f = document.getElementsByTagName("iframe")[0];
+
   SimpleTest.waitForExplicitFinish();
 
   /** Test for Bug 1022869 **/
   function startTest() {
     // Initialize our cookie.
     document.cookie = "a=b";
 
-    SpecialPowers.pushPrefEnv({ set: [["network.cookie.cookieBehavior", 1]] }).then(_ => {
-      let w = window.open("window_bug1171215.html");
-      onmessage = e => {
-        if (e.data.type == "finish") {
-          w.close();
-          SimpleTest.finish();
-          return;
-        }
+    // Set a cookie in example.org so we can test that we can't read it in
+    // third-party cases.
+    f.contentWindow.location =
+        "http://example.org/tests/dom/tests/mochitest/bugs/file_prime_cookie.html";
+    waitForLoad().then(function() {
+        // Cookies are set up, disallow third-party cookies and start the test.
+        SpecialPowers.pushPrefEnv({ set: [
+            ["network.cookie.cookieBehavior", 1],
+          ]}, () => { continueTest(); });
+    }).catch((e) => { ok(false, `Got exception: ${e}`) });
+  }
+
+  function waitForLoad() {
+    return new Promise((resolve) => {
+      window.addEventListener("message", function(msg) {
+        info(`got message ${msg.data}`);
+        resolve(msg.data);
+      }, {once: true});
+    });
+  }
+
+  async function continueTest() {
+    var sameOrigin = "http://mochi.test:8888";
+    var thirdParty = "http://example.org";
+    var page = "tests/dom/tests/mochitest/bugs/file_cookieOutputter.html"
+    var redirect = "tests/dom/tests/mochitest/bugs/file_redirector.sjs";
 
-        if (e.data.type == "info") {
-          info(e.data.msg);
-          return;
-        }
+    function createRedirect(firstOrigin, secondOrigin) {
+      return `${firstOrigin}/${redirect}?${secondOrigin}/${page}`;
+    }
+
+    info("starting test");
+
+    // Same origin to same origin.
+    f.contentWindow.location = createRedirect(sameOrigin, sameOrigin);
+    let cookie = await waitForLoad();
+    is(cookie, "a=b", "got the cookie");
 
-        if (e.data.type == "test") {
-          ok(e.data.test, e.data.msg);
-          return;
-        }
+    // Cross origin to cross origin.
+    f.contentWindow.location = createRedirect(thirdParty, thirdParty);
+    cookie = await waitForLoad();
+    is(cookie, "", "no third-party cookies");
 
-        ok(false, "Unknown message");
-      };
-    });
+    // Same origin to cross origin.
+    f.contentWindow.location = createRedirect(sameOrigin, thirdParty);
+    cookie = await waitForLoad();
+    is(cookie, "", "no third-party cookies");
+
+    // Cross origin to same origin
+    f.contentWindow.location = createRedirect(thirdParty, sameOrigin);
+    cookie = await waitForLoad();
+    is(cookie, "a=b", "got the cookie");
+
+    SimpleTest.finish();
   }
   </script>
 </head>
 <body onload="startTest()">
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1022869">Mozilla Bug 1022869</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+</div>
+<pre id="test">
+</pre>
 </body>
 </html>
deleted file mode 100644
--- a/dom/tests/mochitest/bugs/window_bug1171215.html
+++ /dev/null
@@ -1,86 +0,0 @@
-<!DOCTYPE html>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=1022869
--->
-<head>
-  <meta charset="utf-8">
-  <title>Test for Bug 1022869</title>
-  <iframe src="about:blank"></iframe>
-  <script type="text/javascript">
-
-  function finish() {
-    opener.postMessage({type: "finish" });
-  }
-
-  function info(msg) {
-    opener.postMessage({type: "info", msg });
-  }
-
-  function ok(a, msg) {
-    opener.postMessage({type: "test", test: !!a, msg });
-  }
-
-  function is(a, b, msg) {
-    ok(a === b, msg);
-  }
-
-  var f = document.getElementsByTagName("iframe")[0];
-
-  /** Test for Bug 1022869 **/
-  function startTest() {
-    // Set a cookie in example.org so we can test that we can't read it in
-    // third-party cases.
-    f.contentWindow.location =
-        "http://example.org/tests/dom/tests/mochitest/bugs/file_prime_cookie.html";
-    waitForLoad().then(continueTest).catch((e) => { ok(false, `Got exception: ${e}`) });
-  }
-
-  function waitForLoad() {
-    return new Promise((resolve) => {
-      window.addEventListener("message", function(msg) {
-        info(`got message ${msg.data}`);
-        resolve(msg.data);
-      }, {once: true});
-    });
-  }
-
-  async function continueTest() {
-    var sameOrigin = "http://mochi.test:8888";
-    var thirdParty = "http://example.org";
-    var page = "tests/dom/tests/mochitest/bugs/file_cookieOutputter.html"
-    var redirect = "tests/dom/tests/mochitest/bugs/file_redirector.sjs";
-
-    function createRedirect(firstOrigin, secondOrigin) {
-      return `${firstOrigin}/${redirect}?${secondOrigin}/${page}`;
-    }
-
-    info("starting test");
-
-    // Same origin to same origin.
-    f.contentWindow.location = createRedirect(sameOrigin, sameOrigin);
-    let cookie = await waitForLoad();
-    is(cookie, "a=b", "got the cookie");
-
-    // Cross origin to cross origin.
-    f.contentWindow.location = createRedirect(thirdParty, thirdParty);
-    cookie = await waitForLoad();
-    is(cookie, "", "no third-party cookies");
-
-    // Same origin to cross origin.
-    f.contentWindow.location = createRedirect(sameOrigin, thirdParty);
-    cookie = await waitForLoad();
-    is(cookie, "", "no third-party cookies");
-
-    // Cross origin to same origin
-    f.contentWindow.location = createRedirect(thirdParty, sameOrigin);
-    cookie = await waitForLoad();
-    is(cookie, "a=b", "got the cookie");
-
-    finish();
-  }
-  </script>
-</head>
-<body onload="startTest()">
-</body>
-</html>
--- a/dom/tests/mochitest/general/mochitest.ini
+++ b/dom/tests/mochitest/general/mochitest.ini
@@ -45,17 +45,16 @@ support-files =
   test_interfaces.js
   frameStorageAllowed.html
   frameStoragePrevented.html
   frameStorageChrome.html
   frameStorageNullprincipal.sjs
   workerStorageAllowed.js
   workerStoragePrevented.js
   storagePermissionsUtils.js
-  window_storagePermissions.html
   frameSelectEvents.html
   !/image/test/mochitest/big.png
   !/image/test/mochitest/blue.png
   !/image/test/mochitest/clear.png
   !/image/test/mochitest/damon.jpg
   !/image/test/mochitest/over.png
   !/image/test/mochitest/red.png
   !/dom/base/test/Ahem.ttf
--- a/dom/tests/mochitest/general/storagePermissionsUtils.js
+++ b/dom/tests/mochitest/general/storagePermissionsUtils.js
@@ -237,38 +237,9 @@ function task(fn) {
     gen.then(finishTest, e => {
       ok(false, "An error was thrown while stepping: " + e);
       ok(false, "Stack: " + e.stack);
       finishTest();
     });
   }
 }
 
-// The test will run on a separate window in order to apply the new cookie settings.
-async function runTestInWindow(test) {
-  let w = window.open("window_storagePermissions.html");
-  await new Promise(resolve => {
-    w.onload = e => {
-     resolve();
-    }
-  });
-
-  await new Promise(resolve => {
-    onmessage = e => {
-      if (e.data.type == "finish") {
-        w.close();
-        resolve();
-        return;
-      }
-
-      if (e.data.type == "check") {
-        ok(e.data.test, e.data.msg);
-        return;
-      }
-
-      ok(false, "Unknown message");
-    };
-
-    w.postMessage(test.toString(), "*");
-  });
-}
-
 var thirdparty = "https://example.com/tests/dom/tests/mochitest/general/";
--- a/dom/tests/mochitest/general/test_storagePermissionsAccept.html
+++ b/dom/tests/mochitest/general/test_storagePermissionsAccept.html
@@ -9,36 +9,34 @@
   <body>
     <iframe></iframe>
 
     <script type="text/javascript">
 
 task(async function() {
   await setCookieBehavior(BEHAVIOR_ACCEPT);
 
-  await runTestInWindow(async function() {
-    // We should be able to access storage
-    await storageAllowed();
+  // We should be able to access storage
+  await storageAllowed();
 
-    // Same origin iframes should be allowed, unless they redirect to a URI with the null principal
-    await runIFrame("frameStorageAllowed.html");
-    await runIFrame("frameStorageNullprincipal.sjs");
-    await runIFrame("frameStorageChrome.html?allowed=yes");
+  // Same origin iframes should be allowed, unless they redirect to a URI with the null principal
+  await runIFrame("frameStorageAllowed.html");
+  await runIFrame("frameStorageNullprincipal.sjs");
+  await runIFrame("frameStorageChrome.html?allowed=yes");
 
-    // Sandboxed iframes should have the null principal, and thus can't access storage
-    document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
-    await runIFrame("frameStoragePrevented.html#nullprincipal");
-    await runIFrame("frameStorageNullprincipal.sjs");
-    document.querySelector('iframe').removeAttribute('sandbox');
+  // Sandboxed iframes should have the null principal, and thus can't access storage
+  document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
+  await runIFrame("frameStoragePrevented.html#nullprincipal");
+  await runIFrame("frameStorageNullprincipal.sjs");
+  document.querySelector('iframe').removeAttribute('sandbox');
 
-    // Thirdparty iframes should be allowed, unless they redirect to a URI with the null principal
-    await runIFrame(thirdparty + "frameStorageAllowed.html");
-    await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
-    await runIFrame(thirdparty + "frameStorageChrome.html?allowed=yes");
+  // Thirdparty iframes should be allowed, unless they redirect to a URI with the null principal
+  await runIFrame(thirdparty + "frameStorageAllowed.html");
+  await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
+  await runIFrame(thirdparty + "frameStorageChrome.html?allowed=yes");
 
-    // Workers should be able to access storage
-    await runWorker("workerStorageAllowed.js");
-  });
+  // Workers should be able to access storage
+  await runWorker("workerStorageAllowed.js");
 });
 
     </script>
   </body>
 </html>
--- a/dom/tests/mochitest/general/test_storagePermissionsLimitForeign.html
+++ b/dom/tests/mochitest/general/test_storagePermissionsLimitForeign.html
@@ -9,38 +9,36 @@
   <body>
     <iframe></iframe>
 
     <script type="text/javascript">
 
 task(async function() {
   await setCookieBehavior(BEHAVIOR_LIMIT_FOREIGN);
 
-  await runTestInWindow(async function() {
-    // We should be able to access storage
-    await storageAllowed();
+  // We should be able to access storage
+  await storageAllowed();
 
-    // Same origin iframes should be allowed.
-    await runIFrame("frameStorageAllowed.html");
-    await runIFrame("frameStorageChrome.html?allowed=yes");
+  // Same origin iframes should be allowed.
+  await runIFrame("frameStorageAllowed.html");
+  await runIFrame("frameStorageChrome.html?allowed=yes");
 
-    // Null principal iframes should not.
-    await runIFrame("frameStorageNullprincipal.sjs");
+  // Null principal iframes should not.
+  await runIFrame("frameStorageNullprincipal.sjs");
 
-    // Sandboxed iframes should have the null principal, and thus can't access storage
-    document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
-    await runIFrame("frameStoragePrevented.html#nullprincipal");
-    await runIFrame("frameStorageNullprincipal.sjs");
-    document.querySelector('iframe').removeAttribute('sandbox');
+  // Sandboxed iframes should have the null principal, and thus can't access storage
+  document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
+  await runIFrame("frameStoragePrevented.html#nullprincipal");
+  await runIFrame("frameStorageNullprincipal.sjs");
+  document.querySelector('iframe').removeAttribute('sandbox');
 
-    // Thirdparty iframes should be blocked, even when accessed from chrome over Xrays.
-    await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
-    await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
-    await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
+  // Thirdparty iframes should be blocked, even when accessed from chrome over Xrays.
+  await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
+  await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
+  await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
 
-    // Workers should be unable to access storage
-    await runWorker("workerStorageAllowed.js");
-  });
+  // Workers should be unable to access storage
+  await runWorker("workerStorageAllowed.js");
 });
 
     </script>
   </body>
 </html>
--- a/dom/tests/mochitest/general/test_storagePermissionsReject.html
+++ b/dom/tests/mochitest/general/test_storagePermissionsReject.html
@@ -9,36 +9,34 @@
   <body>
     <iframe></iframe>
 
     <script type="text/javascript">
 
 task(async function() {
   await setCookieBehavior(BEHAVIOR_REJECT);
 
-  await runTestInWindow(async function() {
-    // We should be unable to access storage
-    await storagePrevented();
+  // We should be unable to access storage
+  await storagePrevented();
 
-    // Same origin iframes should be blocked.
-    await runIFrame("frameStoragePrevented.html");
-    await runIFrame("frameStorageNullprincipal.sjs");
-    await runIFrame("frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
+  // Same origin iframes should be blocked.
+  await runIFrame("frameStoragePrevented.html");
+  await runIFrame("frameStorageNullprincipal.sjs");
+  await runIFrame("frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
 
-    // Sandboxed iframes should have the null principal, and thus can't access storage
-    document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
-    await runIFrame("frameStoragePrevented.html#nullprincipal");
-    await runIFrame("frameStorageNullprincipal.sjs");
-    document.querySelector('iframe').removeAttribute('sandbox');
+  // Sandboxed iframes should have the null principal, and thus can't access storage
+  document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
+  await runIFrame("frameStoragePrevented.html#nullprincipal");
+  await runIFrame("frameStorageNullprincipal.sjs");
+  document.querySelector('iframe').removeAttribute('sandbox');
 
-    // thirdparty iframes should be blocked.
-    await runIFrame(thirdparty + "frameStoragePrevented.html");
-    await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
-    await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
+  // thirdparty iframes should be blocked.
+  await runIFrame(thirdparty + "frameStoragePrevented.html");
+  await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
+  await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
 
-    // Workers should be unable to access storage
-    await runWorker("workerStoragePrevented.js");
-  });
+  // Workers should be unable to access storage
+  await runWorker("workerStoragePrevented.js");
 });
 
     </script>
   </body>
 </html>
--- a/dom/tests/mochitest/general/test_storagePermissionsRejectForeign.html
+++ b/dom/tests/mochitest/general/test_storagePermissionsRejectForeign.html
@@ -9,36 +9,34 @@
   <body>
     <iframe></iframe>
 
     <script type="text/javascript">
 
 task(async function() {
   await setCookieBehavior(BEHAVIOR_REJECT_FOREIGN);
 
-  await runTestInWindow(async function() {
-    // We should be able to access storage
-    await storageAllowed();
+  // We should be able to access storage
+  await storageAllowed();
 
-    // Same origin iframes should be allowed, unless they redirect to a URI with the null principal
-    await runIFrame("frameStorageAllowed.html");
-    await runIFrame("frameStorageNullprincipal.sjs");
-    await runIFrame("frameStorageChrome.html?allowed=yes");
+  // Same origin iframes should be allowed, unless they redirect to a URI with the null principal
+  await runIFrame("frameStorageAllowed.html");
+  await runIFrame("frameStorageNullprincipal.sjs");
+  await runIFrame("frameStorageChrome.html?allowed=yes");
 
-    // Sandboxed iframes should have the null principal, and thus can't access storage
-    document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
-    await runIFrame("frameStoragePrevented.html#nullprincipal");
-    await runIFrame("frameStorageNullprincipal.sjs");
-    document.querySelector('iframe').removeAttribute('sandbox');
+  // Sandboxed iframes should have the null principal, and thus can't access storage
+  document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
+  await runIFrame("frameStoragePrevented.html#nullprincipal");
+  await runIFrame("frameStorageNullprincipal.sjs");
+  document.querySelector('iframe').removeAttribute('sandbox');
 
-    // thirdparty iframes should be blocked.
-    await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
-    await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
-    await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
+  // thirdparty iframes should be blocked.
+  await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
+  await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
+  await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
 
-    // Workers should be able to access storage
-    await runWorker("workerStorageAllowed.js");
-  });
+  // Workers should be able to access storage
+  await runWorker("workerStorageAllowed.js");
 });
 
     </script>
   </body>
 </html>
deleted file mode 100644
--- a/dom/tests/mochitest/general/window_storagePermissions.html
+++ /dev/null
@@ -1,38 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-  <head>
-    <title>Storage Permission Restrictions</title>
-    <script type="text/javascript" src="storagePermissionsUtils.js"></script>
-  </head>
-  <body>
-    <iframe></iframe>
-
-    <script type="text/javascript">
-
-function ok(a, msg) {
-  opener.postMessage({type: "check", test: !!a, msg }, "*");
-}
-
-function is(a, b, msg) {
-  ok(a === b , msg);
-}
-
-let init = false;
-onmessage = e => {
-  if (!init) {
-    init = true;
-
-    let runnableStr = `(() => {return (${e.data});})();`;
-    let runnable = eval(runnableStr); // eslint-disable-line no-eval
-    runnable.call(this).then(_ => {
-      opener.postMessage({ type: "finish" }, "*");
-    });
-
-    return;
-  }
-
-  parent.postMessage(e.data, "*");
-}
-
-    </script>
-  </body>
-</html>
--- a/dom/tests/mochitest/localstorage/frameLocalStorageCookieSettings.html
+++ b/dom/tests/mochitest/localstorage/frameLocalStorageCookieSettings.html
@@ -1,16 +1,20 @@
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <title>localStorage cookies settings test</title>
 
+<script type="text/javascript" src="interOriginFrame.js"></script>
+
 </head>
 <body>
 <script type="text/javascript">
   try {
     localStorage.setItem("contentkey", "test-value");
     ok(false, "Setting localStorageItem should throw a type error exception");
   } catch(ex) {
     is(ex.name, "TypeError");
   }
+
+  finishTest();
 </script>
 </body>
 </html>
--- a/dom/tests/mochitest/localstorage/mochitest.ini
+++ b/dom/tests/mochitest/localstorage/mochitest.ini
@@ -12,24 +12,24 @@ support-files =
   frameSlaveEqual.html
   frameSlaveNotEqual.html
   interOriginFrame.js
   interOriginTest.js
   interOriginTest2.js
   localStorageCommon.js
   frameLocalStorageSessionOnly.html
   file_tryAccessSessionStorage.html
-  windowProxy.html
 
 [test_brokenUTF-16.html]
 [test_bug600307-DBOps.html]
 [test_bug746272-1.html]
 [test_bug746272-2.html]
 skip-if = os == "android" || verify # bug 962029
 [test_cookieBlock.html]
+[test_cookieSession.html]
 [test_embededNulls.html]
 [test_keySync.html]
 [test_localStorageBase.html]
 skip-if = e10s
 [test_localStorageBaseSessionOnly.html]
 [test_localStorageCookieSettings.html]
 [test_localStorageEnablePref.html]
 [test_localStorageKeyOrder.html]
@@ -44,8 +44,9 @@ skip-if = toolkit == 'android' #TIMED_OU
 skip-if = toolkit == 'android' #TIMED_OUT
 [test_localStorageQuotaSessionOnly.html]
 skip-if = toolkit == 'android' || (verify && (os == 'linux' || os == 'mac' || os == 'win')) #TIMED_OUT
 [test_localStorageQuotaSessionOnly2.html]
 skip-if = true # bug 1347690
 [test_localStorageReplace.html]
 skip-if = toolkit == 'android'
 [test_storageConstructor.html]
+[test_localStorageSessionPrefOverride.html]
--- a/dom/tests/mochitest/localstorage/test_cookieBlock.html
+++ b/dom/tests/mochitest/localstorage/test_cookieBlock.html
@@ -4,38 +4,33 @@
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 function startTest()
 {
-  // Let's use a new window to have the cookie permission applied.
-  let w = window.open("windowProxy.html");
-  w.onload = _ => {
-    try {
-      w.localStorage.setItem("blocked", "blockedvalue");
-      ok(false, "Exception for localStorage.setItem, ACCESS_DENY");
-    }
-    catch (ex) {
-      ok(true, "Exception for localStorage.setItem, ACCESS_DENY");
-    }
+  try {
+    localStorage.setItem("blocked", "blockedvalue");
+    ok(false, "Exception for localStorage.setItem, ACCESS_DENY");
+  }
+  catch (ex) {
+    ok(true, "Exception for localStorage.setItem, ACCESS_DENY");
+  }
 
-    try {
-      w.localStorage.getItem("blocked");
-      ok(false, "Exception for localStorage.getItem, ACCESS_DENY");
-    }
-    catch (ex) {
-      ok(true, "Exception for localStorage.getItem, ACCESS_DENY");
-    }
+  try {
+    localStorage.getItem("blocked");
+    ok(false, "Exception for localStorage.getItem, ACCESS_DENY");
+  }
+  catch (ex) {
+    ok(true, "Exception for localStorage.getItem, ACCESS_DENY");
+  }
 
-    w.close();
-    SimpleTest.finish();
-  }
+  SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 // Initialize storage before setting the cookie, otherwise we won't be testing
 // the checks in setItem/getItem methods.
 var storage = localStorage;
 
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/localstorage/test_cookieSession.html
@@ -0,0 +1,139 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>cookie per-session only test</title>
+
+<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+
+<script type="text/javascript">
+
+/*
+  Set cookie access to be just per session and store to the localStorage.
+  Content stored must prevail only for session of the browser, so it must
+  be accessible in another window we try to access that key in the same
+  storage.
+ */
+
+function pushCookie(aPermission, aNext) {
+  SpecialPowers.pushPermissions([{'type': 'cookie', 'allow': aPermission, 'context': document}], aNext);
+}
+
+function test1() {
+  localStorage.setItem("persistent1", "persistent value 1");
+  localStorage.setItem("persistent2", "persistent value 2");
+
+  pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION, test1_b);
+}
+
+function test1_b() {
+  localStorage.setItem("session only", "session value");
+  parent.is(localStorage.getItem("session only"), "session value");
+  parent.is(localStorage.getItem("persistent1"), "persistent value 1");
+  parent.is(localStorage.getItem("persistent2"), "persistent value 2");
+
+  window.location.search = '?2';
+}
+
+function test2()
+{
+  parent.is(localStorage.getItem("session only"), "session value", "Value present when cookies in session-only mode");
+  parent.is(localStorage.getItem("persistent1"), "persistent value 1", "Persistent value present");
+  parent.is(localStorage.getItem("persistent2"), "persistent value 2", "Persistent value present");
+
+  localStorage.setItem("persistent1", "changed persistent value 1");
+  localStorage.removeItem("persistent2");
+
+  parent.is(localStorage.getItem("session only"), "session value", "Value present when cookies in session-only mode");
+  parent.is(localStorage.getItem("persistent1"), "changed persistent value 1", "Persistent value present");
+  parent.is(localStorage.getItem("persistent2"), null, "Persistent value removed");
+
+  // This clear has to delete only changes made in session only mode
+  localStorage.clear();
+
+  parent.is(localStorage.getItem("session only"), null, "Value not present when cookies in session-only mode after delete");
+  parent.is(localStorage.getItem("persistent1"), null, "Persistent value not present in session only after delete");
+  parent.is(localStorage.getItem("persistent2"), null, "Persistent value not present in session only after delete");
+
+  localStorage.setItem("session only 2", "must be deleted on drop of session-only cookies permissions");
+
+  pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT, function() { window.location.search = '?3'; });
+}
+
+function test3() {
+  parent.is(localStorage.getItem("session only"), null, "No value when cookies are in default mode");
+  parent.is(localStorage.getItem("session only 2"), null, "No value when cookies are in default mode");
+  parent.is(localStorage.getItem("persistent1"), "persistent value 1", "Persistent value present");
+  parent.is(localStorage.getItem("persistent2"), "persistent value 2", "Persistent value present");
+
+  pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION, function() { window.location.search = '?4'; });
+}
+
+function test4() {
+  parent.is(localStorage.getItem("session only"), null, "Value not present when cookies in session-only mode after delete");
+  parent.is(localStorage.getItem("session only 2"), null, "Value not present when cookies in session-only mode after delete");
+  parent.is(localStorage.getItem("persistent1"), "persistent value 1", "Persistent value present again");
+  parent.is(localStorage.getItem("persistent2"), "persistent value 2", "Persistent value present again");
+
+  pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT, function() { window.location.search = '?5'; });
+}
+
+function test5() {
+  localStorage.clear();
+
+  parent.is(localStorage.getItem("session only"), null, "No value when cookies are in default mode");
+  parent.is(localStorage.getItem("persistent1"), null, "Persistent value not present after delete");
+  parent.is(localStorage.getItem("persistent2"), null, "Persistent value not present after delete");
+
+  pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION, function() { window.location.search = '?6'; });
+}
+
+function test6() {
+  parent.is(localStorage.getItem("session only"), null, "Value not present when cookies in session-only mode after delete");
+  parent.is(localStorage.getItem("session only 2"), null, "No value when cookies are in default mode");
+  parent.is(localStorage.getItem("persistent1"), null, "Persistent value not present in session only after delete");
+  parent.is(localStorage.getItem("persistent2"), null, "Persistent value not present in session only after delete");
+
+  parent.SimpleTest.finish();
+}
+
+function startTest() {
+  switch (location.search) {
+    case '?1':
+      test1();
+      break;
+    case '?2':
+      test2();
+      break;
+    case '?3':
+      test3();
+      break;
+    case '?4':
+      test4();
+      break;
+    case '?5':
+      test5();
+      break;
+    case '?6':
+      test6();
+      break;
+    default:
+      SimpleTest.waitForExplicitFinish();
+
+      if (SpecialPowers.Services.lsm.nextGenLocalStorageEnabled) {
+        ok(true, "Test ignored when the next gen local storage is enabled.");
+        SimpleTest.finish();
+        return;
+      }
+
+      var iframe = document.createElement('iframe');
+      iframe.src = 'test_cookieSession.html?1';
+      document.body.appendChild(iframe);
+  }
+}
+</script>
+
+</head>
+
+<body onload="startTest()">
+</body>
+</html>
--- a/dom/tests/mochitest/localstorage/test_localStorageCookieSettings.html
+++ b/dom/tests/mochitest/localstorage/test_localStorageCookieSettings.html
@@ -3,65 +3,58 @@
 <title>localStorage cookies settings test</title>
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <script type="text/javascript" src="interOriginTest.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 </head>
 <body>
+<iframe></iframe>
 
 <script type="text/javascript">
 
 SimpleTest.waitForExplicitFinish();
 
 // Set cookies behavior to "always reject".
 SpecialPowers.pushPrefEnv({"set": [
   ["network.cookie.cookieBehavior", 2],
 ]}, test1);
 
 function test1() {
-  let w = window.open("windowProxy.html");
-  w.onload = _ => {
-    try {
-      w.localStorage.setItem("contentkey", "test-value");
-      ok(false, "Setting localStorageItem should throw a security exception");
-    }
-    catch(ex) {
-      is(ex.name, "TypeError");
-    }
+  try {
+    localStorage.setItem("contentkey", "test-value");
+    ok(false, "Setting localStorageItem should throw a type error exception");
+  }
+  catch(ex) {
+    is(ex.name, "TypeError");
+  }
 
-    w.close();
-
-    // Set cookies behavior to "reject 3rd party"
-    SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 1]],
-                               "clear": [["network.cookie.lifetimePolicy"]]},
-                              test2);
-  }
+  // Set cookies behavior to "reject 3rd party"
+  SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 1]],
+                             "clear": [["network.cookie.lifetimePolicy"]]},
+                            test3);
 }
 
-function test2() {
-  let w = window.open("windowProxy.html");
-  w.onload = _ => {
-    try {
-      w.localStorage.setItem("contentkey", "test-value");
-      ok(true, "Setting localStorageItem should not throw a security exception");
-    }
-    catch(ex) {
-      ok(false, "Setting localStorageItem should not throw a security exception");
-    }
+function test3() {
+  try {
+    localStorage.setItem("contentkey", "test-value");
+    ok(true, "Setting localStorageItem should not throw a type error exception");
+  }
+  catch(ex) {
+    ok(false, "Setting localStorageItem should not throw a type error exception");
+  }
 
-    var fileTest = (location.protocol + "//example.com" + location.pathname)
-                   .replace("test_l", "frameL");
+  var fileTest = (location.protocol + "//example.com" + location.pathname)
+                 .replace("test_l", "frameL");
 
-    var myframe = w.document.createElement("iframe");
-    w.document.body.appendChild(myframe);
-    myframe.src = fileTest;
-    myframe.onload = _ => {
-      w.close();
-      SimpleTest.finish();
-    }
-  }
+  var myframe = document.querySelector("iframe");
+  myframe.src = fileTest;
+}
+
+// Called by interOriginTest.js
+function doNextTest() {
+  SimpleTest.finish();
 }
 
 </script>
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/localstorage/test_localStorageSessionPrefOverride.html
@@ -0,0 +1,56 @@
+<html>
+  <head>
+    <title>Local Storage Session Pref Override</title>
+    <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+    <script type="text/javascript" src="/tests/SimpleTest/AddTask.js"></script>
+    <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+    <script>
+      const ACCEPT_SESSION = 2;
+
+      add_task(async function() {
+        if (SpecialPowers.Services.lsm.nextGenLocalStorageEnabled) {
+          ok(true, "Test ignored when the next gen local storage is enabled.");
+          return;
+        }
+
+        await SpecialPowers.pushPrefEnv({"set": [["network.cookie.lifetimePolicy",
+                                                  ACCEPT_SESSION]]});
+
+        // Before setting permission
+        await new Promise((resolve) => {
+          var frame = document.createElement('iframe');
+          frame.src = "frameLocalStorageSessionOnly.html";
+
+          var listener = (e) => {
+            is(e.data, true, "Before adding permission should be session only");
+            window.removeEventListener('message', listener);
+            resolve();
+          };
+          window.addEventListener('message', listener);
+          document.body.appendChild(frame);
+        });
+
+        // After setting permission
+        await new Promise((resolve) => {
+          SpecialPowers.pushPermissions([{"type": "cookie", "allow": 1, "context": document}],
+                                        resolve);
+        });
+
+        await new Promise((resolve) => {
+          var frame = document.createElement('iframe');
+          frame.src = "frameLocalStorageSessionOnly.html";
+
+          var listener = (e) => {
+            is(e.data, false, "After adding permission should not be session only");
+            window.removeEventListener('message', listener);
+            resolve();
+          };
+          window.addEventListener('message', listener);
+          document.body.appendChild(frame);
+        });
+      });
+    </script>
+  </head>
+  <body>
+  </body>
+</html>
deleted file mode 100644
--- a/dom/tests/mochitest/localstorage/windowProxy.html
+++ /dev/null
@@ -1,3 +0,0 @@
-<html xmlns="http://www.w3.org/1999/xhtml">
-<body></body>
-</html>
--- a/dom/tests/mochitest/sessionstorage/mochitest.ini
+++ b/dom/tests/mochitest/sessionstorage/mochitest.ini
@@ -3,16 +3,17 @@ support-files =
   file_http.html
   file_https.html
   frameEqual.html
   frameNotEqual.html
   frameReplace.html
   interOriginSlave.js
   interOriginTest.js
 
+[test_cookieSession.html]
 [test_sessionStorageBase.html]
 [test_sessionStorageBaseSessionOnly.html]
 [test_sessionStorageClone.html]
 skip-if = toolkit == 'android'
 [test_sessionStorageHttpHttps.html]
 skip-if = toolkit == 'android' #TIMED_OUT
 [test_sessionStorageReplace.html]
 [test_sessionStorageUsage.html]
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/sessionstorage/test_cookieSession.html
@@ -0,0 +1,124 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>cookie per-session only test</title>
+
+<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+
+<script type="text/javascript">
+
+/*
+  Set cookie access to be just per session and store to the sessionStorage.
+  Content stored must prevail only for session of the browser, so it must
+  be accessible in another window we try to access that key in the same
+  storage.
+ */
+
+function pushCookie(aValue, aNext) {
+  SpecialPowers.pushPermissions([{'type': 'cookie', 'allow': aValue, 'context': document}], pushPermissionAndTest);
+}
+
+function pushPermissionAndTest() {
+  var test = tests.shift();
+  if (test) {
+    document.getElementById('testframe').onload = test;
+    /* After every permission change, an iframe has to be reloaded,
+       otherwise this test causes failures in b2g (oop) mochitest, because
+       the permission changes don't seem to be always picked up
+       by the code that excercises it */
+    document.getElementById('testframe').contentWindow.location.reload();
+  } else {
+    ok(false, 'should not be reached');
+    SimpleTest.finish();
+  }
+}
+
+function startTest() {
+  pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT);
+}
+
+var tests = [
+  function test1() {
+    sessionStorage.setItem("persistent1", "persistent value 1");
+    sessionStorage.setItem("persistent2", "persistent value 2");
+
+    pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION);
+  },
+
+  function test2() {
+    sessionStorage.setItem("session only", "session value");
+    is(sessionStorage.getItem("session only"), "session value", "Value present when cookies in session-only mode");
+    is(sessionStorage.getItem("persistent1"), "persistent value 1", "Persistent value present");
+    is(sessionStorage.getItem("persistent2"), "persistent value 2", "Persistent value present");
+
+    sessionStorage.setItem("persistent1", "changed persistent value 1");
+    sessionStorage.removeItem("persistent2");
+
+    is(sessionStorage.getItem("session only"), "session value", "Value present when cookies in session-only mode");
+    is(sessionStorage.getItem("persistent1"), "changed persistent value 1", "Persistent value present");
+    is(sessionStorage.getItem("persistent2"), null, "Persistent value removed");
+
+    // This clear has to delete only changes made in session only mode
+    sessionStorage.clear();
+
+    is(sessionStorage.getItem("session only"), null, "Value not present when cookies in session-only mode after delete");
+    is(sessionStorage.getItem("persistent1"), null, "Persistent value not present in session only after delete");
+    is(sessionStorage.getItem("persistent2"), null, "Persistent value not present in session only after delete");
+
+    sessionStorage.setItem("session only 2", "must be deleted on drop of session-only cookies permissions");
+
+    pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT);
+  },
+
+  function test3() {
+    is(sessionStorage.getItem("session only"), null, "No value when cookies are in default mode");
+    is(sessionStorage.getItem("session only 2"), null, "No value when cookies are in default mode");
+    is(sessionStorage.getItem("persistent1"), "persistent value 1", "Persistent value present");
+    is(sessionStorage.getItem("persistent2"), "persistent value 2", "Persistent value present");
+
+    pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION);
+  },
+
+  function test4() {
+    is(sessionStorage.getItem("session only"), null, "Value not present when cookies in session-only mode after delete");
+    is(sessionStorage.getItem("session only 2"), null, "Value not present when cookies in session-only mode after delete");
+    is(sessionStorage.getItem("persistent1"), "persistent value 1", "Persistent value present again");
+    is(sessionStorage.getItem("persistent2"), "persistent value 2", "Persistent value present again");
+
+    pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT);
+  },
+
+  function test5() {
+    sessionStorage.clear();
+
+    is(sessionStorage.getItem("session only"), null, "No value when cookies are in default mode");
+    is(sessionStorage.getItem("persistent1"), null, "Persistent value not present after delete");
+    is(sessionStorage.getItem("persistent2"), null, "Persistent value not present after delete");
+
+    pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION);
+  },
+
+  function test6() {
+    is(sessionStorage.getItem("session only"), null, "Value not present when cookies in session-only mode after delete");
+    is(sessionStorage.getItem("session only 2"), null, "No value when cookies are in default mode");
+    is(sessionStorage.getItem("persistent1"), null, "Persistent value not present in session only after delete");
+    is(sessionStorage.getItem("persistent2"), null, "Persistent value not present in session only after delete");
+
+    pushCookie(SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT);
+  },
+
+  function test7() {
+    SimpleTest.finish();
+  }
+];
+
+SimpleTest.waitForExplicitFinish();
+
+</script>
+
+</head>
+
+<body onload="startTest();">
+<iframe id="testframe" srcdoc="<meta charset=utf-8>"></iframe>
+</body>
+</html>
--- a/dom/webbrowserpersist/nsWebBrowserPersist.cpp
+++ b/dom/webbrowserpersist/nsWebBrowserPersist.cpp
@@ -57,17 +57,16 @@
 
 #include "nsWebBrowserPersist.h"
 #include "WebBrowserPersistLocalDocument.h"
 
 #include "nsIContent.h"
 #include "nsIMIMEInfo.h"
 #include "mozilla/dom/HTMLInputElement.h"
 #include "mozilla/dom/HTMLSharedElement.h"
-#include "mozilla/net/CookieSettings.h"
 #include "mozilla/Printf.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 // Buffer file writes in 32kb chunks
 #define BUFFERED_OUTPUT_SIZE (1024 * 32)
 
@@ -1230,26 +1229,21 @@ nsresult nsWebBrowserPersist::SaveURIInt
 
   nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
   if (mPersistFlags & PERSIST_FLAGS_BYPASS_CACHE) {
     loadFlags |= nsIRequest::LOAD_BYPASS_CACHE;
   } else if (mPersistFlags & PERSIST_FLAGS_FROM_CACHE) {
     loadFlags |= nsIRequest::LOAD_FROM_CACHE;
   }
 
-  // Create a new cookieSettings for this download in order to send cookies
-  // based on the current state of the prefs/permissions.
-  nsCOMPtr<nsICookieSettings> cookieSettings =
-      mozilla::net::CookieSettings::Create();
-
   // Open a channel to the URI
   nsCOMPtr<nsIChannel> inputChannel;
   rv = NS_NewChannel(getter_AddRefs(inputChannel), aURI, aTriggeringPrincipal,
                      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
-                     nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD, cookieSettings,
+                     nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD,
                      nullptr,  // aPerformanceStorage
                      nullptr,  // aLoadGroup
                      static_cast<nsIInterfaceRequestor *>(this), loadFlags);
 
   nsCOMPtr<nsIPrivateBrowsingChannel> pbChannel =
       do_QueryInterface(inputChannel);
   if (pbChannel) {
     pbChannel->SetPrivate(aIsPrivate);
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -2014,20 +2014,18 @@ void RuntimeService::ResumeWorkersForWin
     workers[index]->ParentWindowResumed();
   }
 }
 
 void RuntimeService::PropagateFirstPartyStorageAccessGranted(
     nsPIDOMWindowInner* aWindow) {
   AssertIsOnMainThread();
   MOZ_ASSERT(aWindow);
-  MOZ_ASSERT_IF(
-      aWindow->GetExtantDoc(),
-      aWindow->GetExtantDoc()->CookieSettings()->GetCookieBehavior() ==
-          nsICookieService::BEHAVIOR_REJECT_TRACKER);
+  MOZ_ASSERT(StaticPrefs::network_cookie_cookieBehavior() ==
+             nsICookieService::BEHAVIOR_REJECT_TRACKER);
 
   nsTArray<WorkerPrivate*> workers;
   GetWorkersForWindow(aWindow, workers);
 
   for (uint32_t index = 0; index < workers.Length(); index++) {
     workers[index]->PropagateFirstPartyStorageAccessGranted();
   }
 }
@@ -2398,20 +2396,18 @@ void ResumeWorkersForWindow(nsPIDOMWindo
   if (runtime) {
     runtime->ResumeWorkersForWindow(aWindow);
   }
 }
 
 void PropagateFirstPartyStorageAccessGrantedToWorkers(
     nsPIDOMWindowInner* aWindow) {
   AssertIsOnMainThread();
-  MOZ_ASSERT_IF(
-      aWindow->GetExtantDoc(),
-      aWindow->GetExtantDoc()->CookieSettings()->GetCookieBehavior() ==
-          nsICookieService::BEHAVIOR_REJECT_TRACKER);
+  MOZ_ASSERT(StaticPrefs::network_cookie_cookieBehavior() ==
+             nsICookieService::BEHAVIOR_REJECT_TRACKER);
 
   RuntimeService* runtime = RuntimeService::GetService();
   if (runtime) {
     runtime->PropagateFirstPartyStorageAccessGranted(aWindow);
   }
 }
 
 WorkerPrivate* GetWorkerPrivateFromContext(JSContext* aCx) {
--- a/dom/workers/ScriptLoader.cpp
+++ b/dom/workers/ScriptLoader.cpp
@@ -120,25 +120,27 @@ nsresult ConstructURI(const nsAString& a
   }
 
   if (NS_FAILED(rv)) {
     return NS_ERROR_DOM_SYNTAX_ERR;
   }
   return NS_OK;
 }
 
-nsresult ChannelFromScriptURL(
-    nsIPrincipal* principal, Document* parentDoc, WorkerPrivate* aWorkerPrivate,
-    nsILoadGroup* loadGroup, nsIIOService* ios,
-    nsIScriptSecurityManager* secMan, nsIURI* aScriptURL,
-    const Maybe<ClientInfo>& aClientInfo,
-    const Maybe<ServiceWorkerDescriptor>& aController, bool aIsMainScript,
-    WorkerScriptType aWorkerScriptType,
-    nsContentPolicyType aMainScriptContentPolicyType, nsLoadFlags aLoadFlags,
-    nsICookieSettings* aCookieSettings, nsIChannel** aChannel) {
+nsresult ChannelFromScriptURL(nsIPrincipal* principal, Document* parentDoc,
+                              WorkerPrivate* aWorkerPrivate,
+                              nsILoadGroup* loadGroup, nsIIOService* ios,
+                              nsIScriptSecurityManager* secMan,
+                              nsIURI* aScriptURL,
+                              const Maybe<ClientInfo>& aClientInfo,
+                              const Maybe<ServiceWorkerDescriptor>& aController,
+                              bool aIsMainScript,
+                              WorkerScriptType aWorkerScriptType,
+                              nsContentPolicyType aMainScriptContentPolicyType,
+                              nsLoadFlags aLoadFlags, nsIChannel** aChannel) {
   AssertIsOnMainThread();
 
   nsresult rv;
   nsCOMPtr<nsIURI> uri = aScriptURL;
 
   // If we have the document, use it. Unfortunately, for dedicated workers
   // 'parentDoc' ends up being the parent document, which is not the document
   // that we want to use. So make sure to avoid using 'parentDoc' in that
@@ -199,17 +201,21 @@ nsresult ChannelFromScriptURL(
   //
   // Note, if we ever allow service worker scripts to be loaded from network
   // here we need to configure the channel properly.  For example, it must
   // not allow redirects.
   MOZ_DIAGNOSTIC_ASSERT(contentPolicyType !=
                         nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER);
 
   nsCOMPtr<nsIChannel> channel;
-  if (parentDoc) {
+  // If we have the document, use it. Unfortunately, for dedicated workers
+  // 'parentDoc' ends up being the parent document, which is not the document
+  // that we want to use. So make sure to avoid using 'parentDoc' in that
+  // situation.
+  if (parentDoc && parentDoc->NodePrincipal() == principal) {
     rv = NS_NewChannel(getter_AddRefs(channel), uri, parentDoc, secFlags,
                        contentPolicyType,
                        nullptr,  // aPerformanceStorage
                        loadGroup,
                        nullptr,  // aCallbacks
                        aLoadFlags, ios);
     NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_SECURITY_ERR);
   } else {
@@ -223,23 +229,23 @@ nsresult ChannelFromScriptURL(
     if (aWorkerPrivate && !aIsMainScript) {
       performanceStorage = aWorkerPrivate->GetPerformanceStorage();
       cspEventListener = aWorkerPrivate->CSPEventListener();
     }
 
     if (aClientInfo.isSome()) {
       rv = NS_NewChannel(getter_AddRefs(channel), uri, principal,
                          aClientInfo.ref(), aController, secFlags,
-                         contentPolicyType, aCookieSettings, performanceStorage,
-                         loadGroup, nullptr,  // aCallbacks
+                         contentPolicyType, performanceStorage, loadGroup,
+                         nullptr,  // aCallbacks
                          aLoadFlags, ios);
     } else {
       rv = NS_NewChannel(getter_AddRefs(channel), uri, principal, secFlags,
-                         contentPolicyType, aCookieSettings, performanceStorage,
-                         loadGroup, nullptr,  // aCallbacks
+                         contentPolicyType, performanceStorage, loadGroup,
+                         nullptr,  // aCallbacks
                          aLoadFlags, ios);
     }
 
     NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_SECURITY_ERR);
 
     if (cspEventListener) {
       nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
       rv = loadInfo->SetCspEventListener(cspEventListener);
@@ -949,21 +955,21 @@ class ScriptLoaderRunnable final : publi
       bool useDefaultEncoding = !(!parentWorker && IsMainWorkerScript());
       nsCOMPtr<nsIURI> url;
       rv = ConstructURI(loadInfo.mURL, baseURI, parentDoc, useDefaultEncoding,
                         getter_AddRefs(url));
       if (NS_FAILED(rv)) {
         return rv;
       }
 
-      rv = ChannelFromScriptURL(
-          principal, parentDoc, mWorkerPrivate, loadGroup, ios, secMan, url,
-          mClientInfo, mController, IsMainWorkerScript(), mWorkerScriptType,
-          mWorkerPrivate->ContentPolicyType(), loadFlags,
-          mWorkerPrivate->CookieSettings(), getter_AddRefs(channel));
+      rv = ChannelFromScriptURL(principal, parentDoc, mWorkerPrivate, loadGroup,
+                                ios, secMan, url, mClientInfo, mController,
+                                IsMainWorkerScript(), mWorkerScriptType,
+                                mWorkerPrivate->ContentPolicyType(), loadFlags,
+                                getter_AddRefs(channel));
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
 
     // We need to know which index we're on in OnStreamComplete so we know
     // where to put the result.
     RefPtr<LoaderListener> listener = new LoaderListener(this, aIndex);
@@ -1818,34 +1824,32 @@ class ChannelGetterRunnable final : publ
     // Figure out our base URI.
     nsCOMPtr<nsIURI> baseURI = mWorkerPrivate->GetBaseURI();
     MOZ_ASSERT(baseURI);
 
     // May be null.
     nsCOMPtr<Document> parentDoc = mWorkerPrivate->GetDocument();
 
     mLoadInfo.mLoadGroup = mWorkerPrivate->GetLoadGroup();
-    mLoadInfo.mCookieSettings = mWorkerPrivate->CookieSettings();
 
     // Nested workers use default uri encoding.
     nsCOMPtr<nsIURI> url;
     mResult =
         ConstructURI(mScriptURL, baseURI, parentDoc, true, getter_AddRefs(url));
     NS_ENSURE_SUCCESS(mResult, true);
 
     Maybe<ClientInfo> clientInfo;
     clientInfo.emplace(mClientInfo);
 
     nsCOMPtr<nsIChannel> channel;
     mResult = workerinternals::ChannelFromScriptURLMainThread(
         mLoadInfo.mLoadingPrincipal, parentDoc, mLoadInfo.mLoadGroup, url,
         clientInfo,
         // Nested workers are always dedicated.
-        nsIContentPolicy::TYPE_INTERNAL_WORKER, mLoadInfo.mCookieSettings,
-        getter_AddRefs(channel));
+        nsIContentPolicy::TYPE_INTERNAL_WORKER, getter_AddRefs(channel));
     NS_ENSURE_SUCCESS(mResult, true);
 
     mResult = mLoadInfo.SetPrincipalFromChannel(channel);
     NS_ENSURE_SUCCESS(mResult, true);
 
     mLoadInfo.mChannel = channel.forget();
     return true;
   }
@@ -2150,30 +2154,28 @@ void LoadAllScripts(WorkerPrivate* aWork
 
 } /* anonymous namespace */
 
 namespace workerinternals {
 
 nsresult ChannelFromScriptURLMainThread(
     nsIPrincipal* aPrincipal, Document* aParentDoc, nsILoadGroup* aLoadGroup,
     nsIURI* aScriptURL, const Maybe<ClientInfo>& aClientInfo,
-    nsContentPolicyType aMainScriptContentPolicyType,
-    nsICookieSettings* aCookieSettings, nsIChannel** aChannel) {
+    nsContentPolicyType aMainScriptContentPolicyType, nsIChannel** aChannel) {
   AssertIsOnMainThread();
 
   nsCOMPtr<nsIIOService> ios(do_GetIOService());
 
   nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
   NS_ASSERTION(secMan, "This should never be null!");
 
   return ChannelFromScriptURL(
       aPrincipal, aParentDoc, nullptr, aLoadGroup, ios, secMan, aScriptURL,
       aClientInfo, Maybe<ServiceWorkerDescriptor>(), true, WorkerScript,
-      aMainScriptContentPolicyType, nsIRequest::LOAD_NORMAL, aCookieSettings,
-      aChannel);
+      aMainScriptContentPolicyType, nsIRequest::LOAD_NORMAL, aChannel);
 }
 
 nsresult ChannelFromScriptURLWorkerThread(JSContext* aCx,
                                           WorkerPrivate* aParent,
                                           const nsAString& aScriptURL,
                                           WorkerLoadInfo& aLoadInfo) {
   aParent->AssertIsOnWorkerThread();
 
--- a/dom/workers/ScriptLoader.h
+++ b/dom/workers/ScriptLoader.h
@@ -11,17 +11,16 @@
 #include "nsIContentPolicy.h"
 #include "nsStringFwd.h"
 
 class nsIPrincipal;
 class nsIURI;
 
 class nsILoadGroup;
 class nsIChannel;
-class nsICookieSettings;
 
 namespace mozilla {
 
 class ErrorResult;
 
 namespace dom {
 
 struct WorkerLoadInfo;
@@ -29,18 +28,17 @@ class WorkerPrivate;
 
 enum WorkerScriptType { WorkerScript, DebuggerScript };
 
 namespace workerinternals {
 
 nsresult ChannelFromScriptURLMainThread(
     nsIPrincipal* aPrincipal, Document* aParentDoc, nsILoadGroup* aLoadGroup,
     nsIURI* aScriptURL, const Maybe<ClientInfo>& aClientInfo,
-    nsContentPolicyType aContentPolicyType, nsICookieSettings* aCookieSettings,
-    nsIChannel** aChannel);
+    nsContentPolicyType aContentPolicyType, nsIChannel** aChannel);
 
 nsresult ChannelFromScriptURLWorkerThread(JSContext* aCx,
                                           WorkerPrivate* aParent,
                                           const nsAString& aScriptURL,
                                           WorkerLoadInfo& aLoadInfo);
 
 void ReportLoadError(ErrorResult& aRv, nsresult aLoadResult,
                      const nsAString& aScriptURL);
--- a/dom/workers/WorkerLoadInfo.h
+++ b/dom/workers/WorkerLoadInfo.h
@@ -14,17 +14,16 @@
 #include "nsIInterfaceRequestor.h"
 #include "nsILoadContext.h"
 #include "nsIRequest.h"
 #include "nsISupportsImpl.h"
 #include "nsIWeakReferenceUtils.h"
 
 class nsIChannel;
 class nsIContentSecurityPolicy;
-class nsICookieSettings;
 class nsILoadGroup;
 class nsIPrincipal;
 class nsIRunnable;
 class nsIScriptContext;
 class nsITabChild;
 class nsIURI;
 class nsPIDOMWindowInner;
 
@@ -46,19 +45,16 @@ struct WorkerLoadInfoData {
 
   // This is the principal of the global (parent worker or a window) loading
   // the worker. It can be null if we are executing a ServiceWorker, otherwise,
   // except for data: URL, it must subsumes the worker principal.
   // If we load a data: URL, mPrincipal will be a null principal.
   nsCOMPtr<nsIPrincipal> mLoadingPrincipal;
   nsCOMPtr<nsIPrincipal> mPrincipal;
 
-  // Taken from the parent context.
-  nsCOMPtr<nsICookieSettings> mCookieSettings;
-
   nsCOMPtr<nsIScriptContext> mScriptContext;
   nsCOMPtr<nsPIDOMWindowInner> mWindow;
   nsCOMPtr<nsIContentSecurityPolicy> mCSP;
   nsCOMPtr<nsIChannel> mChannel;
   nsCOMPtr<nsILoadGroup> mLoadGroup;
 
   class InterfaceRequestor final : public nsIInterfaceRequestor {
     NS_DECL_ISUPPORTS
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -54,17 +54,16 @@
 #include "nsRFPService.h"
 #include "nsSandboxFlags.h"
 #include "nsUTF8Utils.h"
 
 #include "RuntimeService.h"
 #include "ScriptLoader.h"
 #include "mozilla/dom/ServiceWorkerEvents.h"
 #include "mozilla/dom/ServiceWorkerManager.h"
-#include "mozilla/net/CookieSettings.h"
 #include "WorkerCSPEventListener.h"
 #include "WorkerDebugger.h"
 #include "WorkerDebuggerManager.h"
 #include "WorkerError.h"
 #include "WorkerEventTarget.h"
 #include "WorkerNavigator.h"
 #include "WorkerRef.h"
 #include "WorkerRunnable.h"
@@ -2471,17 +2470,16 @@ nsresult WorkerPrivate::GetLoadInfo(JSCo
 
       loadInfo.mXHRParamsAllowed = perm == nsIPermissionManager::ALLOW_ACTION;
 
       loadInfo.mFromWindow = true;
       loadInfo.mWindowID = globalWindow->WindowID();
       nsContentUtils::StorageAccess access =
           nsContentUtils::StorageAllowedForWindow(globalWindow);
       loadInfo.mStorageAllowed = access > nsContentUtils::StorageAccess::eDeny;
-      loadInfo.mCookieSettings = document->CookieSettings();
       loadInfo.mOriginAttributes =
           nsContentUtils::GetOriginAttributes(document);
       loadInfo.mParentController = globalWindow->GetController();
       loadInfo.mSecureContext = loadInfo.mWindow->IsSecureContext()
                                     ? WorkerLoadInfo::eSecureContext
                                     : WorkerLoadInfo::eInsecureContext;
     } else {
       // Not a window
@@ -2517,19 +2515,16 @@ nsresult WorkerPrivate::GetLoadInfo(JSCo
         if (NS_FAILED(rv)) {
           return rv;
         }
       }
       loadInfo.mXHRParamsAllowed = true;
       loadInfo.mFromWindow = false;
       loadInfo.mWindowID = UINT64_MAX;
       loadInfo.mStorageAllowed = true;
-      loadInfo.mCookieSettings = mozilla::net::CookieSettings::Create();
-      MOZ_ASSERT(loadInfo.mCookieSettings);
-
       loadInfo.mOriginAttributes = OriginAttributes();
     }
 
     MOZ_ASSERT(loadInfo.mLoadingPrincipal);
     MOZ_ASSERT(isChrome || !loadInfo.mDomain.IsEmpty());
 
     if (!loadInfo.mLoadGroup || aLoadGroupBehavior == OverrideLoadGroup) {
       OverrideLoadInfoLoadGroup(loadInfo, loadInfo.mLoadingPrincipal);
@@ -2539,20 +2534,20 @@ nsresult WorkerPrivate::GetLoadInfo(JSCo
 
     // Top level workers' main script use the document charset for the script
     // uri encoding.
     nsCOMPtr<nsIURI> url;
     rv = nsContentUtils::NewURIWithDocumentCharset(
         getter_AddRefs(url), aScriptURL, document, loadInfo.mBaseURI);
     NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_SYNTAX_ERR);
 
-    rv = ChannelFromScriptURLMainThread(
-        loadInfo.mLoadingPrincipal, document, loadInfo.mLoadGroup, url,
-        clientInfo, ContentPolicyType(aWorkerType), loadInfo.mCookieSettings,
-        getter_AddRefs(loadInfo.mChannel));
+    rv = ChannelFromScriptURLMainThread(loadInfo.mLoadingPrincipal, document,
+                                        loadInfo.mLoadGroup, url, clientInfo,
+                                        ContentPolicyType(aWorkerType),
+                                        getter_AddRefs(loadInfo.mChannel));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = NS_GetFinalChannelURI(loadInfo.mChannel,
                                getter_AddRefs(loadInfo.mResolvedScriptURI));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = loadInfo.SetPrincipalFromChannel(loadInfo.mChannel);
     NS_ENSURE_SUCCESS(rv, rv);
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -725,22 +725,16 @@ class WorkerPrivate : public RelativeTim
   }
 
   bool IsStorageAllowed() const {
     AssertIsOnWorkerThread();
     return mLoadInfo.mStorageAllowed ||
            mLoadInfo.mFirstPartyStorageAccessGranted;
   }
 
-  nsICookieSettings* CookieSettings() const {
-    // Any thread.
-    MOZ_ASSERT(mLoadInfo.mCookieSettings);
-    return mLoadInfo.mCookieSettings;
-  }
-
   const OriginAttributes& GetOriginAttributes() const {
     return mLoadInfo.mOriginAttributes;
   }
 
   // Determine if the SW testing per-window flag is set by devtools
   bool ServiceWorkersTestingInWindow() const {
     return mLoadInfo.mServiceWorkersTestingInWindow;
   }
--- a/dom/workers/remoteworkers/RemoteWorkerChild.cpp
+++ b/dom/workers/remoteworkers/RemoteWorkerChild.cpp
@@ -13,17 +13,16 @@
 #include "mozilla/dom/ServiceWorkerUtils.h"
 #include "mozilla/dom/workerinternals/ScriptLoader.h"
 #include "mozilla/dom/WorkerError.h"
 #include "mozilla/dom/WorkerPrivate.h"
 #include "mozilla/dom/WorkerRef.h"
 #include "mozilla/dom/WorkerRunnable.h"
 #include "mozilla/ipc/BackgroundUtils.h"
 #include "mozilla/ipc/URIUtils.h"
-#include "mozilla/net/CookieSettings.h"
 #include "nsIConsoleReportCollector.h"
 #include "nsIPrincipal.h"
 #include "nsNetUtil.h"
 #include "nsProxyRelease.h"
 
 namespace mozilla {
 
 using namespace ipc;
@@ -265,17 +264,16 @@ nsresult RemoteWorkerChild::ExecWorkerOn
   info.mPrincipalInfo = new PrincipalInfo(aData.principalInfo());
 
   info.mDomain = aData.domain();
   info.mPrincipal = principal;
   info.mLoadingPrincipal = loadingPrincipal;
   info.mStorageAllowed = aData.isStorageAccessAllowed();
   info.mOriginAttributes =
       BasePrincipal::Cast(principal)->OriginAttributesRef();
-  info.mCookieSettings = net::CookieSettings::Create();
 
   // Default CSP permissions for now.  These will be overrided if necessary
   // based on the script CSP headers during load in ScriptLoader.
   info.mEvalAllowed = true;
   info.mReportCSPViolations = false;
   info.mSecureContext = aData.isSecureContext()
                             ? WorkerLoadInfo::eSecureContext
                             : WorkerLoadInfo::eInsecureContext;
@@ -298,17 +296,17 @@ nsresult RemoteWorkerChild::ExecWorkerOn
 
   // Top level workers' main script use the document charset for the script
   // uri encoding.
   rv = ChannelFromScriptURLMainThread(
       info.mLoadingPrincipal, nullptr /* parent document */, info.mLoadGroup,
       info.mResolvedScriptURI, clientInfo,
       aData.isSharedWorker() ? nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER
                              : nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER,
-      info.mCookieSettings, getter_AddRefs(info.mChannel));
+      getter_AddRefs(info.mChannel));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   AutoJSAPI jsapi;
   jsapi.Init();
 
   ErrorResult error;
--- a/dom/workers/test/mochitest.ini
+++ b/dom/workers/test/mochitest.ini
@@ -50,16 +50,17 @@ support-files =
   onLine_worker_child.js
   onLine_worker_head.js
   promise_worker.js
   recursion_worker.js
   recursiveOnerror_worker.js
   redirect_to_foreign.sjs
   rvals_worker.js
   sharedWorker_sharedWorker.js
+  sharedWorker_thirdparty_frame.html
   simpleThread_worker.js
   suspend_window.html
   suspend_worker.js
   terminate_worker.js
   test_csp.html^headers^
   test_csp.js
   referrer_worker.html
   threadErrors_worker1.js
@@ -167,19 +168,16 @@ skip-if = toolkit == 'android'
 [test_promise_resolved_with_string.html]
 [test_recursion.html]
 [test_recursiveOnerror.html]
 [test_resolveWorker.html]
 [test_resolveWorker-assignment.html]
 [test_rvals.html]
 [test_sharedWorker.html]
 [test_sharedWorker_thirdparty.html]
-support-files =
-  sharedWorker_thirdparty_frame.html
-  sharedWorker_thirdparty_window.html
 [test_simpleThread.html]
 [test_suspend.html]
 [test_terminate.html]
 [test_threadErrors.html]
 [test_threadTimeouts.html]
 [test_throwingOnerror.html]
 [test_timeoutTracing.html]
 [test_transferable.html]
deleted file mode 100644
--- a/dom/workers/test/sharedWorker_thirdparty_window.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-  Any copyright is dedicated to the Public Domain.
-  http://creativecommons.org/publicdomain/zero/1.0/
--->
-<!DOCTYPE HTML>
-<html>
-<head>
-  <title>Test for SharedWorker in 3rd Party Iframes</title>
-</head>
-<body>
-  <script>
-
-  let url = new URL(window.location);
-
-  let frame = document.createElement('iframe');
-  frame.src =
-    'http://example.org/tests/dom/workers/test/sharedWorker_thirdparty_frame.html?name=' + url.searchParams.get('name');
-  document.body.appendChild(frame);
-  window.addEventListener('message', evt => {
-    frame.remove();
-    opener.postMessage(evt.data, "*");
-  }, {once: true});
-
-  </script>
-</body>
-</html>
--- a/dom/workers/test/test_sharedWorker_thirdparty.html
+++ b/dom/workers/test/test_sharedWorker_thirdparty.html
@@ -6,28 +6,32 @@
 <html>
 <head>
   <title>Test for SharedWorker in 3rd Party Iframes</title>
   <script src="/tests/SimpleTest/SimpleTest.js"> </script>
   <script src="/tests/SimpleTest/AddTask.js"> </script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
 </head>
 <body>
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test">
   <script class="testbody">
 
   function testThirdPartyFrame(name) {
     return new Promise(resolve => {
-      // Let's use a window, loading the same origin, in order to have the new
-      // cookie-policy applied.
-      let w = window.open("sharedWorker_thirdparty_window.html?name=" + name);
+      let frame = document.createElement('iframe');
+      frame.src =
+        'http://example.org/tests/dom/workers/test/sharedWorker_thirdparty_frame.html?name=' + name;
+      document.body.appendChild(frame);
       window.addEventListener('message', function messageListener(evt) {
         if (evt.data.name !== name) {
           return;
         }
-        w.close();
+        frame.remove();
         window.removeEventListener('message', messageListener);
         resolve(evt.data.result);
       });
     });
   }
 
   const COOKIE_BEHAVIOR_ACCEPT        = 0;
   const COOKIE_BEHAVIOR_REJECTFOREIGN = 1;
@@ -46,10 +50,11 @@
       ["network.cookie.cookieBehavior", COOKIE_BEHAVIOR_REJECTFOREIGN]
     ]});
     let result = await testThirdPartyFrame('blocked');
     ok(result === 'blocked',
        'SharedWorker should not be allowed when 3rd party iframes are denied storage');
   });
 
   </script>
+  </pre>
 </body>
 </html>
--- a/dom/xbl/nsXBLService.cpp
+++ b/dom/xbl/nsXBLService.cpp
@@ -1042,17 +1042,16 @@ nsresult nsXBLService::FetchBindingDocum
         nsIContentPolicy::TYPE_XBL,
         nullptr,  // aPerformanceStorage
         loadGroup);
   } else {
     rv = NS_NewChannel(getter_AddRefs(channel), aDocumentURI,
                        nsContentUtils::GetSystemPrincipal(),
                        nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS,
                        nsIContentPolicy::TYPE_XBL,
-                       nullptr,  // nsICookieSettings
                        nullptr,  // PerformanceStorage
                        loadGroup);
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!aForceSyncLoad) {
     // We can be asynchronous
     nsXBLStreamListener* xblListener =
--- a/dom/xhr/XMLHttpRequest.cpp
+++ b/dom/xhr/XMLHttpRequest.cpp
@@ -2,18 +2,16 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "XMLHttpRequest.h"
 #include "XMLHttpRequestMainThread.h"
 #include "XMLHttpRequestWorker.h"
-#include "mozilla/net/CookieSettings.h"
-#include "nsGlobalWindowInner.h"
 
 namespace mozilla {
 namespace dom {
 
 /* static */
 already_AddRefed<XMLHttpRequest> XMLHttpRequest::Constructor(
     const GlobalObject& aGlobal, const MozXMLHttpRequestParameters& aParams,
     ErrorResult& aRv) {
@@ -22,33 +20,18 @@ already_AddRefed<XMLHttpRequest> XMLHttp
         do_QueryInterface(aGlobal.GetAsSupports());
     nsCOMPtr<nsIScriptObjectPrincipal> principal =
         do_QueryInterface(aGlobal.GetAsSupports());
     if (!global || !principal) {
       aRv.Throw(NS_ERROR_FAILURE);
       return nullptr;
     }
 
-    nsCOMPtr<nsICookieSettings> cookieSettings;
-    nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(global);
-    if (window) {
-      Document* document = window->GetExtantDoc();
-      if (NS_WARN_IF(!document)) {
-        aRv.Throw(NS_ERROR_FAILURE);
-        return nullptr;
-      }
-
-      cookieSettings = document->CookieSettings();
-    } else {
-      // We are here because this is a sandbox.
-      cookieSettings = net::CookieSettings::Create();
-    }
-
     RefPtr<XMLHttpRequestMainThread> req = new XMLHttpRequestMainThread();
-    req->Construct(principal->GetPrincipal(), global, cookieSettings);
+    req->Construct(principal->GetPrincipal(), global);
     req->InitParameters(aParams.mMozAnon, aParams.mMozSystem);
     return req.forget();
   }
 
   return XMLHttpRequestWorker::Construct(aGlobal, aParams, aRv);
 }
 
 }  // namespace dom
--- a/dom/xhr/XMLHttpRequestMainThread.cpp
+++ b/dom/xhr/XMLHttpRequestMainThread.cpp
@@ -2329,26 +2329,24 @@ nsresult XMLHttpRequestMainThread::Creat
                        nullptr,  // aPerformanceStorage
                        loadGroup,
                        nullptr,  // aCallbacks
                        loadFlags);
   } else if (mClientInfo.isSome()) {
     rv = NS_NewChannel(getter_AddRefs(mChannel), mRequestURL, mPrincipal,
                        mClientInfo.ref(), mController, secFlags,
                        nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST,
-                       mCookieSettings,
                        mPerformanceStorage,  // aPerformanceStorage
                        loadGroup,
                        nullptr,  // aCallbacks
                        loadFlags);
   } else {
     // Otherwise use the principal.
     rv = NS_NewChannel(getter_AddRefs(mChannel), mRequestURL, mPrincipal,
                        secFlags, nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST,
-                       mCookieSettings,
                        mPerformanceStorage,  // aPerformanceStorage
                        loadGroup,
                        nullptr,  // aCallbacks
                        loadFlags);
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (mCSPEventListener) {
--- a/dom/xhr/XMLHttpRequestMainThread.h
+++ b/dom/xhr/XMLHttpRequestMainThread.h
@@ -194,26 +194,24 @@ class XMLHttpRequestMainThread final : p
     eRedirect,
     eTerminated,
     ENUM_MAX
   };
 
   XMLHttpRequestMainThread();
 
   void Construct(nsIPrincipal* aPrincipal, nsIGlobalObject* aGlobalObject,
-                 nsICookieSettings* aCookieSettings, nsIURI* aBaseURI = nullptr,
-                 nsILoadGroup* aLoadGroup = nullptr,
+                 nsIURI* aBaseURI = nullptr, nsILoadGroup* aLoadGroup = nullptr,
                  PerformanceStorage* aPerformanceStorage = nullptr,
                  nsICSPEventListener* aCSPEventListener = nullptr) {
     MOZ_ASSERT(aPrincipal);
     mPrincipal = aPrincipal;
     BindToOwner(aGlobalObject);
     mBaseURI = aBaseURI;
     mLoadGroup = aLoadGroup;
-    mCookieSettings = aCookieSettings;
     mPerformanceStorage = aPerformanceStorage;
     mCSPEventListener = aCSPEventListener;
   }
 
   void InitParameters(bool aAnon, bool aSystem);
 
   void SetParameters(bool aAnon, bool aSystem) {
     mIsAnon = aAnon || aSystem;
@@ -491,18 +489,16 @@ class XMLHttpRequestMainThread final : p
   nsCOMPtr<nsIPrincipal> mPrincipal;
   nsCOMPtr<nsIChannel> mChannel;
   nsCString mRequestMethod;
   nsCOMPtr<nsIURI> mRequestURL;
   RefPtr<Document> mResponseXML;
 
   nsCOMPtr<nsIStreamListener> mXMLParserStreamListener;
 
-  nsCOMPtr<nsICookieSettings> mCookieSettings;
-
   RefPtr<PerformanceStorage> mPerformanceStorage;
   nsCOMPtr<nsICSPEventListener> mCSPEventListener;
 
   // used to implement getAllResponseHeaders()
   class nsHeaderVisitor : public nsIHttpHeaderVisitor {
     struct HeaderEntry final {
       nsCString mName;
       nsCString mValue;
--- a/dom/xhr/XMLHttpRequestWorker.cpp
+++ b/dom/xhr/XMLHttpRequestWorker.cpp
@@ -774,17 +774,16 @@ bool Proxy::Init() {
   if (ownerWindow && !ownerWindow->IsCurrentInnerWindow()) {
     NS_WARNING("Window has navigated, cannot create XHR here.");
     return false;
   }
 
   mXHR = new XMLHttpRequestMainThread();
   mXHR->Construct(mWorkerPrivate->GetPrincipal(),
                   ownerWindow ? ownerWindow->AsGlobal() : nullptr,
-                  mWorkerPrivate->CookieSettings(),
                   mWorkerPrivate->GetBaseURI(), mWorkerPrivate->GetLoadGroup(),
                   mWorkerPrivate->GetPerformanceStorage(),
                   mWorkerPrivate->CSPEventListener());
 
   mXHR->SetParameters(mMozAnon, mMozSystem);
   mXHR->SetClientInfoAndController(mClientInfo, mController);
 
   ErrorResult rv;
--- a/dom/xhr/tests/mochitest.ini
+++ b/dom/xhr/tests/mochitest.ini
@@ -74,17 +74,16 @@ 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,41 +9,66 @@ 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">
 
-  document.cookie = "a=cookie_is_set";
+  var worker = new Worker("xhr_worker.js");
+
+  var gotUploadLoad = false, gotLoadend = false;
 
-  SpecialPowers.pushPrefEnv({ set: [[ "network.cookie.cookieBehavior", 1 ]] },
-                            () => {
-    let w = window.open("window_worker_xhr_3rdparty.html");
-
-    onmessage = e => {
-      if (e.data.type == "finish") {
-        w.close();
+  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.");
         SimpleTest.finish();
-        return;
+        break;
       }
+      default: {
+        ok(false, "Unexpected message");
+        SimpleTest.finish();
+      }
+    }
+  };
 
-      if (e.data.type == "test") {
-        ok(e.data.test, e.data.msg);
-        return;
-      }
+  worker.onerror = function(event) {
+    is(event.target, worker);
+    ok(false, "Worker had an error:" + event.message);
+    SimpleTest.finish();
+  }
 
-      ok(false, "Invalid message.");
-    }
-  });
+  document.cookie = "a=cookie_is_set";
+  SpecialPowers.pushPrefEnv({ set: [[ "network.cookie.cookieBehavior", 1 ]] },
+                            () => worker.postMessage("worker_file_getcookie.sjs"));
 
   SimpleTest.waitForExplicitFinish();
 
 </script>
 </pre>
 </body>
 </html>
deleted file mode 100644
--- a/dom/xhr/tests/window_worker_xhr_3rdparty.html
+++ /dev/null
@@ -1,71 +0,0 @@
-<!--
-  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/dom/xml/nsXMLPrettyPrinter.cpp
+++ b/dom/xml/nsXMLPrettyPrinter.cpp
@@ -63,19 +63,18 @@ nsresult nsXMLPrettyPrinter::PrettyPrint
   rv = NS_NewURI(
       getter_AddRefs(xslUri),
       NS_LITERAL_CSTRING("chrome://global/content/xml/XMLPrettyPrint.xsl"));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<Document> xslDocument;
   rv = nsSyncLoadService::LoadDocument(
       xslUri, nsIContentPolicy::TYPE_XSLT, nsContentUtils::GetSystemPrincipal(),
-      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, nullptr,
-      aDocument->CookieSettings(), true, mozilla::net::RP_Unset,
-      getter_AddRefs(xslDocument));
+      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL, nullptr, true,
+      mozilla::net::RP_Unset, getter_AddRefs(xslDocument));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Transform the document
   RefPtr<txMozillaXSLTProcessor> transformer = new txMozillaXSLTProcessor();
   ErrorResult err;
   transformer->ImportStylesheet(*xslDocument, err);
   if (NS_WARN_IF(err.Failed())) {
     return err.StealNSResult();
--- a/dom/xslt/xml/txXMLParser.cpp
+++ b/dom/xslt/xml/txXMLParser.cpp
@@ -33,18 +33,17 @@ nsresult txParseDocumentFromURI(const ns
 
   // Raw pointer, we want the resulting txXPathNode to hold a reference to
   // the document.
   Document* theDocument = nullptr;
   nsAutoSyncOperation sync(loaderDocument);
   rv = nsSyncLoadService::LoadDocument(
       documentURI, nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST,
       loaderDocument->NodePrincipal(),
-      nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS, loadGroup,
-      loaderDocument->CookieSettings(), true,
+      nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS, loadGroup, true,
       loaderDocument->GetReferrerPolicy(), &theDocument);
 
   if (NS_FAILED(rv)) {
     aErrMsg.AppendLiteral("Document load of ");
     aErrMsg.Append(aHref);
     aErrMsg.AppendLiteral(" failed.");
     return NS_FAILED(rv) ? rv : NS_ERROR_FAILURE;
   }
--- a/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
+++ b/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp
@@ -558,18 +558,17 @@ nsresult txSyncCompileObserver::loadURI(
   if (mProcessor) {
     source = mProcessor->GetSourceContentModel();
   }
   nsAutoSyncOperation sync(source ? source->OwnerDoc() : nullptr);
   nsCOMPtr<Document> document;
 
   rv = nsSyncLoadService::LoadDocument(
       uri, nsIContentPolicy::TYPE_XSLT, referrerPrincipal,
-      nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS, nullptr,
-      source ? source->OwnerDoc()->CookieSettings() : nullptr, false,
+      nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS, nullptr, false,
       aReferrerPolicy, getter_AddRefs(document));
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = handleNode(document, aCompiler);
   if (NS_FAILED(rv)) {
     nsAutoCString spec;
     uri->GetSpec(spec);
     aCompiler->cancel(rv, nullptr, NS_ConvertUTF8toUTF16(spec).get());
--- a/extensions/cookie/test/unit/test_cookies_privatebrowsing.js
+++ b/extensions/cookie/test/unit/test_cookies_privatebrowsing.js
@@ -21,19 +21,16 @@ 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.js
+++ b/extensions/cookie/test/unit/test_cookies_thirdparty.js
@@ -1,104 +1,62 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // test third party cookie blocking, for the cases:
 // 1) with null channel
 // 2) with channel, but with no docshell parent
 
 function run_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.
-  let spec1 = "http://foo.com/foo.html";
-  let spec2 = "http://bar.com/bar.html";
-  let uri1 = NetUtil.newURI(spec1);
-  let uri2 = NetUtil.newURI(spec2);
-
-    // test with cookies enabled
-  {
-    Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
+  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});
 
-    let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
-    let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
-
-    do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
-    Services.cookies.removeAll();
-    do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
-    Services.cookies.removeAll();
-  }
+  // test with cookies enabled
+  Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
+  do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
+  Services.cookies.removeAll();
+  do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
+  Services.cookies.removeAll();
 
   // test with third party cookies blocked
-  {
-    Services.prefs.setIntPref("network.cookie.cookieBehavior", 1);
-
-    let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
-    let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
-
-    do_set_cookies(uri1, channel1, true, [0, 0, 0, 0]);
-    Services.cookies.removeAll();
-    do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
-    Services.cookies.removeAll();
-  }
+  Services.prefs.setIntPref("network.cookie.cookieBehavior", 1);
+  do_set_cookies(uri1, channel1, true, [0, 0, 0, 0]);
+  Services.cookies.removeAll();
+  do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
+  Services.cookies.removeAll();
 
   // Force the channel URI to be used when determining the originating URI of
   // the channel.
-  // test with third party cookies blocked
+  var httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal);
+  var httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
+  httpchannel1.forceAllowThirdPartyCookie = true;
+  httpchannel2.forceAllowThirdPartyCookie = true;
 
   // test with cookies enabled
-  {
-    Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
-
-    let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
-    let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal);
-    httpchannel1.forceAllowThirdPartyCookie = true;
-
-    let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
-    let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
-    httpchannel2.forceAllowThirdPartyCookie = true;
-
-    do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
-    Services.cookies.removeAll();
-    do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
-    Services.cookies.removeAll();
-  }
+  Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
+  do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
+  Services.cookies.removeAll();
+  do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
+  Services.cookies.removeAll();
 
   // test with third party cookies blocked
-  {
-    Services.prefs.setIntPref("network.cookie.cookieBehavior", 1);
-
-    let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
-    let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal);
-    httpchannel1.forceAllowThirdPartyCookie = true;
-
-    let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
-    let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
-    httpchannel2.forceAllowThirdPartyCookie = true;
-
-    do_set_cookies(uri1, channel1, true, [0, 1, 1, 2]);
-    Services.cookies.removeAll();
-    do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
-    Services.cookies.removeAll();
-  }
+  Services.prefs.setIntPref("network.cookie.cookieBehavior", 1);
+  do_set_cookies(uri1, channel1, true, [0, 1, 1, 2]);
+  Services.cookies.removeAll();
+  do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
+  Services.cookies.removeAll();
 
   // test with third party cookies limited
-  {
-    Services.prefs.setIntPref("network.cookie.cookieBehavior", 3);
-
-    let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
-    let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal);
-    httpchannel1.forceAllowThirdPartyCookie = true;
-
-    let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
-    let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
-    httpchannel2.forceAllowThirdPartyCookie = true;
-
-    do_set_cookies(uri1, channel1, true, [0, 1, 2, 3]);
-    Services.cookies.removeAll();
-    do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
-    Services.cookies.removeAll();
-    do_set_single_http_cookie(uri1, channel1, 1);
-    do_set_cookies(uri1, channel2, true, [2, 3, 4, 5]);
-    Services.cookies.removeAll();
-  }
+  Services.prefs.setIntPref("network.cookie.cookieBehavior", 3);
+  do_set_cookies(uri1, channel1, true, [0, 1, 2, 3]);
+  Services.cookies.removeAll();
+  do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
+  Services.cookies.removeAll();
+  do_set_single_http_cookie(uri1, channel1, 1);
+  do_set_cookies(uri1, channel2, true, [2, 3, 4, 5]);
+  Services.cookies.removeAll();
 }
--- a/extensions/cookie/test/unit/test_cookies_thirdparty_nonsecure_session.js
+++ b/extensions/cookie/test/unit/test_cookies_thirdparty_nonsecure_session.js
@@ -20,19 +20,16 @@ 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,19 +18,16 @@ 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/extensions/pref/autoconfig/src/nsAutoConfig.cpp
+++ b/extensions/pref/autoconfig/src/nsAutoConfig.cpp
@@ -244,17 +244,16 @@ nsresult nsAutoConfig::downloadAutoConfi
   }
 
   MOZ_LOG(MCD, LogLevel::Debug, ("running MCD url %s\n", mConfigURL.get()));
   // open a channel for the url
   rv = NS_NewChannel(
       getter_AddRefs(channel), url, nsContentUtils::GetSystemPrincipal(),
       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
       nsIContentPolicy::TYPE_OTHER,
-      nullptr,  // nsICookieSettings
       nullptr,  // PerformanceStorage
       nullptr,  // loadGroup
       nullptr,  // aCallbacks
       nsIRequest::INHIBIT_PERSISTENT_CACHING | nsIRequest::LOAD_BYPASS_CACHE);
 
   if (NS_FAILED(rv)) return rv;
 
   rv = channel->AsyncOpen(this);
--- a/image/imgLoader.cpp
+++ b/image/imgLoader.cpp
@@ -830,21 +830,20 @@ static nsresult NewImageChannel(
           aTriggeringPrincipal->OriginAttributesRef());
     }
   } else {
     // either we are loading something inside a document, in which case
     // we should always have a requestingNode, or we are loading something
     // outside a document, in which case the triggeringPrincipal and
     // triggeringPrincipal should always be the systemPrincipal.
     // However, there are exceptions: one is Notifications which create a
-    // channel in the parent process in which case we can't get a
+    // channel in the parent prcoess in which case we can't get a
     // requestingNode.
     rv = NS_NewChannel(aResult, aURI, nsContentUtils::GetSystemPrincipal(),
                        securityFlags, aPolicyType,
-                       nullptr,  // nsICookieSettings
                        nullptr,  // PerformanceStorage
                        nullptr,  // loadGroup
                        callbacks, aLoadFlags);
 
     if (NS_FAILED(rv)) {
       return rv;
     }
 
--- a/ipc/glue/BackgroundUtils.cpp
+++ b/ipc/glue/BackgroundUtils.cpp
@@ -7,17 +7,16 @@
 #include "BackgroundUtils.h"
 
 #include "MainThreadUtils.h"
 #include "mozilla/Assertions.h"
 #include "mozilla/ContentPrincipal.h"
 #include "mozilla/NullPrincipal.h"
 #include "mozilla/ipc/PBackgroundSharedTypes.h"
 #include "mozilla/ipc/URIUtils.h"
-#include "mozilla/net/CookieSettings.h"
 #include "mozilla/net/NeckoChannelParams.h"
 #include "ExpandedPrincipal.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIURI.h"
 #include "nsNetUtil.h"
 #include "mozilla/LoadInfo.h"
 #include "nsContentUtils.h"
 #include "nsString.h"
@@ -482,24 +481,16 @@ nsresult LoadInfoToLoadInfoArgs(nsILoadI
   const Maybe<ServiceWorkerDescriptor>& controller = aLoadInfo->GetController();
   if (controller.isSome()) {
     ipcController = controller.ref().ToIPC();
   }
 
   nsAutoString cspNonce;
   Unused << NS_WARN_IF(NS_FAILED(aLoadInfo->GetCspNonce(cspNonce)));
 
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  rv = aLoadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  CookieSettingsArgs cookieSettingsArgs;
-  static_cast<CookieSettings*>(cookieSettings.get())
-      ->Serialize(cookieSettingsArgs);
-
   *aOptionalLoadInfoArgs = Some(LoadInfoArgs(
       loadingPrincipalInfo, triggeringPrincipalInfo, principalToInheritInfo,
       sandboxedLoadingPrincipalInfo, topLevelPrincipalInfo,
       topLevelStorageAreaPrincipalInfo, optionalResultPrincipalURI,
       aLoadInfo->GetSecurityFlags(), aLoadInfo->InternalContentPolicyType(),
       static_cast<uint32_t>(aLoadInfo->GetTainting()),
       aLoadInfo->GetUpgradeInsecureRequests(),
       aLoadInfo->GetBrowserUpgradeInsecureRequests(),
@@ -520,17 +511,17 @@ nsresult LoadInfoToLoadInfoArgs(nsILoadI
       ancestorPrincipals, aLoadInfo->AncestorOuterWindowIDs(), ipcClientInfo,
       ipcReservedClientInfo, ipcInitialClientInfo, ipcController,
       aLoadInfo->CorsUnsafeHeaders(), aLoadInfo->GetForcePreflight(),
       aLoadInfo->GetIsPreflight(), aLoadInfo->GetLoadTriggeredFromExternal(),
       aLoadInfo->GetServiceWorkerTaintingSynthesized(),
       aLoadInfo->GetDocumentHasUserInteracted(),
       aLoadInfo->GetDocumentHasLoaded(), cspNonce,
       aLoadInfo->GetIsFromProcessingFrameAttributes(),
-      aLoadInfo->GetOpenerPolicy(), cookieSettingsArgs));
+      aLoadInfo->GetOpenerPolicy()));
 
   return NS_OK;
 }
 
 nsresult LoadInfoArgsToLoadInfo(
     const Maybe<LoadInfoArgs>& aOptionalLoadInfoArgs,
     nsILoadInfo** outLoadInfo) {
   if (aOptionalLoadInfoArgs.isNothing()) {
@@ -644,25 +635,21 @@ nsresult LoadInfoArgsToLoadInfo(
 
   Maybe<ServiceWorkerDescriptor> controller;
   if (loadInfoArgs.controller().type() !=
       OptionalIPCServiceWorkerDescriptor::Tvoid_t) {
     controller.emplace(ServiceWorkerDescriptor(
         loadInfoArgs.controller().get_IPCServiceWorkerDescriptor()));
   }
 
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  CookieSettings::Deserialize(loadInfoArgs.cookieSettings(),
-                              getter_AddRefs(cookieSettings));
-
   RefPtr<mozilla::LoadInfo> loadInfo = new mozilla::LoadInfo(
       loadingPrincipal, triggeringPrincipal, principalToInherit,
       sandboxedLoadingPrincipal, topLevelPrincipal,
-      topLevelStorageAreaPrincipal, resultPrincipalURI, cookieSettings,
-      clientInfo, reservedClientInfo, initialClientInfo, controller,
+      topLevelStorageAreaPrincipal, resultPrincipalURI, clientInfo,
+      reservedClientInfo, initialClientInfo, controller,
       loadInfoArgs.securityFlags(), loadInfoArgs.contentPolicyType(),
       static_cast<LoadTainting>(loadInfoArgs.tainting()),
       loadInfoArgs.upgradeInsecureRequests(),
       loadInfoArgs.browserUpgradeInsecureRequests(),
       loadInfoArgs.browserWouldUpgradeInsecureRequests(),
       loadInfoArgs.verifySignedContent(), loadInfoArgs.enforceSRI(),
       loadInfoArgs.forceAllowDataURI(),
       loadInfoArgs.allowInsecureRedirectToDataURI(),
@@ -695,47 +682,37 @@ nsresult LoadInfoArgsToLoadInfo(
 void LoadInfoToParentLoadInfoForwarder(
     nsILoadInfo* aLoadInfo, ParentLoadInfoForwarderArgs* aForwarderArgsOut) {
   if (!aLoadInfo) {
     *aForwarderArgsOut = ParentLoadInfoForwarderArgs(
         false, void_t(), nsILoadInfo::TAINTING_BASIC,
         false,  // serviceWorkerTaintingSynthesized
         false,  // documentHasUserInteracted
         false,  // documentHasLoaded
-        nsILoadInfo::OPENER_POLICY_NULL, Maybe<CookieSettingsArgs>());
+        nsILoadInfo::OPENER_POLICY_NULL);
     return;
   }
 
   OptionalIPCServiceWorkerDescriptor ipcController = void_t();
   Maybe<ServiceWorkerDescriptor> controller(aLoadInfo->GetController());
   if (controller.isSome()) {
     ipcController = controller.ref().ToIPC();
   }
 
   uint32_t tainting = nsILoadInfo::TAINTING_BASIC;
   Unused << aLoadInfo->GetTainting(&tainting);
 
   nsILoadInfo::CrossOriginOpenerPolicy openerPolicy =
       aLoadInfo->GetOpenerPolicy();
 
-  Maybe<CookieSettingsArgs> cookieSettingsArgs;
-
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  nsresult rv = aLoadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-  if (NS_SUCCEEDED(rv) && cookieSettings) {
-    CookieSettingsArgs args;
-    static_cast<CookieSettings*>(cookieSettings.get())->Serialize(args);
-    cookieSettingsArgs = Some(args);
-  }
-
   *aForwarderArgsOut = ParentLoadInfoForwarderArgs(
       aLoadInfo->GetAllowInsecureRedirectToDataURI(), ipcController, tainting,
       aLoadInfo->GetServiceWorkerTaintingSynthesized(),
       aLoadInfo->GetDocumentHasUserInteracted(),
-      aLoadInfo->GetDocumentHasLoaded(), openerPolicy, cookieSettingsArgs);
+      aLoadInfo->GetDocumentHasLoaded(), openerPolicy);
 }
 
 nsresult MergeParentLoadInfoForwarder(
     ParentLoadInfoForwarderArgs const& aForwarderArgs, nsILoadInfo* aLoadInfo) {
   if (!aLoadInfo) {
     return NS_OK;
   }
 
@@ -762,27 +739,16 @@ nsresult MergeParentLoadInfoForwarder(
   MOZ_ALWAYS_SUCCEEDS(
       aLoadInfo->SetOpenerPolicy(aForwarderArgs.openerPolicy()));
 
   MOZ_ALWAYS_SUCCEEDS(aLoadInfo->SetDocumentHasUserInteracted(
       aForwarderArgs.documentHasUserInteracted()));
   MOZ_ALWAYS_SUCCEEDS(
       aLoadInfo->SetDocumentHasLoaded(aForwarderArgs.documentHasLoaded()));
 
-  const Maybe<CookieSettingsArgs>& cookieSettingsArgs =
-      aForwarderArgs.cookieSettings();
-  if (cookieSettingsArgs.isSome()) {
-    nsCOMPtr<nsICookieSettings> cookieSettings;
-    nsresult rv = aLoadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-    if (NS_SUCCEEDED(rv) && cookieSettings) {
-      static_cast<CookieSettings*>(cookieSettings.get())
-          ->Merge(cookieSettingsArgs.ref());
-    }
-  }
-
   return NS_OK;
 }
 
 void LoadInfoToChildLoadInfoForwarder(
     nsILoadInfo* aLoadInfo, ChildLoadInfoForwarderArgs* aForwarderArgsOut) {
   if (!aLoadInfo) {
     *aForwarderArgsOut =
         ChildLoadInfoForwarderArgs(void_t(), void_t(), void_t());
--- a/js/xpconnect/loader/mozJSComponentLoader.cpp
+++ b/js/xpconnect/loader/mozJSComponentLoader.cpp
@@ -233,17 +233,16 @@ class MOZ_STACK_CLASS ComponentLoaderInf
     return mScriptChannel;
   }
   nsresult EnsureScriptChannel() {
     BEGIN_ENSURE(ScriptChannel, IOService, URI);
     return NS_NewChannel(getter_AddRefs(mScriptChannel), mURI,
                          nsContentUtils::GetSystemPrincipal(),
                          nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                          nsIContentPolicy::TYPE_SCRIPT,
-                         nullptr,  // nsICookieSettings
                          nullptr,  // aPerformanceStorage
                          nullptr,  // aLoadGroup
                          nullptr,  // aCallbacks
                          nsIRequest::LOAD_NORMAL, mIOService);
   }
 
   nsIURI* ResolvedURI() {
     MOZ_ASSERT(mResolvedURI);
--- a/js/xpconnect/loader/mozJSSubScriptLoader.cpp
+++ b/js/xpconnect/loader/mozJSSubScriptLoader.cpp
@@ -412,17 +412,16 @@ nsresult mozJSSubScriptLoader::ReadScrip
   // We create a channel and call SetContentType, to avoid expensive MIME type
   // lookups (bug 632490).
   nsCOMPtr<nsIChannel> channel;
   nsresult rv;
   rv = NS_NewChannel(getter_AddRefs(channel), uri,
                      nsContentUtils::GetSystemPrincipal(),
                      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                      nsIContentPolicy::TYPE_OTHER,
-                     nullptr,  // nsICookieSettings
                      nullptr,  // aPerformanceStorage
                      nullptr,  // aLoadGroup
                      nullptr,  // aCallbacks
                      nsIRequest::LOAD_NORMAL, serv);
 
   if (!NS_SUCCEEDED(rv)) {
     return rv;
   }
@@ -452,17 +451,16 @@ bool mozJSSubScriptLoader::ReadScript(ns
   // lookups (bug 632490).
   nsCOMPtr<nsIChannel> chan;
   nsCOMPtr<nsIInputStream> instream;
   nsresult rv;
   rv = NS_NewChannel(getter_AddRefs(chan), uri,
                      nsContentUtils::GetSystemPrincipal(),
                      nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                      nsIContentPolicy::TYPE_OTHER,
-                     nullptr,  // nsICookieSettings
                      nullptr,  // PerformanceStorage
                      nullptr,  // aLoadGroup
                      nullptr,  // aCallbacks
                      nsIRequest::LOAD_NORMAL, serv);
 
   if (NS_SUCCEEDED(rv)) {
     chan->SetContentType(NS_LITERAL_CSTRING("application/javascript"));
     rv = chan->Open(getter_AddRefs(instream));
--- a/layout/style/Loader.cpp
+++ b/layout/style/Loader.cpp
@@ -1388,28 +1388,25 @@ nsresult Loader::LoadSheet(SheetLoadData
       return LoadSheet(existingData, eSheetNeedsParser, aIsPreload);
     }
     // All done here; once the load completes we'll be marked complete
     // automatically
     return NS_OK;
   }
 
   nsCOMPtr<nsILoadGroup> loadGroup;
-  nsCOMPtr<nsICookieSettings> cookieSettings;
   if (mDocument) {
     loadGroup = mDocument->GetDocumentLoadGroup();
     // load for a document with no loadgrup indicates that something is
     // completely bogus, let's bail out early.
     if (!loadGroup) {
       LOG_ERROR(("  Failed to query loadGroup from document"));
       SheetComplete(aLoadData, NS_ERROR_UNEXPECTED);
       return NS_ERROR_UNEXPECTED;
     }
-
-    cookieSettings = mDocument->CookieSettings();
   }
 #ifdef DEBUG
   mSyncCallback = true;
 #endif
 
   CORSMode ourCORSMode = aLoadData->mSheet->GetCORSMode();
   nsSecurityFlags securityFlags =
       ourCORSMode == CORS_NONE
@@ -1441,17 +1438,17 @@ nsresult Loader::LoadSheet(SheetLoadData
         nsIChannel::LOAD_NORMAL | nsIChannel::LOAD_CLASSIFY_URI);
   } else {
     // either we are loading something inside a document, in which case
     // we should always have a requestingNode, or we are loading something
     // outside a document, in which case the loadingPrincipal and the
     // triggeringPrincipal should always be the systemPrincipal.
     rv = NS_NewChannel(getter_AddRefs(channel), aLoadData->mURI,
                        nsContentUtils::GetSystemPrincipal(), securityFlags,
-                       contentPolicyType, cookieSettings,
+                       contentPolicyType,
                        nullptr,  // aPerformanceStorage
                        loadGroup,
                        nullptr,  // aCallbacks
                        nsIChannel::LOAD_NORMAL | nsIChannel::LOAD_CLASSIFY_URI);
   }
 
   if (NS_FAILED(rv)) {
 #ifdef DEBUG
--- a/modules/libpref/init/StaticPrefList.h
+++ b/modules/libpref/init/StaticPrefList.h
@@ -1747,24 +1747,16 @@ VARCACHE_PREF(
 
 // Enables the predictive service.
 VARCACHE_PREF(
   "network.predictor.enabled",
    network_predictor_enabled,
   bool, true
 )
 
-// Allow CookieSettings to be unblocked for channels without a document.
-// This is for testing only.
-VARCACHE_PREF(
-  "network.cookieSettings.unblocked_for_testing",
-   network_cookieSettings_unblocked_for_testing,
-  bool, false
-)
-
 VARCACHE_PREF(
   "network.predictor.enable-hover-on-ssl",
    network_predictor_enable_hover_on_ssl,
   bool, false
 )
 
 VARCACHE_PREF(
   "network.predictor.enable-prefetch",
--- a/netwerk/base/LoadInfo.cpp
+++ b/netwerk/base/LoadInfo.cpp
@@ -8,27 +8,23 @@
 
 #include "mozilla/Assertions.h"
 #include "mozilla/dom/ClientIPCTypes.h"
 #include "mozilla/dom/ClientSource.h"
 #include "mozilla/dom/PerformanceStorage.h"
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/dom/ToJSValue.h"
 #include "mozilla/dom/BrowsingContext.h"
-#include "mozilla/net/CookieSettings.h"
 #include "mozilla/NullPrincipal.h"
-#include "mozilla/StaticPrefs.h"
 #include "mozIThirdPartyUtil.h"
 #include "nsFrameLoader.h"
 #include "nsFrameLoaderOwner.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsIDocShell.h"
 #include "mozilla/dom/Document.h"
-#include "nsCookiePermission.h"
-#include "nsICookieService.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsISupportsImpl.h"
 #include "nsISupportsUtils.h"
 #include "nsIXPConnect.h"
 #include "nsContentUtils.h"
 #include "nsDocShell.h"
 #include "nsGlobalWindow.h"
 #include "nsMixedContentBlocker.h"
@@ -204,20 +200,16 @@ LoadInfo::LoadInfo(
             nsGlobalWindowInner* topInner =
                 nsGlobalWindowInner::Cast(topOuter->GetCurrentInnerWindow());
             if (topInner) {
               mDocumentHasLoaded = topInner->IsDocumentLoaded();
             }
           }
         }
       }
-
-      // Let's inherit the cookie behavior and permission from the parent
-      // document.
-      mCookieSettings = aLoadingContext->OwnerDoc()->CookieSettings();
     }
 
     mInnerWindowID = aLoadingContext->OwnerDoc()->InnerWindowID();
     mAncestorPrincipals = aLoadingContext->OwnerDoc()->AncestorPrincipals();
     mAncestorOuterWindowIDs =
         aLoadingContext->OwnerDoc()->AncestorOuterWindowIDs();
     MOZ_DIAGNOSTIC_ASSERT(mAncestorPrincipals.Length() ==
                           mAncestorOuterWindowIDs.Length());
@@ -429,32 +421,26 @@ LoadInfo::LoadInfo(nsPIDOMWindowOuter* a
                         mAncestorOuterWindowIDs.Length());
 
 #ifdef DEBUG
   if (docShell->ItemType() == nsIDocShellTreeItem::typeChrome) {
     MOZ_ASSERT(mOriginAttributes.mPrivateBrowsingId == 0,
                "chrome docshell shouldn't have mPrivateBrowsingId set.");
   }
 #endif
-
-  // Let's take the current cookie behavior and current cookie permission
-  // for the documents' loadInfo. Note that for any other loadInfos,
-  // cookieBehavior will be BEHAVIOR_REJECT for security reasons.
-  mCookieSettings = CookieSettings::Create();
 }
 
 LoadInfo::LoadInfo(const LoadInfo& rhs)
     : mLoadingPrincipal(rhs.mLoadingPrincipal),
       mTriggeringPrincipal(rhs.mTriggeringPrincipal),
       mPrincipalToInherit(rhs.mPrincipalToInherit),
       mSandboxedLoadingPrincipal(rhs.mSandboxedLoadingPrincipal),
       mTopLevelPrincipal(rhs.mTopLevelPrincipal),
       mTopLevelStorageAreaPrincipal(rhs.mTopLevelStorageAreaPrincipal),
       mResultPrincipalURI(rhs.mResultPrincipalURI),
-      mCookieSettings(rhs.mCookieSettings),
       mClientInfo(rhs.mClientInfo),
       // mReservedClientSource must be handled specially during redirect
       // mReservedClientInfo must be handled specially during redirect
       // mInitialClientInfo must be handled specially during redirect
       mController(rhs.mController),
       mPerformanceStorage(rhs.mPerformanceStorage),
       mLoadingContext(rhs.mLoadingContext),
       mContextForTopLevelLoad(rhs.mContextForTopLevelLoad),
@@ -503,17 +489,17 @@ LoadInfo::LoadInfo(const LoadInfo& rhs)
       mIsFromProcessingFrameAttributes(rhs.mIsFromProcessingFrameAttributes),
       mOpenerPolicy(rhs.mOpenerPolicy) {}
 
 LoadInfo::LoadInfo(
     nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
     nsIPrincipal* aPrincipalToInherit, nsIPrincipal* aSandboxedLoadingPrincipal,
     nsIPrincipal* aTopLevelPrincipal,
     nsIPrincipal* aTopLevelStorageAreaPrincipal, nsIURI* aResultPrincipalURI,
-    nsICookieSettings* aCookieSettings, const Maybe<ClientInfo>& aClientInfo,
+    const Maybe<ClientInfo>& aClientInfo,
     const Maybe<ClientInfo>& aReservedClientInfo,
     const Maybe<ClientInfo>& aInitialClientInfo,
     const Maybe<ServiceWorkerDescriptor>& aController,
     nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
     LoadTainting aTainting, bool aUpgradeInsecureRequests,
     bool aBrowserUpgradeInsecureRequests,
     bool aBrowserWouldUpgradeInsecureRequests, bool aVerifySignedContent,
     bool aEnforceSRI, bool aForceAllowDataURI,
@@ -535,17 +521,16 @@ LoadInfo::LoadInfo(
     bool aServiceWorkerTaintingSynthesized, bool aDocumentHasUserInteracted,
     bool aDocumentHasLoaded, const nsAString& aCspNonce)
     : mLoadingPrincipal(aLoadingPrincipal),
       mTriggeringPrincipal(aTriggeringPrincipal),
       mPrincipalToInherit(aPrincipalToInherit),
       mTopLevelPrincipal(aTopLevelPrincipal),
       mTopLevelStorageAreaPrincipal(aTopLevelStorageAreaPrincipal),
       mResultPrincipalURI(aResultPrincipalURI),
-      mCookieSettings(aCookieSettings),
       mClientInfo(aClientInfo),
       mReservedClientInfo(aReservedClientInfo),
       mInitialClientInfo(aInitialClientInfo),
       mController(aController),
       mSecurityFlags(aSecurityFlags),
       mInternalContentPolicyType(aContentPolicyType),
       mTainting(aTainting),
       mUpgradeInsecureRequests(aUpgradeInsecureRequests),
@@ -781,56 +766,16 @@ LoadInfo::GetCookiePolicy(uint32_t* aRes
                  ? nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
                  : nsILoadInfo::SEC_COOKIES_INCLUDE;
   }
 
   *aResult = policy;
   return NS_OK;
 }
 
-namespace {
-
-already_AddRefed<nsICookieSettings> CreateCookieSettings(
-    nsContentPolicyType aContentPolicyType) {
-  if (StaticPrefs::network_cookieSettings_unblocked_for_testing()) {
-    return CookieSettings::Create();
-  }
-
-  // These contentPolictTypes require a real CookieSettings because favicon and
-  // save-as requests must send cookies. Anything else should not send/receive
-  // cookies.
-  if (aContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON ||
-      aContentPolicyType == nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD) {
-    return CookieSettings::Create();
-  }
-
-  return CookieSettings::CreateBlockingAll();
-}
-
-}  // namespace
-
-NS_IMETHODIMP
-LoadInfo::GetCookieSettings(nsICookieSettings** aCookieSettings) {
-  if (!mCookieSettings) {
-    mCookieSettings = CreateCookieSettings(mInternalContentPolicyType);
-  }
-
-  nsCOMPtr<nsICookieSettings> cookieSettings = mCookieSettings;
-  cookieSettings.forget(aCookieSettings);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-LoadInfo::SetCookieSettings(nsICookieSettings* aCookieSettings) {
-  MOZ_ASSERT(aCookieSettings);
-  // We allow the overwrite of CookieSettings.
-  mCookieSettings = aCookieSettings;
-  return NS_OK;
-}
-
 void LoadInfo::SetIncludeCookiesSecFlag() {
   MOZ_ASSERT((mSecurityFlags & sCookiePolicyMask) ==
              nsILoadInfo::SEC_COOKIES_DEFAULT);
   mSecurityFlags =
       (mSecurityFlags & ~sCookiePolicyMask) | nsILoadInfo::SEC_COOKIES_INCLUDE;
 }
 
 NS_IMETHODIMP
--- a/netwerk/base/LoadInfo.h
+++ b/netwerk/base/LoadInfo.h
@@ -14,17 +14,16 @@
 #include "nsIURI.h"
 #include "nsString.h"
 #include "nsTArray.h"
 
 #include "mozilla/BasePrincipal.h"
 #include "mozilla/dom/ClientInfo.h"
 #include "mozilla/dom/ServiceWorkerDescriptor.h"
 
-class nsICookieSettings;
 class nsINode;
 class nsPIDOMWindowOuter;
 
 namespace mozilla {
 
 namespace dom {
 class PerformanceStorage;
 class XMLHttpRequestMainThread;
@@ -66,17 +65,16 @@ class LoadInfo final : public nsILoadInf
   // loadingContext than other loads. This ContextForTopLevelLoad is
   // only used for content policy checks.
   LoadInfo(nsPIDOMWindowOuter* aOuterWindow, nsIPrincipal* aTriggeringPrincipal,
            nsISupports* aContextForTopLevelLoad,
            nsSecurityFlags aSecurityFlags);
 
   // create an exact copy of the loadinfo
   already_AddRefed<nsILoadInfo> Clone() const;
-
   // hands off!!! don't use CloneWithNewSecFlags unless you know
   // exactly what you are doing - it should only be used within
   // nsBaseChannel::Redirect()
   already_AddRefed<nsILoadInfo> CloneWithNewSecFlags(
       nsSecurityFlags aSecurityFlags) const;
   // creates a copy of the loadinfo which is appropriate to use for a
   // separate request. I.e. not for a redirect or an inner channel, but
   // when a separate request is made with the same security properties.
@@ -93,17 +91,17 @@ class LoadInfo final : public nsILoadInf
   // HttpChannelParent and FTPChannelParent declared as friends undeneath.
   // In e10s we can not serialize nsINode, hence we store the innerWindowID.
   // Please note that aRedirectChain uses swapElements.
   LoadInfo(nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
            nsIPrincipal* aPrincipalToInherit,
            nsIPrincipal* aSandboxedLoadingPrincipal,
            nsIPrincipal* aTopLevelPrincipal,
            nsIPrincipal* aTopLevelStorageAreaPrincipal,
-           nsIURI* aResultPrincipalURI, nsICookieSettings* aCookieSettings,
+           nsIURI* aResultPrincipalURI,
            const Maybe<mozilla::dom::ClientInfo>& aClientInfo,
            const Maybe<mozilla::dom::ClientInfo>& aReservedClientInfo,
            const Maybe<mozilla::dom::ClientInfo>& aInitialClientInfo,
            const Maybe<mozilla::dom::ServiceWorkerDescriptor>& aController,
            nsSecurityFlags aSecurityFlags,
            nsContentPolicyType aContentPolicyType, LoadTainting aTainting,
            bool aUpgradeInsecureRequests, bool aBrowserUpgradeInsecureRequests,
            bool aBrowserWouldUpgradeInsecureRequests, bool aVerifySignedContent,
@@ -152,17 +150,16 @@ class LoadInfo final : public nsILoadInf
   nsCOMPtr<nsIPrincipal> mLoadingPrincipal;
   nsCOMPtr<nsIPrincipal> mTriggeringPrincipal;
   nsCOMPtr<nsIPrincipal> mPrincipalToInherit;
   nsCOMPtr<nsIPrincipal> mSandboxedLoadingPrincipal;
   nsCOMPtr<nsIPrincipal> mTopLevelPrincipal;
   nsCOMPtr<nsIPrincipal> mTopLevelStorageAreaPrincipal;
   nsCOMPtr<nsIURI> mResultPrincipalURI;
   nsCOMPtr<nsICSPEventListener> mCSPEventListener;
-  nsCOMPtr<nsICookieSettings> mCookieSettings;
 
   Maybe<mozilla::dom::ClientInfo> mClientInfo;
   UniquePtr<mozilla::dom::ClientSource> mReservedClientSource;
   Maybe<mozilla::dom::ClientInfo> mReservedClientInfo;
   Maybe<mozilla::dom::ClientInfo> mInitialClientInfo;
   Maybe<mozilla::dom::ServiceWorkerDescriptor> mController;
   RefPtr<mozilla::dom::PerformanceStorage> mPerformanceStorage;
 
--- a/netwerk/base/NetworkConnectivityService.cpp
+++ b/netwerk/base/NetworkConnectivityService.cpp
@@ -186,17 +186,16 @@ static inline already_AddRefed<nsIChanne
   rv = NS_NewURI(getter_AddRefs(uri), url);
   NS_ENSURE_SUCCESS(rv, nullptr);
 
   nsCOMPtr<nsIChannel> channel;
   rv = NS_NewChannel(
       getter_AddRefs(channel), uri, nsContentUtils::GetSystemPrincipal(),
       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
       nsIContentPolicy::TYPE_OTHER,
-      nullptr,  // nsICookieSettings
       nullptr,  // aPerformanceStorage
       nullptr,  // aLoadGroup
       nullptr,
       nsIRequest::LOAD_BYPASS_CACHE |    // don't read from the cache
           nsIRequest::INHIBIT_CACHING |  // don't write the response to cache
           nsIRequest::LOAD_ANONYMOUS);   // prevent privacy leaks
 
   NS_ENSURE_SUCCESS(rv, nullptr);
--- a/netwerk/base/Predictor.cpp
+++ b/netwerk/base/Predictor.cpp
@@ -1241,18 +1241,17 @@ nsresult Predictor::Prefetch(nsIURI *uri
   uri->GetAsciiSpec(strUri);
   referrer->GetAsciiSpec(strReferrer);
   PREDICTOR_LOG(("Predictor::Prefetch uri=%s referrer=%s verifier=%p",
                  strUri.get(), strReferrer.get(), verifier));
   nsCOMPtr<nsIChannel> channel;
   nsresult rv = NS_NewChannel(
       getter_AddRefs(channel), uri, nsContentUtils::GetSystemPrincipal(),
       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
-      nsIContentPolicy::TYPE_OTHER, nullptr, /* nsICookieSettings */
-      nullptr,                               /* aPerformanceStorage */
+      nsIContentPolicy::TYPE_OTHER, nullptr, /* aPerformanceStorage */
       nullptr,                               /* aLoadGroup */
       nullptr,                               /* aCallbacks */
       nsIRequest::LOAD_BACKGROUND);
 
   if (NS_FAILED(rv)) {
     PREDICTOR_LOG(
         ("    NS_NewChannel failed rv=0x%" PRIX32, static_cast<uint32_t>(rv)));
     return rv;
--- a/netwerk/base/nsILoadInfo.idl
+++ b/netwerk/base/nsILoadInfo.idl
@@ -3,17 +3,16 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 #include "nsIContentPolicy.idl"
 
 interface nsIChannel;
-interface nsICookieSettings;
 interface nsICSPEventListener;
 interface nsINode;
 interface nsIPrincipal;
 interface nsIRedirectHistoryEntry;
 interface nsIURI;
 webidl Document;
 webidl BrowsingContext;
 native LoadContextRef(already_AddRefed<nsISupports>);
@@ -423,22 +422,16 @@ interface nsILoadInfo : nsISupports
    * See the SEC_COOKIES_* flags above. This attribute will never return
    * SEC_COOKIES_DEFAULT, but will instead return what the policy resolves to.
    * I.e. SEC_COOKIES_SAME_ORIGIN for CORS mode, and SEC_COOKIES_INCLUDE
    * otherwise.
    */
   [infallible] readonly attribute unsigned long cookiePolicy;
 
   /**
-   * The cookie settings inherited from the top-level document's loadInfo.
-   * It cannot be null.
-   */
-  attribute nsICookieSettings cookieSettings;
-
-  /**
    * If forceInheritPrincipal is true, the data coming from the channel should
    * inherit its principal, even when the data is loaded over http:// or another
    * protocol that would normally use a URI-based principal.
    *
    * See the documentation for principalToInherit, which describes exactly what
    * principal is inherited.
    *
    * This attribute will never be true when loadingSandboxed is true.
--- a/netwerk/base/nsIncrementalDownload.cpp
+++ b/netwerk/base/nsIncrementalDownload.cpp
@@ -215,17 +215,16 @@ nsresult nsIncrementalDownload::ProcessT
 
   // Fetch next chunk
 
   nsCOMPtr<nsIChannel> channel;
   nsresult rv = NS_NewChannel(getter_AddRefs(channel), mFinalURI,
                               nsContentUtils::GetSystemPrincipal(),
                               nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                               nsIContentPolicy::TYPE_OTHER,
-                              nullptr,  // nsICookieSettings
                               nullptr,  // PerformanceStorage
                               nullptr,  // loadGroup
                               this,     // aCallbacks
                               mLoadFlags);
 
   if (NS_FAILED(rv)) return rv;
 
   nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(channel, &rv);
--- a/netwerk/base/nsNetUtil.cpp
+++ b/netwerk/base/nsNetUtil.cpp
@@ -293,68 +293,64 @@ void AssertLoadingPrincipalAndClientInfo
 }
 
 }  // namespace
 
 nsresult NS_NewChannel(nsIChannel **outChannel, nsIURI *aUri,
                        nsIPrincipal *aLoadingPrincipal,
                        nsSecurityFlags aSecurityFlags,
                        nsContentPolicyType aContentPolicyType,
-                       nsICookieSettings *aCookieSettings /* = nullptr */,
-                       PerformanceStorage *aPerformanceStorage /* = nullptr */,
+                       PerformanceStorage *aPerformanceStorage /* nullptr */,
                        nsILoadGroup *aLoadGroup /* = nullptr */,
                        nsIInterfaceRequestor *aCallbacks /* = nullptr */,
                        nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
                        nsIIOService *aIoService /* = nullptr */) {
-  return NS_NewChannelInternal(
-      outChannel, aUri,
-      nullptr,  // aLoadingNode,
-      aLoadingPrincipal,
-      nullptr,  // aTriggeringPrincipal
-      Maybe<ClientInfo>(), Maybe<ServiceWorkerDescriptor>(), aSecurityFlags,
-      aContentPolicyType, aCookieSettings, aPerformanceStorage, aLoadGroup,
-      aCallbacks, aLoadFlags, aIoService);
+  return NS_NewChannelInternal(outChannel, aUri,
+                               nullptr,  // aLoadingNode,
+                               aLoadingPrincipal,
+                               nullptr,  // aTriggeringPrincipal
+                               Maybe<ClientInfo>(),
+                               Maybe<ServiceWorkerDescriptor>(), aSecurityFlags,
+                               aContentPolicyType, aPerformanceStorage,
+                               aLoadGroup, aCallbacks, aLoadFlags, aIoService);
 }
 
 nsresult NS_NewChannel(nsIChannel **outChannel, nsIURI *aUri,
                        nsIPrincipal *aLoadingPrincipal,
                        const ClientInfo &aLoadingClientInfo,
                        const Maybe<ServiceWorkerDescriptor> &aController,
                        nsSecurityFlags aSecurityFlags,
                        nsContentPolicyType aContentPolicyType,
-                       nsICookieSettings *aCookieSettings /* = nullptr */,
-                       PerformanceStorage *aPerformanceStorage /* = nullptr */,
+                       PerformanceStorage *aPerformanceStorage /* nullptr */,
                        nsILoadGroup *aLoadGroup /* = nullptr */,
                        nsIInterfaceRequestor *aCallbacks /* = nullptr */,
                        nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
                        nsIIOService *aIoService /* = nullptr */) {
   AssertLoadingPrincipalAndClientInfoMatch(
       aLoadingPrincipal, aLoadingClientInfo, aContentPolicyType);
 
   Maybe<ClientInfo> loadingClientInfo;
   loadingClientInfo.emplace(aLoadingClientInfo);
 
   return NS_NewChannelInternal(outChannel, aUri,
                                nullptr,  // aLoadingNode,
                                aLoadingPrincipal,
                                nullptr,  // aTriggeringPrincipal
                                loadingClientInfo, aController, aSecurityFlags,
-                               aContentPolicyType, aCookieSettings,
-                               aPerformanceStorage, aLoadGroup, aCallbacks,
-                               aLoadFlags, aIoService);
+                               aContentPolicyType, aPerformanceStorage,
+                               aLoadGroup, aCallbacks, aLoadFlags, aIoService);
 }
 
 nsresult NS_NewChannelInternal(
     nsIChannel **outChannel, nsIURI *aUri, nsINode *aLoadingNode,
     nsIPrincipal *aLoadingPrincipal, nsIPrincipal *aTriggeringPrincipal,
     const Maybe<ClientInfo> &aLoadingClientInfo,
     const Maybe<ServiceWorkerDescriptor> &aController,
     nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings /* = nullptr */,
-    PerformanceStorage *aPerformanceStorage /* = nullptr */,
+    PerformanceStorage *aPerformanceStorage /* nullptr */,
     nsILoadGroup *aLoadGroup /* = nullptr */,
     nsIInterfaceRequestor *aCallbacks /* = nullptr */,
     nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
     nsIIOService *aIoService /* = nullptr */) {
   NS_ENSURE_ARG_POINTER(outChannel);
 
   nsCOMPtr<nsIIOService> grip;
   nsresult rv = net_EnsureIOService(&aIoService, grip);
@@ -388,26 +384,19 @@ nsresult NS_NewChannelInternal(
   MOZ_DIAGNOSTIC_ASSERT(!(channelLoadFlags & nsIChannel::LOAD_REPLACE));
 #endif
 
   if (aLoadFlags != nsIRequest::LOAD_NORMAL) {
     rv = channel->SetLoadFlags(aLoadFlags);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  if (aPerformanceStorage || aCookieSettings) {
+  if (aPerformanceStorage) {
     nsCOMPtr<nsILoadInfo> loadInfo = channel->LoadInfo();
-
-    if (aPerformanceStorage) {
-      loadInfo->SetPerformanceStorage(aPerformanceStorage);
-    }
-
-    if (aCookieSettings) {
-      loadInfo->SetCookieSettings(aCookieSettings);
-    }
+    loadInfo->SetPerformanceStorage(aPerformanceStorage);
   }
 
   channel.forget(outChannel);
   return NS_OK;
 }
 
 nsresult /*NS_NewChannelWithNodeAndTriggeringPrincipal */
 NS_NewChannelWithTriggeringPrincipal(
@@ -421,83 +410,79 @@ NS_NewChannelWithTriggeringPrincipal(
     nsIIOService *aIoService /* = nullptr */) {
   MOZ_ASSERT(aLoadingNode);
   NS_ASSERTION(aTriggeringPrincipal,
                "Can not create channel without a triggering Principal!");
   return NS_NewChannelInternal(
       outChannel, aUri, aLoadingNode, aLoadingNode->NodePrincipal(),
       aTriggeringPrincipal, Maybe<ClientInfo>(),
       Maybe<ServiceWorkerDescriptor>(), aSecurityFlags, aContentPolicyType,
-      aLoadingNode->OwnerDoc()->CookieSettings(), aPerformanceStorage,
-      aLoadGroup, aCallbacks, aLoadFlags, aIoService);
+      aPerformanceStorage, aLoadGroup, aCallbacks, aLoadFlags, aIoService);
 }
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannelWithTriggeringPrincipal(
     nsIChannel **outChannel, nsIURI *aUri, nsIPrincipal *aLoadingPrincipal,
     nsIPrincipal *aTriggeringPrincipal, nsSecurityFlags aSecurityFlags,
     nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings /* = nullptr */,
     PerformanceStorage *aPerformanceStorage /* = nullptr */,
     nsILoadGroup *aLoadGroup /* = nullptr */,
     nsIInterfaceRequestor *aCallbacks /* = nullptr */,
     nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
     nsIIOService *aIoService /* = nullptr */) {
   NS_ASSERTION(aLoadingPrincipal,
                "Can not create channel without a loading Principal!");
   return NS_NewChannelInternal(
       outChannel, aUri,
       nullptr,  // aLoadingNode
       aLoadingPrincipal, aTriggeringPrincipal, Maybe<ClientInfo>(),
       Maybe<ServiceWorkerDescriptor>(), aSecurityFlags, aContentPolicyType,
-      aCookieSettings, aPerformanceStorage, aLoadGroup, aCallbacks, aLoadFlags,
-      aIoService);
+      aPerformanceStorage, aLoadGroup, aCallbacks, aLoadFlags, aIoService);
 }
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannelWithTriggeringPrincipal(
     nsIChannel **outChannel, nsIURI *aUri, nsIPrincipal *aLoadingPrincipal,
     nsIPrincipal *aTriggeringPrincipal, const ClientInfo &aLoadingClientInfo,
     const Maybe<ServiceWorkerDescriptor> &aController,
     nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings /* = nullptr */,
     PerformanceStorage *aPerformanceStorage /* = nullptr */,
     nsILoadGroup *aLoadGroup /* = nullptr */,
     nsIInterfaceRequestor *aCallbacks /* = nullptr */,
     nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
     nsIIOService *aIoService /* = nullptr */) {
   AssertLoadingPrincipalAndClientInfoMatch(
       aLoadingPrincipal, aLoadingClientInfo, aContentPolicyType);
 
   Maybe<ClientInfo> loadingClientInfo;
   loadingClientInfo.emplace(aLoadingClientInfo);
 
-  return NS_NewChannelInternal(
-      outChannel, aUri,
-      nullptr,  // aLoadingNode
-      aLoadingPrincipal, aTriggeringPrincipal, loadingClientInfo, aController,
-      aSecurityFlags, aContentPolicyType, aCookieSettings, aPerformanceStorage,
-      aLoadGroup, aCallbacks, aLoadFlags, aIoService);
+  return NS_NewChannelInternal(outChannel, aUri,
+                               nullptr,  // aLoadingNode
+                               aLoadingPrincipal, aTriggeringPrincipal,
+                               loadingClientInfo, aController, aSecurityFlags,
+                               aContentPolicyType, aPerformanceStorage,
+                               aLoadGroup, aCallbacks, aLoadFlags, aIoService);
 }
 
 nsresult NS_NewChannel(nsIChannel **outChannel, nsIURI *aUri,
                        nsINode *aLoadingNode, nsSecurityFlags aSecurityFlags,
                        nsContentPolicyType aContentPolicyType,
                        PerformanceStorage *aPerformanceStorage /* = nullptr */,
                        nsILoadGroup *aLoadGroup /* = nullptr */,
                        nsIInterfaceRequestor *aCallbacks /* = nullptr */,
                        nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
                        nsIIOService *aIoService /* = nullptr */) {
   NS_ASSERTION(aLoadingNode, "Can not create channel without a loading Node!");
   return NS_NewChannelInternal(
       outChannel, aUri, aLoadingNode, aLoadingNode->NodePrincipal(),
       nullptr,  // aTriggeringPrincipal
       Maybe<ClientInfo>(), Maybe<ServiceWorkerDescriptor>(), aSecurityFlags,
-      aContentPolicyType, aLoadingNode->OwnerDoc()->CookieSettings(),
-      aPerformanceStorage, aLoadGroup, aCallbacks, aLoadFlags, aIoService);
+      aContentPolicyType, aPerformanceStorage, aLoadGroup, aCallbacks,
+      aLoadFlags, aIoService);
 }
 
 nsresult NS_GetIsDocumentChannel(nsIChannel *aChannel, bool *aIsDocument) {
   // Check if this channel is going to be used to create a document. If it has
   // LOAD_DOCUMENT_URI set it is trivially creating a document. If
   // LOAD_HTML_OBJECT_DATA is set it may or may not be used to create a
   // document, depending on its MIME type.
 
@@ -919,17 +904,16 @@ nsresult NS_NewStreamLoaderInternal(
     nsLoadFlags aLoadFlags /* = nsIRequest::LOAD_NORMAL */,
     nsIURI *aReferrer /* = nullptr */) {
   nsCOMPtr<nsIChannel> channel;
   nsresult rv = NS_NewChannelInternal(
       getter_AddRefs(channel), aUri, aLoadingNode, aLoadingPrincipal,
       nullptr,  // aTriggeringPrincipal
       Maybe<ClientInfo>(), Maybe<ServiceWorkerDescriptor>(), aSecurityFlags,
       aContentPolicyType,
-      nullptr,  // nsICookieSettings
       nullptr,  // PerformanceStorage
       aLoadGroup, aCallbacks, aLoadFlags);
 
   NS_ENSURE_SUCCESS(rv, rv);
   nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
   if (httpChannel) {
     rv = httpChannel->SetReferrer(aReferrer);
     MOZ_ASSERT(NS_SUCCEEDED(rv));
--- a/netwerk/base/nsNetUtil.h
+++ b/netwerk/base/nsNetUtil.h
@@ -27,17 +27,16 @@
 #include "nsString.h"
 
 class nsIPrincipal;
 class nsIAsyncStreamCopier;
 class nsIAuthPrompt;
 class nsIAuthPrompt2;
 class nsIChannel;
 class nsIChannelPolicy;
-class nsICookieSettings;
 class nsIDownloadObserver;
 class nsIEventTarget;
 class nsIFileProtocolHandler;
 class nsIFileStream;
 class nsIHttpChannel;
 class nsIInputStream;
 class nsIInputStreamPump;
 class nsIInterfaceRequestor;
@@ -162,17 +161,16 @@ nsresult NS_GetSanitizedURIStringFromURI
  * systemPrincipal as the loadingPrincipal.
  */
 nsresult NS_NewChannelInternal(
     nsIChannel **outChannel, nsIURI *aUri, nsINode *aLoadingNode,
     nsIPrincipal *aLoadingPrincipal, nsIPrincipal *aTriggeringPrincipal,
     const mozilla::Maybe<mozilla::dom::ClientInfo> &aLoadingClientInfo,
     const mozilla::Maybe<mozilla::dom::ServiceWorkerDescriptor> &aController,
     nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings = nullptr,
     mozilla::dom::PerformanceStorage *aPerformanceStorage = nullptr,
     nsILoadGroup *aLoadGroup = nullptr,
     nsIInterfaceRequestor *aCallbacks = nullptr,
     nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL,
     nsIIOService *aIoService = nullptr);
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannelInternal(
@@ -195,31 +193,29 @@ NS_NewChannelWithTriggeringPrincipal(
     nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL,
     nsIIOService *aIoService = nullptr);
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannelWithTriggeringPrincipal(
     nsIChannel **outChannel, nsIURI *aUri, nsIPrincipal *aLoadingPrincipal,
     nsIPrincipal *aTriggeringPrincipal, nsSecurityFlags aSecurityFlags,
     nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings = nullptr,
     mozilla::dom::PerformanceStorage *aPerformanceStorage = nullptr,
     nsILoadGroup *aLoadGroup = nullptr,
     nsIInterfaceRequestor *aCallbacks = nullptr,
     nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL,
     nsIIOService *aIoService = nullptr);
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannelWithTriggeringPrincipal(
     nsIChannel **outChannel, nsIURI *aUri, nsIPrincipal *aLoadingPrincipal,
     nsIPrincipal *aTriggeringPrincipal,
     const mozilla::dom::ClientInfo &aLoadingClientInfo,
     const mozilla::Maybe<mozilla::dom::ServiceWorkerDescriptor> &aController,
     nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings = nullptr,
     mozilla::dom::PerformanceStorage *aPerformanceStorage = nullptr,
     nsILoadGroup *aLoadGroup = nullptr,
     nsIInterfaceRequestor *aCallbacks = nullptr,
     nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL,
     nsIIOService *aIoService = nullptr);
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannel(
@@ -230,30 +226,28 @@ nsresult NS_NewChannel(
     nsIInterfaceRequestor *aCallbacks = nullptr,
     nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL,
     nsIIOService *aIoService = nullptr);
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannel(
     nsIChannel **outChannel, nsIURI *aUri, nsIPrincipal *aLoadingPrincipal,
     nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings = nullptr,
     mozilla::dom::PerformanceStorage *aPerformanceStorage = nullptr,
     nsILoadGroup *aLoadGroup = nullptr,
     nsIInterfaceRequestor *aCallbacks = nullptr,
     nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL,
     nsIIOService *aIoService = nullptr);
 
 // See NS_NewChannelInternal for usage and argument description
 nsresult NS_NewChannel(
     nsIChannel **outChannel, nsIURI *aUri, nsIPrincipal *aLoadingPrincipal,
     const mozilla::dom::ClientInfo &aLoadingClientInfo,
     const mozilla::Maybe<mozilla::dom::ServiceWorkerDescriptor> &aController,
     nsSecurityFlags aSecurityFlags, nsContentPolicyType aContentPolicyType,
-    nsICookieSettings *aCookieSettings = nullptr,
     mozilla::dom::PerformanceStorage *aPerformanceStorage = nullptr,
     nsILoadGroup *aLoadGroup = nullptr,
     nsIInterfaceRequestor *aCallbacks = nullptr,
     nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL,
     nsIIOService *aIoService = nullptr);
 
 nsresult NS_GetIsDocumentChannel(nsIChannel *aChannel, bool *aIsDocument);
 
--- a/netwerk/base/nsPACMan.cpp
+++ b/netwerk/base/nsPACMan.cpp
@@ -632,18 +632,17 @@ void nsPACMan::ContinueLoadingAfterPACUr
       // NOTE: This results in GetProxyForURI being called
       if (pacURI) {
         nsresult rv = pacURI->GetSpec(mNormalPACURISpec);
         MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
         NS_NewChannel(getter_AddRefs(channel), pacURI,
                       nsContentUtils::GetSystemPrincipal(),
                       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                       nsIContentPolicy::TYPE_OTHER,
-                      nullptr,  // nsICookieSettings
-                      nullptr,  // PerformanceStorage
+                      nullptr,  // PerformanceStorage,
                       nullptr,  // aLoadGroup
                       nullptr,  // aCallbacks
                       nsIRequest::LOAD_NORMAL, ios);
       } else {
         LOG(("nsPACMan::StartLoading Failed pacspec uri conversion %s\n",
              mPACURISpec.get()));
       }
 
--- a/netwerk/cookie/CookieServiceChild.cpp
+++ b/netwerk/cookie/CookieServiceChild.cpp
@@ -22,25 +22,25 @@
 #include "nsCookiePermission.h"
 #include "nsIEffectiveTLDService.h"
 #include "nsIURI.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsServiceManagerUtils.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/TimeStamp.h"
-#include "ThirdPartyUtil.h"
 
 using namespace mozilla::ipc;
 using mozilla::OriginAttributes;
 
 namespace mozilla {
 namespace net {
 
 // Pref string constants
+static const char kPrefCookieBehavior[] = "network.cookie.cookieBehavior";
 static const char kPrefThirdPartySession[] =
     "network.cookie.thirdparty.sessionOnly";
 static const char kPrefThirdPartyNonsecureSession[] =
     "network.cookie.thirdparty.nonsecureSessionOnly";
 static const char kCookieMoveIntervalSecs[] =
     "network.cookie.move.interval_sec";
 
 static StaticRefPtr<CookieServiceChild> gCookieService;
@@ -54,17 +54,18 @@ already_AddRefed<CookieServiceChild> Coo
 
   return do_AddRef(gCookieService);
 }
 
 NS_IMPL_ISUPPORTS(CookieServiceChild, nsICookieService, nsIObserver,
                   nsITimerCallback, nsISupportsWeakReference)
 
 CookieServiceChild::CookieServiceChild()
-    : mThirdPartySession(false),
+    : mCookieBehavior(nsICookieService::BEHAVIOR_ACCEPT),
+      mThirdPartySession(false),
       mThirdPartyNonsecureSession(false),
       mIPCOpen(false) {
   NS_ASSERTION(IsNeckoChild(), "not a child process");
 
   mozilla::dom::ContentChild *cc =
       static_cast<mozilla::dom::ContentChild *>(gNeckoChild->Manager());
   if (cc->IsShuttingDown()) {
     return;
@@ -75,26 +76,24 @@ CookieServiceChild::CookieServiceChild()
 
   NeckoChild::InitNeckoChild();
 
   // Create a child PCookieService actor.
   gNeckoChild->SendPCookieServiceConstructor(this);
 
   mIPCOpen = true;
 
-  mThirdPartyUtil = ThirdPartyUtil::GetInstance();
-  NS_ASSERTION(mThirdPartyUtil, "couldn't get ThirdPartyUtil service");
-
   mTLDService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
   NS_ASSERTION(mTLDService, "couldn't get TLDService");
 
   // Init our prefs and observer.
   nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
   NS_WARNING_ASSERTION(prefBranch, "no prefservice");
   if (prefBranch) {
+    prefBranch->AddObserver(kPrefCookieBehavior, this, true);
     prefBranch->AddObserver(kPrefThirdPartySession, this, true);
     prefBranch->AddObserver(kPrefThirdPartyNonsecureSession, this, true);
     prefBranch->AddObserver(kCookieMoveIntervalSecs, this, true);
     PrefChanged(prefBranch);
   }
 
   nsCOMPtr<nsIObserverService> observerService =
       mozilla::services::GetObserverService();
@@ -144,18 +143,17 @@ void CookieServiceChild::TrackCookieLoad
     return;
   }
 
   bool isForeign = false;
   bool isTrackingResource = false;
   bool firstPartyStorageAccessGranted = false;
   nsCOMPtr<nsIURI> uri;
   aChannel->GetURI(getter_AddRefs(uri));
-  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
-  if (RequireThirdPartyCheck(loadInfo)) {
+  if (RequireThirdPartyCheck()) {
     mThirdPartyUtil->IsThirdPartyChannel(aChannel, uri, &isForeign);
   }
   nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
   if (httpChannel) {
     isTrackingResource = httpChannel->GetIsTrackingResource();
     // Check first-party storage access even for non-tracking resources, since
     // we will need the result when computing the access rights for the reject
     // foreign cookie behavior mode.
@@ -169,16 +167,17 @@ void CookieServiceChild::TrackCookieLoad
     // since the parent process can't do it for us as it won't have a channel
     // object handy.
     if (!firstPartyStorageAccessGranted) {
       AntiTrackingCommon::NotifyBlockingDecision(
           aChannel, AntiTrackingCommon::BlockingDecision::eBlock,
           rejectedReason);
     }
   }
+  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
   mozilla::OriginAttributes attrs = loadInfo->GetOriginAttributes();
   URIParams uriParams;
   SerializeURI(uri, uriParams);
   bool isSafeTopLevelNav = NS_IsSafeTopLevelNav(aChannel);
   bool isSameSiteForeign = NS_IsSameSiteForeign(aChannel, uri);
   SendPrepareCookieList(uriParams, isForeign, isTrackingResource,
                         firstPartyStorageAccessGranted, isSafeTopLevelNav,
                         isSameSiteForeign, attrs);
@@ -248,25 +247,36 @@ mozilla::ipc::IPCResult CookieServiceChi
         aCookiesList[i].sameSite());
     RecordDocumentCookie(cookie, aAttrs);
   }
 
   return IPC_OK();
 }
 
 void CookieServiceChild::PrefChanged(nsIPrefBranch *aPrefBranch) {
+  int32_t val;
+  if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefCookieBehavior, &val)))
+    mCookieBehavior = val >= nsICookieService::BEHAVIOR_ACCEPT &&
+                              val <= nsICookieService::BEHAVIOR_LAST
+                          ? val
+                          : nsICookieService::BEHAVIOR_ACCEPT;
+
   bool boolval;
   if (NS_SUCCEEDED(aPrefBranch->GetBoolPref(kPrefThirdPartySession, &boolval)))
     mThirdPartySession = !!boolval;
 
   if (NS_SUCCEEDED(
           aPrefBranch->GetBoolPref(kPrefThirdPartyNonsecureSession, &boolval)))
     mThirdPartyNonsecureSession = boolval;
 
-  int32_t val;
+  if (!mThirdPartyUtil && RequireThirdPartyCheck()) {
+    mThirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID);
+    NS_ASSERTION(mThirdPartyUtil, "require ThirdPartyUtil service");
+  }
+
   if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kCookieMoveIntervalSecs, &val))) {
     gMoveCookiesIntervalSeconds = clamped<uint32_t>(val, 0, 3600);
     if (gMoveCookiesIntervalSeconds && !mCookieTimer) {
       NS_NewTimerWithCallback(getter_AddRefs(mCookieTimer), this,
                               gMoveCookiesIntervalSeconds * 1000,
                               nsITimer::TYPE_REPEATING_SLACK_LOW_PRIORITY);
     }
     if (!gMoveCookiesIntervalSeconds && mCookieTimer) {
@@ -277,55 +287,49 @@ void CookieServiceChild::PrefChanged(nsI
       mCookieTimer->SetDelay(gMoveCookiesIntervalSeconds * 1000);
     }
   }
 }
 
 void CookieServiceChild::GetCookieStringFromCookieHashTable(
     nsIURI *aHostURI, bool aIsForeign, bool aIsTrackingResource,
     bool aFirstPartyStorageAccessGranted, bool aIsSafeTopLevelNav,
-    bool aIsSameSiteForeign, nsIChannel *aChannel, nsCString &aCookieString) {
+    bool aIsSameSiteForeign, const OriginAttributes &aOriginAttrs,
+    nsCString &aCookieString) {
   nsCOMPtr<nsIEffectiveTLDService> TLDService =
       do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
   NS_ASSERTION(TLDService, "Can't get TLDService");
   bool requireHostMatch;
   nsAutoCString baseDomain;
-
-  nsCOMPtr<nsILoadInfo> loadInfo;
-  mozilla::OriginAttributes attrs;
-  if (aChannel) {
-    loadInfo = aChannel->LoadInfo();
-    attrs = loadInfo->GetOriginAttributes();
-  }
-
   nsCookieService::GetBaseDomain(TLDService, aHostURI, baseDomain,
                                  requireHostMatch);
-  nsCookieKey key(baseDomain, attrs);
+  nsCookieKey key(baseDomain, aOriginAttrs);
   CookiesList *cookiesList = nullptr;
   mCookiesMap.Get(key, &cookiesList);
 
   if (!cookiesList) {
     return;
   }
 
   nsAutoCString hostFromURI, pathFromURI;
   bool isSecure;
   aHostURI->GetAsciiHost(hostFromURI);
   aHostURI->GetPathQueryRef(pathFromURI);
   aHostURI->SchemeIs("https", &isSecure);
   int64_t currentTimeInUsec = PR_Now();
   int64_t currentTime = currentTimeInUsec / PR_USEC_PER_SEC;
 
-  nsCOMPtr<nsICookieSettings> cookieSettings =
-      nsCookieService::GetCookieSettings(aChannel);
-
+  nsCOMPtr<nsICookiePermission> permissionService =
+      nsCookiePermission::GetOrCreate();
   CookieStatus cookieStatus = nsCookieService::CheckPrefs(
-      cookieSettings, mThirdPartySession, mThirdPartyNonsecureSession, aHostURI,
-      aIsForeign, aIsTrackingResource, aFirstPartyStorageAccessGranted, nullptr,
-      CountCookiesFromHashTable(baseDomain, attrs), attrs, nullptr);
+      permissionService, mCookieBehavior, mThirdPartySession,
+      mThirdPartyNonsecureSession, aHostURI, aIsForeign, aIsTrackingResource,
+      aFirstPartyStorageAccessGranted, nullptr,
+      CountCookiesFromHashTable(baseDomain, aOriginAttrs), aOriginAttrs,
+      nullptr);
 
   if (cookieStatus != STATUS_ACCEPTED &&
       cookieStatus != STATUS_ACCEPT_SESSION) {
     return;
   }
 
   cookiesList->Sort(CompareCookiesForSending());
   for (uint32_t i = 0; i < cookiesList->Length(); i++) {
@@ -400,27 +404,20 @@ void CookieServiceChild::SetCookieIntern
       aCookieAttributes.path, aCookieAttributes.expiryTime, currentTimeInUsec,
       nsCookie::GenerateUniqueCreationTime(currentTimeInUsec),
       aCookieAttributes.isSession, aCookieAttributes.isSecure,
       aCookieAttributes.isHttpOnly, aAttrs, aCookieAttributes.sameSite);
 
   RecordDocumentCookie(cookie, aAttrs);
 }
 
-bool CookieServiceChild::RequireThirdPartyCheck(nsILoadInfo *aLoadInfo) {
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  nsresult rv = aLoadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    return false;
-  }
-
-  uint32_t cookieBehavior = cookieSettings->GetCookieBehavior();
-  return cookieBehavior == nsICookieService::BEHAVIOR_REJECT_FOREIGN ||
-         cookieBehavior == nsICookieService::BEHAVIOR_LIMIT_FOREIGN ||
-         cookieBehavior == nsICookieService::BEHAVIOR_REJECT_TRACKER ||
+bool CookieServiceChild::RequireThirdPartyCheck() {
+  return mCookieBehavior == nsICookieService::BEHAVIOR_REJECT_FOREIGN ||
+         mCookieBehavior == nsICookieService::BEHAVIOR_LIMIT_FOREIGN ||
+         mCookieBehavior == nsICookieService::BEHAVIOR_REJECT_TRACKER ||
          mThirdPartySession || mThirdPartyNonsecureSession;
 }
 
 void CookieServiceChild::RecordDocumentCookie(nsCookie *aCookie,
                                               const OriginAttributes &aAttrs) {
   nsAutoCString baseDomain;
   nsCookieService::GetBaseDomainFromHost(mTLDService, aCookie->Host(),
                                          baseDomain);
@@ -468,22 +465,27 @@ nsresult CookieServiceChild::GetCookieSt
   *aCookieString = nullptr;
 
   // Fast past: don't bother sending IPC messages about nullprincipal'd
   // documents.
   nsAutoCString scheme;
   aHostURI->GetScheme(scheme);
   if (scheme.EqualsLiteral("moz-nullprincipal")) return NS_OK;
 
+  nsCOMPtr<nsILoadInfo> loadInfo;
+  mozilla::OriginAttributes attrs;
+  if (aChannel) {
+    loadInfo = aChannel->LoadInfo();
+    attrs = loadInfo->GetOriginAttributes();
+  }
+
   // Asynchronously call the parent.
   bool isForeign = true;
-  nsCOMPtr<nsILoadInfo> loadInfo = aChannel ? aChannel->LoadInfo() : nullptr;
-  if (RequireThirdPartyCheck(loadInfo)) {
+  if (RequireThirdPartyCheck())
     mThirdPartyUtil->IsThirdPartyChannel(aChannel, aHostURI, &isForeign);
-  }
 
   bool isTrackingResource = false;
   bool firstPartyStorageAccessGranted = false;
   nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
   if (httpChannel) {
     isTrackingResource = httpChannel->GetIsTrackingResource();
     // Check first-party storage access even for non-tracking resources, since
     // we will need the result when computing the access rights for the reject
@@ -495,17 +497,17 @@ nsresult CookieServiceChild::GetCookieSt
   }
 
   bool isSafeTopLevelNav = NS_IsSafeTopLevelNav(aChannel);
   bool isSameSiteForeign = NS_IsSameSiteForeign(aChannel, aHostURI);
 
   nsAutoCString result;
   GetCookieStringFromCookieHashTable(
       aHostURI, isForeign, isTrackingResource, firstPartyStorageAccessGranted,
-      isSafeTopLevelNav, isSameSiteForeign, aChannel, result);
+      isSafeTopLevelNav, isSameSiteForeign, attrs, result);
 
   if (!result.IsEmpty()) *aCookieString = ToNewCString(result);
 
   return NS_OK;
 }
 
 nsresult CookieServiceChild::SetCookieStringInternal(nsIURI *aHostURI,
                                                      nsIChannel *aChannel,
@@ -518,20 +520,18 @@ nsresult CookieServiceChild::SetCookieSt
   // Fast past: don't bother sending IPC messages about nullprincipal'd
   // documents.
   nsAutoCString scheme;
   aHostURI->GetScheme(scheme);
   if (scheme.EqualsLiteral("moz-nullprincipal")) return NS_OK;
 
   // Determine whether the request is foreign. Failure is acceptable.
   bool isForeign = true;
-  nsCOMPtr<nsILoadInfo> loadInfo = aChannel ? aChannel->LoadInfo() : nullptr;
-  if (RequireThirdPartyCheck(loadInfo)) {
+  if (RequireThirdPartyCheck())
     mThirdPartyUtil->IsThirdPartyChannel(aChannel, aHostURI, &isForeign);
-  }
 
   bool isTrackingResource = false;
   bool firstPartyStorageAccessGranted = false;
   nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
   if (httpChannel) {
     isTrackingResource = httpChannel->GetIsTrackingResource();
     // Check first-party storage access even for non-tracking resources, since
     // we will need the result when computing the access rights for the reject
@@ -551,46 +551,42 @@ nsresult CookieServiceChild::SetCookieSt
 
   Maybe<URIParams> channelURIParams;
   mozilla::OriginAttributes attrs;
   if (aChannel) {
     nsCOMPtr<nsIURI> channelURI;
     aChannel->GetURI(getter_AddRefs(channelURI));
     SerializeURI(channelURI, channelURIParams);
 
-    MOZ_ASSERT(loadInfo);
+    nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
     attrs = loadInfo->GetOriginAttributes();
   } else {
     SerializeURI(nullptr, channelURIParams);
   }
 
-  Maybe<LoadInfoArgs> optionalLoadInfoArgs;
-  LoadInfoToLoadInfoArgs(loadInfo, &optionalLoadInfoArgs);
-
   // Asynchronously call the parent.
   if (mIPCOpen) {
-    SendSetCookieString(hostURIParams, channelURIParams, optionalLoadInfoArgs,
-                        isForeign, isTrackingResource,
-                        firstPartyStorageAccessGranted, cookieString,
-                        stringServerTime, aFromHttp);
+    SendSetCookieString(hostURIParams, channelURIParams, isForeign,
+                        isTrackingResource, firstPartyStorageAccessGranted,
+                        cookieString, stringServerTime, attrs, aFromHttp);
   }
 
   bool requireHostMatch;
   nsCString baseDomain;
   nsCookieService::GetBaseDomain(mTLDService, aHostURI, baseDomain,
                                  requireHostMatch);
 
-  nsCOMPtr<nsICookieSettings> cookieSettings =
-      nsCookieService::GetCookieSettings(aChannel);
+  nsCOMPtr<nsICookiePermission> permissionService =
+      nsCookiePermission::GetOrCreate();
 
   CookieStatus cookieStatus = nsCookieService::CheckPrefs(
-      cookieSettings, mThirdPartySession, mThirdPartyNonsecureSession, aHostURI,
-      isForeign, isTrackingResource, firstPartyStorageAccessGranted,
-      aCookieString, CountCookiesFromHashTable(baseDomain, attrs), attrs,
-      nullptr);
+      permissionService, mCookieBehavior, mThirdPartySession,
+      mThirdPartyNonsecureSession, aHostURI, isForeign, isTrackingResource,
+      firstPartyStorageAccessGranted, aCookieString,
+      CountCookiesFromHashTable(baseDomain, attrs), attrs, nullptr);
 
   if (cookieStatus != STATUS_ACCEPTED &&
       cookieStatus != STATUS_ACCEPT_SESSION) {
     return NS_OK;
   }
 
   nsCookieKey key(baseDomain, attrs);
   CookiesList *cookies = mCookiesMap.Get(key);
@@ -619,18 +615,16 @@ nsresult CookieServiceChild::SetCookieSt
             cookie->IsHttpOnly()) {
           // Can't overwrite an httponly cookie from a script context.
           canSetCookie = false;
         }
       }
     }
 
     if (canSetCookie) {
-      nsCOMPtr<nsICookiePermission> permissionService =
-          nsCookiePermission::GetOrCreate();
       SetCookieInternal(cookieAttributes, attrs, aChannel, aFromHttp,
                         permissionService);
     }
 
     // document.cookie can only set one cookie at a time.
     if (!aFromHttp) {
       break;
     }
--- a/netwerk/cookie/CookieServiceChild.h
+++ b/netwerk/cookie/CookieServiceChild.h
@@ -14,17 +14,16 @@
 #include "nsIPrefBranch.h"
 #include "mozIThirdPartyUtil.h"
 #include "nsWeakReference.h"
 #include "nsThreadUtils.h"
 
 class nsCookie;
 class nsICookiePermission;
 class nsIEffectiveTLDService;
-class nsILoadInfo;
 
 struct nsCookieAttributes;
 
 namespace mozilla {
 namespace net {
 class CookieStruct;
 
 class CookieServiceChild : public PCookieServiceChild,
@@ -56,20 +55,23 @@ class CookieServiceChild : public PCooki
   void SerializeURIs(nsIURI *aHostURI, nsIChannel *aChannel,
                      nsCString &aHostSpec, nsCString &aHostCharset,
                      nsCString &aOriginatingSpec,
                      nsCString &aOriginatingCharset);
 
   nsresult GetCookieStringInternal(nsIURI *aHostURI, nsIChannel *aChannel,
                                    char **aCookieString);
 
-  void GetCookieStringFromCookieHashTable(
-      nsIURI *aHostURI, bool aIsForeign, bool aIsTrackingResource,
-      bool aFirstPartyStorageAccessGranted, bool aIsSafeTopLevelNav,
-      bool aIsSameSiteForeign, nsIChannel *aChannel, nsCString &aCookieString);
+  void GetCookieStringFromCookieHashTable(nsIURI *aHostURI, bool aIsForeign,
+                                          bool aIsTrackingResource,
+                                          bool aFirstPartyStorageAccessGranted,
+                                          bool aIsSafeTopLevelNav,
+                                          bool aIsSameSiteForeign,
+                                          const OriginAttributes &aAttrs,
+                                          nsCString &aCookieString);
 
   nsresult SetCookieStringInternal(nsIURI *aHostURI, nsIChannel *aChannel,
                                    const char *aCookieString,
                                    const char *aServerTime, bool aFromHttp);
 
   void RecordDocumentCookie(nsCookie *aCookie, const OriginAttributes &aAttrs);
 
   void SetCookieInternal(nsCookieAttributes &aCookieAttributes,
@@ -77,17 +79,17 @@ class CookieServiceChild : public PCooki
                          nsIChannel *aChannel, bool aFromHttp,
                          nsICookiePermission *aPermissionService);
 
   uint32_t CountCookiesFromHashTable(const nsCString &aBaseDomain,
                                      const OriginAttributes &aOriginAttrs);
 
   void PrefChanged(nsIPrefBranch *aPrefBranch);
 
-  bool RequireThirdPartyCheck(nsILoadInfo *aLoadInfo);
+  bool RequireThirdPartyCheck();
 
   mozilla::ipc::IPCResult RecvTrackCookiesLoad(
       nsTArray<CookieStruct> &&aCookiesList, const OriginAttributes &aAttrs);
 
   mozilla::ipc::IPCResult RecvRemoveAll();
 
   mozilla::ipc::IPCResult RecvRemoveBatchDeletedCookies(
       nsTArray<CookieStruct> &&aCookiesList,
@@ -100,16 +102,17 @@ class CookieServiceChild : public PCooki
                                         const OriginAttributes &aAttrs);
 
   virtual void ActorDestroy(ActorDestroyReason aWhy) override;
 
   CookiesMap mCookiesMap;
   nsCOMPtr<nsITimer> mCookieTimer;
   nsCOMPtr<mozIThirdPartyUtil> mThirdPartyUtil;
   nsCOMPtr<nsIEffectiveTLDService> mTLDService;
+  uint8_t mCookieBehavior;
   bool mThirdPartySession;
   bool mThirdPartyNonsecureSession;
   bool mIPCOpen;
 };
 
 }  // namespace net
 }  // namespace mozilla
 
--- a/netwerk/cookie/CookieServiceParent.cpp
+++ b/netwerk/cookie/CookieServiceParent.cpp
@@ -23,27 +23,38 @@ using mozilla::BasePrincipal;
 using mozilla::OriginAttributes;
 using mozilla::dom::PContentParent;
 using mozilla::net::NeckoParent;
 
 namespace {
 
 // Ignore failures from this function, as they only affect whether we do or
 // don't show a dialog box in private browsing mode if the user sets a pref.
-nsresult CreateDummyChannel(nsIURI *aHostURI, nsILoadInfo *aLoadInfo,
-                            nsIChannel **aChannel) {
-  nsCOMPtr<nsIChannel> dummyChannel;
-  nsresult rv =
-      NS_NewChannelInternal(getter_AddRefs(dummyChannel), aHostURI, aLoadInfo);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    return rv;
+void CreateDummyChannel(nsIURI *aHostURI, nsIURI *aChannelURI,
+                        OriginAttributes &aAttrs, nsIChannel **aChannel) {
+  nsCOMPtr<nsIPrincipal> principal =
+      BasePrincipal::CreateCodebasePrincipal(aHostURI, aAttrs);
+  if (!principal) {
+    return;
   }
 
+  // The following channel is never openend, so it does not matter what
+  // securityFlags we pass; let's follow the principle of least privilege.
+  nsCOMPtr<nsIChannel> dummyChannel;
+  NS_NewChannel(getter_AddRefs(dummyChannel), aChannelURI, principal,
+                nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED,
+                nsIContentPolicy::TYPE_INVALID);
+  nsCOMPtr<nsIPrivateBrowsingChannel> pbChannel =
+      do_QueryInterface(dummyChannel);
+  if (!pbChannel) {
+    return;
+  }
+
+  pbChannel->SetPrivate(aAttrs.mPrivateBrowsingId > 0);
   dummyChannel.forget(aChannel);
-  return NS_OK;
 }
 
 }  // namespace
 
 namespace mozilla {
 namespace net {
 
 CookieServiceParent::CookieServiceParent() {
@@ -200,60 +211,48 @@ mozilla::ipc::IPCResult CookieServicePar
 
 void CookieServiceParent::ActorDestroy(ActorDestroyReason aWhy) {
   // Nothing needed here. Called right before destructor since this is a
   // non-refcounted class.
 }
 
 mozilla::ipc::IPCResult CookieServiceParent::RecvSetCookieString(
     const URIParams &aHost, const Maybe<URIParams> &aChannelURI,
-    const Maybe<LoadInfoArgs> &aLoadInfoArgs, const bool &aIsForeign,
-    const bool &aIsTrackingResource,
+    const bool &aIsForeign, const bool &aIsTrackingResource,
     const bool &aFirstPartyStorageAccessGranted, const nsCString &aCookieString,
-    const nsCString &aServerTime, const bool &aFromHttp) {
+    const nsCString &aServerTime, const OriginAttributes &aAttrs,
+    const bool &aFromHttp) {
   if (!mCookieService) return IPC_OK();
 
   // Deserialize URI. Having a host URI is mandatory and should always be
   // provided by the child; thus we consider failure fatal.
   nsCOMPtr<nsIURI> hostURI = DeserializeURI(aHost);
   if (!hostURI) return IPC_FAIL_NO_REASON(this);
 
   nsCOMPtr<nsIURI> channelURI = DeserializeURI(aChannelURI);
 
-  nsCOMPtr<nsILoadInfo> loadInfo;
-  Unused << NS_WARN_IF(NS_FAILED(
-      LoadInfoArgsToLoadInfo(aLoadInfoArgs, getter_AddRefs(loadInfo))));
-
   // This is a gross hack. We've already computed everything we need to know
   // for whether to set this cookie or not, but we need to communicate all of
   // this information through to nsICookiePermission, which indirectly
   // computes the information from the channel. We only care about the
   // aIsPrivate argument as nsCookieService::SetCookieStringInternal deals
   // with aIsForeign before we have to worry about nsCookiePermission trying
   // to use the channel to inspect it.
   nsCOMPtr<nsIChannel> dummyChannel;
-  nsresult rv =
-      CreateDummyChannel(channelURI, loadInfo, getter_AddRefs(dummyChannel));
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    // No reason to kill the content process.
-    return IPC_OK();
-  }
+  CreateDummyChannel(hostURI, channelURI,
+                     const_cast<OriginAttributes &>(aAttrs),
+                     getter_AddRefs(dummyChannel));
 
   // NB: dummyChannel could be null if something failed in CreateDummyChannel.
   nsDependentCString cookieString(aCookieString, 0);
 
-  OriginAttributes attrs;
-  if (loadInfo) {
-    attrs = loadInfo->GetOriginAttributes();
-  }
-
   // We set this to true while processing this cookie update, to make sure
   // we don't send it back to the same content process.
   mProcessingCookie = true;
   mCookieService->SetCookieStringInternal(
       hostURI, aIsForeign, aIsTrackingResource, aFirstPartyStorageAccessGranted,
-      cookieString, aServerTime, aFromHttp, attrs, dummyChannel);
+      cookieString, aServerTime, aFromHttp, aAttrs, dummyChannel);
   mProcessingCookie = false;
   return IPC_OK();
 }
 
 }  // namespace net
 }  // namespace mozilla
--- a/netwerk/cookie/CookieServiceParent.h
+++ b/netwerk/cookie/CookieServiceParent.h
@@ -41,22 +41,20 @@ class CookieServiceParent : public PCook
   // processes, not the one they originated from.
   bool ProcessingCookie() { return mProcessingCookie; }
 
  protected:
   virtual void ActorDestroy(ActorDestroyReason aWhy) override;
 
   mozilla::ipc::IPCResult RecvSetCookieString(
       const URIParams &aHost, const Maybe<URIParams> &aChannelURI,
-      const Maybe<LoadInfoArgs> &aLoadInfoArgs, const bool &aIsForeign,
-      const bool &aIsTrackingResource,
+      const bool &aIsForeign, const bool &aIsTrackingResource,
       const bool &aFirstPartyStorageAccessGranted,
       const nsCString &aCookieString, const nsCString &aServerTime,
-      const bool &aFromHttp);
-
+      const OriginAttributes &aAttrs, const bool &aFromHttp);
   mozilla::ipc::IPCResult RecvPrepareCookieList(
       const URIParams &aHost, const bool &aIsForeign,
       const bool &aIsTackingResource,
       const bool &aFirstPartyStorageAccessGranted,
       const bool &aIsSafeTopLevelNav, const bool &aIsSameSiteForeign,
       const OriginAttributes &aAttrs);
 
   void SerialializeCookieList(const nsTArray<nsCookie *> &aFoundCookieList,
deleted file mode 100644
--- a/netwerk/cookie/CookieSettings.cpp
+++ /dev/null
@@ -1,246 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "mozilla/net/CookieSettings.h"
-#include "mozilla/Unused.h"
-#include "nsGlobalWindowInner.h"
-#include "nsPermission.h"
-#include "nsPermissionManager.h"
-
-namespace mozilla {
-namespace net {
-
-namespace {
-
-class PermissionComparator {
- public:
-  bool Equals(nsIPermission* aA, nsIPermission* aB) const {
-    nsCOMPtr<nsIPrincipal> principalA;
-    nsresult rv = aA->GetPrincipal(getter_AddRefs(principalA));
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      return false;
-    }
-
-    nsCOMPtr<nsIPrincipal> principalB;
-    rv = aB->GetPrincipal(getter_AddRefs(principalB));
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      return false;
-    }
-
-    bool equals = false;
-    rv = principalA->Equals(principalB, &equals);
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      return false;
-    }
-
-    return equals;
-  }
-};
-
-class ReleaseCookiePermissions final : public Runnable {
- public:
-  explicit ReleaseCookiePermissions(nsTArray<RefPtr<nsIPermission>>& aArray)
-      : Runnable("ReleaseCookiePermissions") {
-    mArray.SwapElements(aArray);
-  }
-
-  NS_IMETHOD Run() override {
-    MOZ_ASSERT(NS_IsMainThread());
-    mArray.Clear();
-    return NS_OK;
-  }
-
- private:
-  nsTArray<RefPtr<nsIPermission>> mArray;
-};
-
-}  // namespace
-
-// static
-already_AddRefed<nsICookieSettings> CookieSettings::CreateBlockingAll() {
-  MOZ_ASSERT(NS_IsMainThread());
-
-  RefPtr<CookieSettings> cookieSettings =
-      new CookieSettings(nsICookieService::BEHAVIOR_REJECT, eFixed);
-  return cookieSettings.forget();
-}
-
-// static
-already_AddRefed<nsICookieSettings> CookieSettings::Create() {
-  MOZ_ASSERT(NS_IsMainThread());
-
-  RefPtr<CookieSettings> cookieSettings = new CookieSettings(
-      StaticPrefs::network_cookie_cookieBehavior(), eProgressive);
-  return cookieSettings.forget();
-}
-
-CookieSettings::CookieSettings(uint32_t aCookieBehavior, State aState)
-    : mCookieBehavior(aCookieBehavior), mState(aState) {
-  MOZ_ASSERT(NS_IsMainThread());
-}
-
-CookieSettings::~CookieSettings() {
-  if (!NS_IsMainThread() && !mCookiePermissions.IsEmpty()) {
-    nsCOMPtr<nsIEventTarget> systemGroupEventTarget =
-        mozilla::SystemGroup::EventTargetFor(mozilla::TaskCategory::Other);
-    MOZ_ASSERT(systemGroupEventTarget);
-
-    RefPtr<Runnable> r = new ReleaseCookiePermissions(mCookiePermissions);
-    MOZ_ASSERT(mCookiePermissions.IsEmpty());
-
-    systemGroupEventTarget->Dispatch(r.forget());
-  }
-}
-
-NS_IMETHODIMP
-CookieSettings::GetCookieBehavior(uint32_t* aCookieBehavior) {
-  *aCookieBehavior = mCookieBehavior;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-CookieSettings::CookiePermission(nsIPrincipal* aPrincipal,
-                                 uint32_t* aCookiePermission) {
-  MOZ_ASSERT(NS_IsMainThread());
-  NS_ENSURE_ARG_POINTER(aPrincipal);
-  NS_ENSURE_ARG_POINTER(aCookiePermission);
-
-  *aCookiePermission = nsIPermissionManager::UNKNOWN_ACTION;
-
-  nsresult rv;
-
-  // Let's see if we know this permission.
-  for (const RefPtr<nsIPermission>& permission : mCookiePermissions) {
-    bool match = false;
-    rv = permission->Matches(aPrincipal, false, &match);
-    if (NS_WARN_IF(NS_FAILED(rv)) || !match) {
-      continue;
-    }
-
-    rv = permission->GetCapability(aCookiePermission);
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      return rv;
-    }
-
-    return NS_OK;
-  }
-
-  // Let's ask the permission manager.
-  nsPermissionManager* pm = nsPermissionManager::GetInstance();
-  if (NS_WARN_IF(!pm)) {
-    return NS_ERROR_FAILURE;
-  }
-
-  rv = pm->TestPermissionFromPrincipal(aPrincipal, NS_LITERAL_CSTRING("cookie"),
-                                       aCookiePermission);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    return rv;
-  }
-
-  // Let's store the permission, also if the result is UNKNOWN in order to avoid
-  // race conditions.
-
-  nsCOMPtr<nsIPermission> permission = nsPermission::Create(
-      aPrincipal, NS_LITERAL_CSTRING("cookie"), *aCookiePermission, 0, 0);
-  if (permission) {
-    mCookiePermissions.AppendElement(permission);
-  }
-
-  return NS_OK;
-}
-
-void CookieSettings::Serialize(CookieSettingsArgs& aData) {
-  MOZ_ASSERT(NS_IsMainThread());
-
-  aData.isFixed() = mState == eFixed;
-  aData.cookieBehavior() = mCookieBehavior;
-
-  for (const RefPtr<nsIPermission>& permission : mCookiePermissions) {
-    nsCOMPtr<nsIPrincipal> principal;
-    nsresult rv = permission->GetPrincipal(getter_AddRefs(principal));
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      continue;
-    }
-
-    PrincipalInfo principalInfo;
-    rv = PrincipalToPrincipalInfo(principal, &principalInfo);
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      continue;
-    }
-
-    uint32_t cookiePermission = 0;
-    rv = permission->GetCapability(&cookiePermission);
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      continue;
-    }
-
-    aData.cookiePermissions().AppendElement(
-        CookiePermissionData(principalInfo, cookiePermission));
-  }
-}
-
-/* static */ void CookieSettings::Deserialize(
-    const CookieSettingsArgs& aData, nsICookieSettings** aCookieSettings) {
-  MOZ_ASSERT(NS_IsMainThread());
-
-  CookiePermissionList list;
-  for (const CookiePermissionData& data : aData.cookiePermissions()) {
-    nsCOMPtr<nsIPrincipal> principal =
-        PrincipalInfoToPrincipal(data.principalInfo());
-    if (NS_WARN_IF(!principal)) {
-      continue;
-    }
-
-    nsCOMPtr<nsIPermission> permission = nsPermission::Create(
-        principal, NS_LITERAL_CSTRING("cookie"), data.cookiePermission(), 0, 0);
-    if (NS_WARN_IF(!permission)) {
-      continue;
-    }
-
-    list.AppendElement(permission);
-  }
-
-  RefPtr<CookieSettings> cookieSettings = new CookieSettings(
-      aData.cookieBehavior(), aData.isFixed() ? eFixed : eProgressive);
-
-  cookieSettings->mCookiePermissions.SwapElements(list);
-
-  cookieSettings.forget(aCookieSettings);
-}
-
-void CookieSettings::Merge(const CookieSettingsArgs& aData) {
-  MOZ_ASSERT(NS_IsMainThread());
-  MOZ_ASSERT(mCookieBehavior == aData.cookieBehavior());
-
-  if (mState == eFixed) {
-    return;
-  }
-
-  PermissionComparator comparator;
-
-  for (const CookiePermissionData& data : aData.cookiePermissions()) {
-    nsCOMPtr<nsIPrincipal> principal =
-        PrincipalInfoToPrincipal(data.principalInfo());
-    if (NS_WARN_IF(!principal)) {
-      continue;
-    }
-
-    nsCOMPtr<nsIPermission> permission = nsPermission::Create(
-        principal, NS_LITERAL_CSTRING("cookie"), data.cookiePermission(), 0, 0);
-    if (NS_WARN_IF(!permission)) {
-      continue;
-    }
-
-    if (!mCookiePermissions.Contains(permission, comparator)) {
-      mCookiePermissions.AppendElement(permission);
-    }
-  }
-}
-
-NS_IMPL_ISUPPORTS(CookieSettings, nsICookieSettings)
-
-}  // namespace net
-}  // namespace mozilla
deleted file mode 100644
--- a/netwerk/cookie/CookieSettings.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=8 sts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef mozilla_net_CookieSettings_h
-#define mozilla_net_CookieSettings_h
-
-#include "nsICookieSettings.h"
-#include "nsDataHashtable.h"
-
-class nsIPermission;
-
-namespace mozilla {
-namespace net {
-
-class CookieSettingsArgs;
-
-/**
- * CookieSettings
- * ~~~~~~~~~~~~~~
- *
- * CookieSettings is a snapshot of cookie policy and cookie permissions in a
- * precise moment of time. This object is used by top-level documents to have a
- * consistent cookie configuration also in case the user changes it. New cookie
- * configurations will apply only to new top-level documents.
- *
- * CookieSettings creation
- * ~~~~~~~~~~~~~~~~~~~~~~~
- *
- * CookieSettings is created when the top-level document's nsIChannel's
- * nsILoadInfo is constructed. Any sub-resource and any sub-document inherits it
- * from that nsILoadInfo. Also dedicated workers and their resources inherit it
- * from the parent document.
- *
- * SharedWorkers and ServiceWorkers have their own CookieSettings because they
- * don't have a single parent document (SharedWorkers could have more than one,
- * ServiceWorkers have none).
- *
- * In Chrome code, we have a new CookieSettings when we download resources via
- * 'Save-as...' and we also have a new CookieSettings for favicon downloading.
- *
- * Content-scripts WebExtensions also have their own CookieSettings because they
- * don't have a direct access to the document they are running into.
- *
- * Anything else will have a special CookieSettings which blocks everything
- * (CookieSettings::CreateBlockingAll()) by forcing BEHAVIOR_REJECT as policy.
- * When this happens, that context will not have access to the cookie jar and no
- * cookies are sent or received.
- *
- * Propagation of CookieSettings
- * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- *
- * CookieSettings are shared inside the same top-level document via its
- * nsIChannel's nsILoadInfo.  This is done automatically if you pass a nsINode
- * to NS_NewChannel(), and it must be done manually if you use a different
- * channel constructor. For instance, this happens for any worker networking
- * operation.
- *
- * We use the same CookieSettings for any resource belonging to the top-level
- * document even if cross-origin. This makes the browser behave consistently a
- * scenario where A loads B which loads A again, and cookie policy/permission
- * changes in the meantime.
- *
- * Cookie Permissions propagation
- * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- *
- * CookieSettings populates the known cookie permissions only when required.
- * Initially the list is empty, but when CookieSettings::CookiePermission() is
- * called, the requested permission is stored in the internal list if it doesn't
- * exist yet.
- *
- * This is actually nice because it relies on the permission propagation from
- * parent to content process. No extra IPC is required.
- *
- * Note that we store permissions with UNKNOWN_ACTION values too because they
- * can be set after the loading of the top-level document and we don't want to
- * return a different value when this happens.
- *
- * Use of CookieSettings
- * ~~~~~~~~~~~~~~~~~~~~~
- *
- * In theory, there should not be direct access to cookie permissions or
- * cookieBehavior pref. Everything should pass through CookieSettings.
- *
- * A reference to CookieSettings can be obtained from
- * nsILoadInfo::GetCookieSettings(), from Document::CookieSettings() and from
- * the WorkerPrivate::CookieSettings().
- *
- * CookieSettings is thread-safe, but the permission list must be touched only
- * on the main-thread.
- *
- * Testing
- * ~~~~~~~
- *
- * If you need to test the changing of cookie policy or a cookie permission, you
- * need to workaround CookieSettings. This can be done opening a new window and
- * running the test into that new global.
- */
-
-/**
- * Class that provides an nsICookieSettings implementation.
- */
-class CookieSettings final : public nsICookieSettings {
- public:
-  typedef nsTArray<RefPtr<nsIPermission>> CookiePermissionList;
-
-  NS_DECL_THREADSAFE_ISUPPORTS
-  NS_DECL_NSICOOKIESETTINGS
-
-  static already_AddRefed<nsICookieSettings> CreateBlockingAll();
-
-  static already_AddRefed<nsICookieSettings> Create();
-
-  void Serialize(CookieSettingsArgs& aData);
-
-  static void Deserialize(const CookieSettingsArgs& aData,
-                          nsICookieSettings** aCookieSettings);
-
-  void Merge(const CookieSettingsArgs& aData);
-
- private:
-  enum State {
-    // No cookie permissions are allowed to be stored in this object.
-    eFixed,
-
-    // Cookie permissions can be stored in case they are unknown when they are
-    // asked or when they are sent from the parent process.
-    eProgressive,
-  };
-
-  CookieSettings(uint32_t aCookieBehavior, State aState);
-  ~CookieSettings();
-
-  uint32_t mCookieBehavior;
-  CookiePermissionList mCookiePermissions;
-
-  State mState;
-};
-
-}  // namespace net
-}  // namespace mozilla
-
-#endif  // mozilla_net_CookieSettings_h
--- a/netwerk/cookie/PCookieService.ipdl
+++ b/netwerk/cookie/PCookieService.ipdl
@@ -35,18 +35,16 @@ parent:
 
   /*
    * Set a cookie string.
    *
    * @param host
    *        Same as the 'aURI' argument to nsICookieService.setCookieString.
    * @param channelURI
    *        The URI of the request.
-   * @param loadInfoArgs
-   *        The optional serialization of nsILoadInfo.
    * @param isForeign
    *        True if the the request is third party, for purposes of allowing
    *        access to cookies. This should be obtained from
    *        mozIThirdPartyUtil.isThirdPartyChannel. Third party requests may be
    *        rejected depending on user preferences; if those checks are
    *        disabled, this parameter is ignored.
    * @param isTrackingResource
    *        True if the request has been marked as tracking.
@@ -59,29 +57,32 @@ parent:
    * @param serverTime
    *        Same as the 'aServerTime' argument to
    *        nsICookieService.setCookieStringFromHttp. If the string is empty or
    *        null (e.g. for non-HTTP requests), the current local time is used.
    * @param fromHttp
    *        Whether the result is for an HTTP request header. This should be
    *        true for nsICookieService.setCookieStringFromHttp calls, false
    *        otherwise.
+   * @param attrs
+   *        The origin attributes from the HTTP channel or document that the
+   *        cookie is being set on.
    *
    * @see nsICookieService.setCookieString
    * @see nsICookieService.setCookieStringFromHttp
    * @see mozIThirdPartyUtil.isThirdPartyChannel
    */
   nested(inside_cpow) async SetCookieString(URIParams host,
                                             URIParams? channelURI,
-                                            LoadInfoArgs? loadInfoArgs,
                                             bool isForeign,
                                             bool isTrackingResource,
                                             bool firstPartyStorageAccessGranted,
                                             nsCString cookieString,
                                             nsCString serverTime,
+                                            OriginAttributes attrs,
                                             bool aFromHttp);
 
   async PrepareCookieList(URIParams host,
                           bool isForeign,
                           bool isTrackingResource,
                           bool firstPartyStorageAccessGranted,
                           bool isSafeTopLevelNav,
                           bool isSameSiteForeign,
--- a/netwerk/cookie/moz.build
+++ b/netwerk/cookie/moz.build
@@ -9,56 +9,47 @@ with Files('**'):
 
 # export required interfaces, even if --disable-cookies has been given
 XPIDL_SOURCES += [
     'nsICookie.idl',
     'nsICookie2.idl',
     'nsICookieManager.idl',
     'nsICookiePermission.idl',
     'nsICookieService.idl',
-    'nsICookieSettings.idl',
 ]
 
 XPIDL_MODULE = 'necko_cookie'
 
 if CONFIG['NECKO_COOKIES']:
     EXPORTS.mozilla.net = [
         'CookieServiceChild.h',
         'CookieServiceParent.h',
-        'CookieSettings.h',
         'nsCookieKey.h',
     ]
     UNIFIED_SOURCES += [
         'CookieServiceChild.cpp',
         'CookieServiceParent.cpp',
-        'CookieSettings.cpp',
         'nsCookie.cpp',
     ]
     # nsCookieService.cpp can't be unified because of symbol conflicts
     SOURCES += [
         'nsCookieService.cpp',
     ]
     LOCAL_INCLUDES += [
-        '/dom/base',
-        '/extensions/cookie',
         '/intl/uconv',
     ]
 
     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/nsCookieService.cpp
+++ b/netwerk/cookie/nsCookieService.cpp
@@ -7,17 +7,16 @@
 #include "mozilla/AntiTrackingCommon.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Likely.h"
 #include "mozilla/Printf.h"
 #include "mozilla/Unused.h"
 
-#include "mozilla/net/CookieSettings.h"
 #include "mozilla/net/CookieServiceChild.h"
 #include "mozilla/net/NeckoCommon.h"
 
 #include "nsCookieService.h"
 #include "nsContentUtils.h"
 #include "nsIServiceManager.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIWebProgressListener.h"
@@ -121,16 +120,17 @@ static const int64_t kCookiePurgeAge =
 // network.cookie.maxNumber and network.cookie.maxPerHost prefs respectively.
 static const uint32_t kMaxNumberOfCookies = 3000;
 static const uint32_t kMaxCookiesPerHost = 180;
 static const uint32_t kCookieQuotaPerHost = 150;
 static const uint32_t kMaxBytesPerCookie = 4096;
 static const uint32_t kMaxBytesPerPath = 1024;
 
 // pref string constants
+static const char kPrefCookieBehavior[] = "network.cookie.cookieBehavior";
 static const char kPrefMaxNumberOfCookies[] = "network.cookie.maxNumber";
 static const char kPrefMaxCookiesPerHost[] = "network.cookie.maxPerHost";
 static const char kPrefCookieQuotaPerHost[] = "network.cookie.quotaPerHost";
 static const char kPrefCookiePurgeAge[] = "network.cookie.purgeAge";
 static const char kPrefThirdPartySession[] =
     "network.cookie.thirdparty.sessionOnly";
 static const char kPrefThirdPartyNonsecureSession[] =
     "network.cookie.thirdparty.nonsecureSessionOnly";
@@ -581,16 +581,17 @@ void nsCookieService::AppClearDataObserv
  * public methods
  ******************************************************************************/
 
 NS_IMPL_ISUPPORTS(nsCookieService, nsICookieService, nsICookieManager,
                   nsIObserver, nsISupportsWeakReference, nsIMemoryReporter)
 
 nsCookieService::nsCookieService()
     : mDBState(nullptr),
+      mCookieBehavior(nsICookieService::BEHAVIOR_ACCEPT),
       mThirdPartySession(false),
       mThirdPartyNonsecureSession(false),
       mMaxNumberOfCookies(kMaxNumberOfCookies),
       mMaxCookiesPerHost(kMaxCookiesPerHost),
       mCookieQuotaPerHost(kCookieQuotaPerHost),
       mCookiePurgeAge(kCookiePurgeAge),
       mThread(nullptr),
       mMonitor("CookieThread"),
@@ -606,16 +607,17 @@ nsresult nsCookieService::Init() {
   NS_ENSURE_SUCCESS(rv, rv);
 
   mThirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // init our pref and observer
   nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
   if (prefBranch) {
+    prefBranch->AddObserver(kPrefCookieBehavior, this, true);
     prefBranch->AddObserver(kPrefMaxNumberOfCookies, this, true);
     prefBranch->AddObserver(kPrefMaxCookiesPerHost, this, true);
     prefBranch->AddObserver(kPrefCookiePurgeAge, this, true);
     prefBranch->AddObserver(kPrefThirdPartySession, this, true);
     prefBranch->AddObserver(kPrefThirdPartyNonsecureSession, this, true);
     PrefChanged(prefBranch);
   }
 
@@ -1998,34 +2000,16 @@ nsresult nsCookieService::GetCookieStrin
   nsAutoCString result;
   GetCookieStringInternal(aHostURI, aChannel, isForeign, isTrackingResource,
                           firstPartyStorageAccessGranted, isSafeTopLevelNav,
                           isSameSiteForeign, aHttpBound, attrs, result);
   *aCookie = result.IsEmpty() ? nullptr : ToNewCString(result);
   return NS_OK;
 }
 
-// static
-already_AddRefed<nsICookieSettings> nsCookieService::GetCookieSettings(
-    nsIChannel *aChannel) {
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  if (aChannel) {
-    nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
-    nsresult rv = loadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      cookieSettings = CookieSettings::CreateBlockingAll();
-    }
-  } else {
-    cookieSettings = CookieSettings::Create();
-  }
-
-  MOZ_ASSERT(cookieSettings);
-  return cookieSettings.forget();
-}
-
 NS_IMETHODIMP
 nsCookieService::SetCookieString(nsIURI *aHostURI, nsIPrompt *aPrompt,
                                  const char *aCookieHeader,
                                  nsIChannel *aChannel) {
   // The aPrompt argument is deprecated and unused.  Avoid introducing new
   // code that uses this argument by warning if the value is non-null.
   MOZ_ASSERT(!aPrompt);
   if (aPrompt) {
@@ -2149,28 +2133,28 @@ void nsCookieService::SetCookieStringInt
       GetBaseDomain(mTLDService, aHostURI, baseDomain, requireHostMatch);
   if (NS_FAILED(rv)) {
     COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
                       "couldn't get base domain from URI");
     return;
   }
 
   nsCookieKey key(baseDomain, aOriginAttrs);
-  nsCOMPtr<nsICookieSettings> cookieSettings = GetCookieSettings(aChannel);
 
   // check default prefs
   uint32_t priorCookieCount = 0;
   uint32_t rejectedReason = 0;
   nsAutoCString hostFromURI;
   aHostURI->GetHost(hostFromURI);
   CountCookiesFromHost(hostFromURI, &priorCookieCount);
   CookieStatus cookieStatus = CheckPrefs(
-      cookieSettings, mThirdPartySession, mThirdPartyNonsecureSession, aHostURI,
-      aIsForeign, aIsTrackingResource, aFirstPartyStorageAccessGranted,
-      aCookieHeader.get(), priorCookieCount, aOriginAttrs, &rejectedReason);
+      mPermissionService, mCookieBehavior, mThirdPartySession,
+      mThirdPartyNonsecureSession, aHostURI, aIsForeign, aIsTrackingResource,
+      aFirstPartyStorageAccessGranted, aCookieHeader.get(), priorCookieCount,
+      aOriginAttrs, &rejectedReason);
 
   MOZ_ASSERT_IF(rejectedReason, cookieStatus == STATUS_REJECTED);
 
   // fire a notification if third party or if cookie was rejected
   // (but not if there was an error)
   switch (cookieStatus) {
     case STATUS_REJECTED:
       NotifyRejected(aHostURI, aChannel, rejectedReason, OPERATION_WRITE);
@@ -2371,16 +2355,20 @@ nsCookieService::RunInTransaction(nsICoo
 
 /******************************************************************************
  * nsCookieService:
  * pref observer impl
  ******************************************************************************/
 
 void nsCookieService::PrefChanged(nsIPrefBranch *aPrefBranch) {
   int32_t val;
+  if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefCookieBehavior, &val)))
+    mCookieBehavior =
+        (uint8_t)LIMIT(val, 0, nsICookieService::BEHAVIOR_LAST, 0);
+
   if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefMaxNumberOfCookies, &val)))
     mMaxNumberOfCookies = (uint16_t)LIMIT(val, 1, 0xFFFF, kMaxNumberOfCookies);
 
   if (NS_SUCCEEDED(aPrefBranch->GetIntPref(kPrefCookieQuotaPerHost, &val))) {
     mCookieQuotaPerHost =
         (uint16_t)LIMIT(val, 1, mMaxCookiesPerHost - 1, kCookieQuotaPerHost);
   }
 
@@ -3045,26 +3033,25 @@ void nsCookieService::GetCookiesForURI(
   if (NS_SUCCEEDED(rv)) rv = aHostURI->GetAsciiHost(hostFromURI);
   if (NS_SUCCEEDED(rv)) rv = aHostURI->GetPathQueryRef(pathFromURI);
   if (NS_FAILED(rv)) {
     COOKIE_LOGFAILURE(GET_COOKIE, aHostURI, nullptr,
                       "invalid host/path from URI");
     return;
   }
 
-  nsCOMPtr<nsICookieSettings> cookieSettings = GetCookieSettings(aChannel);
-
   // check default prefs
   uint32_t rejectedReason = 0;
   uint32_t priorCookieCount = 0;
   CountCookiesFromHost(hostFromURI, &priorCookieCount);
-  CookieStatus cookieStatus = CheckPrefs(
-      cookieSettings, mThirdPartySession, mThirdPartyNonsecureSession, aHostURI,
-      aIsForeign, aIsTrackingResource, aFirstPartyStorageAccessGranted, nullptr,
-      priorCookieCount, aOriginAttrs, &rejectedReason);
+  CookieStatus cookieStatus =
+      CheckPrefs(mPermissionService, mCookieBehavior, mThirdPartySession,
+                 mThirdPartyNonsecureSession, aHostURI, aIsForeign,
+                 aIsTrackingResource, aFirstPartyStorageAccessGranted, nullptr,
+                 priorCookieCount, aOriginAttrs, &rejectedReason);
 
   MOZ_ASSERT_IF(rejectedReason, cookieStatus == STATUS_REJECTED);
 
   // for GetCookie(), we only fire acceptance/rejection notifications
   // (but not if there was an error)
   switch (cookieStatus) {
     case STATUS_REJECTED:
       NotifyRejected(aHostURI, aChannel, rejectedReason, OPERATION_READ);
@@ -3977,21 +3964,22 @@ nsresult nsCookieService::NormalizeHost(
 static inline bool IsSubdomainOf(const nsCString &a, const nsCString &b) {
   if (a == b) return true;
   if (a.Length() > b.Length())
     return a[a.Length() - b.Length() - 1] == '.' && StringEndsWith(a, b);
   return false;
 }
 
 CookieStatus nsCookieService::CheckPrefs(
-    nsICookieSettings *aCookieSettings, bool aThirdPartySession,
-    bool aThirdPartyNonsecureSession, nsIURI *aHostURI, bool aIsForeign,
-    bool aIsTrackingResource, bool aFirstPartyStorageAccessGranted,
-    const char *aCookieHeader, const int aNumOfCookies,
-    const OriginAttributes &aOriginAttrs, uint32_t *aRejectedReason) {
+    nsICookiePermission *aPermissionService, uint8_t aCookieBehavior,
+    bool aThirdPartySession, bool aThirdPartyNonsecureSession, nsIURI *aHostURI,
+    bool aIsForeign, bool aIsTrackingResource,
+    bool aFirstPartyStorageAccessGranted, const char *aCookieHeader,
+    const int aNumOfCookies, const OriginAttributes &aOriginAttrs,
+    uint32_t *aRejectedReason) {
   nsresult rv;
 
   // Let's use a internal value in order to avoid a null check on
   // aRejectedReason everywhere.
   uint32_t rejectedReason = 0;
   if (!aRejectedReason) {
     aRejectedReason = &rejectedReason;
   }
@@ -4013,70 +4001,72 @@ CookieStatus nsCookieService::CheckPrefs
     COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI,
                       aCookieHeader,
                       "non-codebase principals cannot get/set cookies");
     return STATUS_REJECTED_WITH_ERROR;
   }
 
   // check the permission list first; if we find an entry, it overrides
   // default prefs. see bug 184059.
-  uint32_t cookiePermission = nsICookiePermission::ACCESS_DEFAULT;
-  rv = aCookieSettings->CookiePermission(principal, &cookiePermission);
-  if (NS_SUCCEEDED(rv)) {
-    switch (cookiePermission) {
-      case nsICookiePermission::ACCESS_DENY:
-        COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI,
-                          aCookieHeader, "cookies are blocked for this site");
-        *aRejectedReason =
-            nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;
-        return STATUS_REJECTED;
-
-      case nsICookiePermission::ACCESS_ALLOW:
-        return STATUS_ACCEPTED;
+  if (aPermissionService) {
+    nsCookieAccess access;
+    // Not passing an nsIChannel here is probably OK; our implementation
+    // doesn't do anything with it anyway.
+    rv = aPermissionService->CanAccess(principal, &access);
+
+    // if we found an entry, use it
+    if (NS_SUCCEEDED(rv)) {
+      switch (access) {
+        case nsICookiePermission::ACCESS_DENY:
+          COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI,
+                            aCookieHeader, "cookies are blocked for this site");
+          *aRejectedReason =
+              nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;
+          return STATUS_REJECTED;
+
+        case nsICookiePermission::ACCESS_ALLOW:
+          return STATUS_ACCEPTED;
+      }
     }
   }
 
   // No cookies allowed if this request comes from a tracker, in a 3rd party
   // context, when anti-tracking protection is enabled and when we don't have
   // access to the first-party cookie jar.
   if (aIsForeign && aIsTrackingResource && !aFirstPartyStorageAccessGranted &&
-      aCookieSettings->GetCookieBehavior() ==
-          nsICookieService::BEHAVIOR_REJECT_TRACKER) {
+      aCookieBehavior == nsICookieService::BEHAVIOR_REJECT_TRACKER) {
     COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI,
                       aCookieHeader, "cookies are disabled in trackers");
     *aRejectedReason = nsIWebProgressListener::STATE_COOKIES_BLOCKED_TRACKER;
     return STATUS_REJECTED;
   }
 
   // check default prefs.
   // Check aFirstPartyStorageAccessGranted when checking aCookieBehavior
   // so that we take things such as the content blocking allow list into
   // account.
-  if (aCookieSettings->GetCookieBehavior() ==
-          nsICookieService::BEHAVIOR_REJECT &&
+  if (aCookieBehavior == nsICookieService::BEHAVIOR_REJECT &&
       !aFirstPartyStorageAccessGranted) {
     COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI,
                       aCookieHeader, "cookies are disabled");
     *aRejectedReason = nsIWebProgressListener::STATE_COOKIES_BLOCKED_ALL;
     return STATUS_REJECTED;
   }
 
   // check if cookie is foreign
   if (aIsForeign) {
-    if (aCookieSettings->GetCookieBehavior() ==
-            nsICookieService::BEHAVIOR_REJECT_FOREIGN &&
+    if (aCookieBehavior == nsICookieService::BEHAVIOR_REJECT_FOREIGN &&
         !aFirstPartyStorageAccessGranted) {
       COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI,
                         aCookieHeader, "context is third party");
       *aRejectedReason = nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN;
       return STATUS_REJECTED;
     }
 
-    if (aCookieSettings->GetCookieBehavior() ==
-            nsICookieService::BEHAVIOR_LIMIT_FOREIGN &&
+    if (aCookieBehavior == nsICookieService::BEHAVIOR_LIMIT_FOREIGN &&
         !aFirstPartyStorageAccessGranted && aNumOfCookies == 0) {
       COOKIE_LOGFAILURE(aCookieHeader ? SET_COOKIE : GET_COOKIE, aHostURI,
                         aCookieHeader, "context is third party");
       *aRejectedReason = nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN;
       return STATUS_REJECTED;
     }
 
     if (aThirdPartySession) return STATUS_ACCEPT_SESSION;
--- a/netwerk/cookie/nsCookieService.h
+++ b/netwerk/cookie/nsCookieService.h
@@ -3,17 +3,16 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsCookieService_h__
 #define nsCookieService_h__
 
 #include "nsICookieService.h"
 #include "nsICookieManager.h"
-#include "nsICookiePermission.h"
 #include "nsIObserver.h"
 #include "nsWeakReference.h"
 
 #include "nsCookie.h"
 #include "nsCookieKey.h"
 #include "nsString.h"
 #include "nsAutoPtr.h"
 #include "nsHashKeys.h"
@@ -34,17 +33,16 @@
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/Monitor.h"
 #include "mozilla/UniquePtr.h"
 
 using mozilla::OriginAttributes;
 
 class nsICookiePermission;
-class nsICookieSettings;
 class nsIEffectiveTLDService;
 class nsIIDNService;
 class nsIPrefBranch;
 class nsIObserverService;
 class nsIURI;
 class nsIChannel;
 class nsIArray;
 class nsIThread;
@@ -255,26 +253,23 @@ class nsCookieService final : public nsI
   static bool CanSetCookie(nsIURI *aHostURI, const nsCookieKey &aKey,
                            nsCookieAttributes &aCookieAttributes,
                            bool aRequireHostMatch, CookieStatus aStatus,
                            nsDependentCString &aCookieHeader,
                            int64_t aServerTime, bool aFromHttp,
                            nsIChannel *aChannel, bool &aSetCookie,
                            mozIThirdPartyUtil *aThirdPartyUtil);
   static CookieStatus CheckPrefs(
-      nsICookieSettings *aCookieSettings, bool aThirdPartySession,
-      bool aThirdPartyNonsecureSession, nsIURI *aHostURI, bool aIsForeign,
-      bool aIsTrackingResource, bool aIsFirstPartyStorageAccessGranted,
-      const char *aCookieHeader, const int aNumOfCookies,
-      const OriginAttributes &aOriginAttrs, uint32_t *aRejectedReason);
+      nsICookiePermission *aPermissionServices, uint8_t aCookieBehavior,
+      bool aThirdPartySession, bool aThirdPartyNonsecureSession,
+      nsIURI *aHostURI, bool aIsForeign, bool aIsTrackingResource,
+      bool aIsFirstPartyStorageAccessGranted, const char *aCookieHeader,
+      const int aNumOfCookies, const OriginAttributes &aOriginAttrs,
+      uint32_t *aRejectedReason);
   static int64_t ParseServerTime(const nsCString &aServerTime);
-
-  static already_AddRefed<nsICookieSettings> GetCookieSettings(
-      nsIChannel *aChannel);
-
   void GetCookiesForURI(nsIURI *aHostURI, nsIChannel *aChannel, bool aIsForeign,
                         bool aIsTrackingResource,
                         bool aFirstPartyStorageAccessGranted,
                         bool aIsSafeTopLevelNav, bool aIsSameSiteForeign,
                         bool aHttpBound, const OriginAttributes &aOriginAttrs,
                         nsTArray<nsCookie *> &aCookieList);
 
  protected:
@@ -398,16 +393,19 @@ class nsCookieService final : public nsI
   // private browsing, switching between them on a per-cookie-request basis.
   // this state encapsulates both the in-memory table and the on-disk DB.
   // note that the private states' dbConn should always be null - we never
   // want to be dealing with the on-disk DB when in private browsing.
   DBState *mDBState;
   RefPtr<DBState> mDefaultDBState;
   RefPtr<DBState> mPrivateDBState;
 
+  // cached prefs
+  uint8_t mCookieBehavior;  // BEHAVIOR_{ACCEPT, REJECTFOREIGN, REJECT,
+                            // LIMITFOREIGN}
   bool mThirdPartySession;
   bool mThirdPartyNonsecureSession;
   uint16_t mMaxNumberOfCookies;
   uint16_t mMaxCookiesPerHost;
   uint16_t mCookieQuotaPerHost;
   int64_t mCookiePurgeAge;
 
   // thread
deleted file mode 100644
--- a/netwerk/cookie/nsICookieSettings.idl
+++ /dev/null
@@ -1,30 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: ft=cpp tw=78 sw=2 et ts=2 sts=2 cin
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsISupports.idl"
-
-interface nsIPrincipal;
-
-/**
- * Cookie settings for top-level documents.
- */
-[builtinclass, uuid(3ec40331-7cf0-4b71-ba2a-2265aab8f6bc)]
-interface nsICookieSettings : nsISupports
-{
-  /**
-   * CookieBehavior at the loading of the document. Any other loadInfo
-   * inherits it from its document's loadInfo. If there is not a document
-   * involved, cookieBehavior is reject.
-   */
-  [infallible] readonly attribute unsigned long cookieBehavior;
-
-  /**
-   * CookiePermission at the loading of the document for a particular
-   * principal. It returns the same cookiePermission also in case it changes
-   * during the life-time of the top document.
-   */
-  unsigned long cookiePermission(in nsIPrincipal aPrincipal);
-};
--- a/netwerk/cookie/test/browser/browser.ini
+++ b/netwerk/cookie/test/browser/browser.ini
@@ -1,15 +1,5 @@
 [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]
deleted file mode 100644
--- a/netwerk/cookie/test/browser/browser_broadcastChannel.js
+++ /dev/null
@@ -1,77 +0,0 @@
-// BroadcastChannel is not considered part of CookieJar. It's not allowed to
-// communicate with other windows with different cookie settings.
-
-CookiePolicyHelper.runTest("BroadcastChannel", {
-  cookieJarAccessAllowed: async w => {
-    new w.BroadcastChannel("hello");
-    ok(true, "BroadcastChannel be used");
-  },
-
-  cookieJarAccessDenied: async w => {
-    try {
-      new w.BroadcastChannel("hello");
-      ok(false, "BroadcastChannel cannot be used!");
-    } catch (e) {
-      ok(true, "BroadcastChannel cannot be used!");
-      is(e.name, "SecurityError", "We want a security error message.");
-    }
-  }
-});
-
-CookiePolicyHelper.runTest("BroadcastChannel in workers", {
-  cookieJarAccessAllowed: async w => {
-    function nonBlockingCode() {
-      new BroadcastChannel("hello");
-      postMessage(true);
-    }
-
-    let blob = new w.Blob([nonBlockingCode.toString() + "; nonBlockingCode();"]);
-    ok(blob, "Blob has been created");
-
-    let blobURL = w.URL.createObjectURL(blob);
-    ok(blobURL, "Blob URL has been created");
-
-    let worker = new w.Worker(blobURL);
-    ok(worker, "Worker has been created");
-
-    await new w.Promise((resolve, reject) => {
-      worker.onmessage = function(e) {
-        if (e) {
-          resolve();
-        } else {
-          reject();
-        }
-      };
-    });
-  },
-
-  cookieJarAccessDenied: async w => {
-    function blockingCode() {
-      try {
-        new BroadcastChannel("hello");
-        postMessage(false);
-      } catch (e) {
-        postMessage(e.name == "SecurityError");
-      }
-    }
-
-    let blob = new w.Blob([blockingCode.toString() + "; blockingCode();"]);
-    ok(blob, "Blob has been created");
-
-    let blobURL = w.URL.createObjectURL(blob);
-    ok(blobURL, "Blob URL has been created");
-
-    let worker = new w.Worker(blobURL);
-    ok(worker, "Worker has been created");
-
-    await new w.Promise((resolve, reject) => {
-      worker.onmessage = function(e) {
-        if (e) {
-          resolve();
-        } else {
-          reject();
-        }
-      };
-    });
-  }
-});
deleted file mode 100644
--- a/netwerk/cookie/test/browser/browser_cookies.js
+++ /dev/null
@@ -1,35 +0,0 @@
-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");
-  }
-});
deleted file mode 100644
--- a/netwerk/cookie/test/browser/browser_domCache.js
+++ /dev/null
@@ -1,13 +0,0 @@
-CookiePolicyHelper.runTest("DOM Cache", {
-  cookieJarAccessAllowed: async w => {
-    await w.caches.open("wow").then(
-      _ => { ok(true, "DOM Cache can be used!"); },
-      _ => { ok(false, "DOM Cache can be used!"); });
-  },
-
-  cookieJarAccessDenied: async w => {
-    await w.caches.open("wow").then(
-      _ => { ok(false, "DOM Cache cannot be used!"); },
-      _ => { ok(true, "DOM Cache cannot be used!"); });
-  },
-});
deleted file mode 100644
--- a/netwerk/cookie/test/browser/browser_indexedDB.js
+++ /dev/null
@@ -1,82 +0,0 @@
-CookiePolicyHelper.runTest("IndexedDB", {
-  cookieJarAccessAllowed: async w => {
-    w.indexedDB.open("test", "1");
-    ok(true, "IDB should be allowed");
-  },
-
-  cookieJarAccessDenied: async w => {
-    try {
-      w.indexedDB.open("test", "1");
-      ok(false, "IDB should be blocked");
-    } catch (e) {
-      ok(true, "IDB should be blocked");
-      is(e.name, "SecurityError", "We want a security error message.");
-    }
-  },
-});
-
-CookiePolicyHelper.runTest("IndexedDB in workers", {
-  cookieJarAccessAllowed: async w => {
-    function nonBlockCode() {
-      indexedDB.open("test", "1");
-      postMessage(true);
-    }
-
-    let blob = new w.Blob([nonBlockCode.toString() + "; nonBlockCode();"]);
-    ok(blob, "Blob has been created");
-
-    let blobURL = w.URL.createObjectURL(blob);
-    ok(blobURL, "Blob URL has been created");
-
-    let worker = new w.Worker(blobURL);
-    ok(worker, "Worker has been created");
-
-    await new w.Promise((resolve, reject) => {
-      worker.onmessage = function(e) {
-        if (e.data) {
-          resolve();
-        } else {
-          reject();
-        }
-      };
-
-      worker.onerror = function(e) {
-        reject();
-      };
-    });
-  },
-
-  cookieJarAccessDenied: async w => {
-    function blockCode() {
-      try {
-        indexedDB.open("test", "1");
-        postMessage(false);
-      } catch (e) {
-        postMessage(e.name == "SecurityError");
-      }
-    }
-
-    let blob = new w.Blob([blockCode.toString() + "; blockCode();"]);
-    ok(blob, "Blob has been created");
-
-    let blobURL = w.URL.createObjectURL(blob);
-    ok(blobURL, "Blob URL has been created");
-
-    let worker = new w.Worker(blobURL);
-    ok(worker, "Worker has been created");
-
-    await new w.Promise((resolve, reject) => {
-      worker.onmessage = function(e) {
-        if (e.data) {
-          resolve();
-        } else {
-          reject();
-        }
-      };
-
-      worker.onerror = function(e) {
-        reject();
-      };
-    });
-  },
-});
deleted file mode 100644
--- a/netwerk/cookie/test/browser/browser_serviceWorker.js
+++ /dev/null
@@ -1,24 +0,0 @@
-CookiePolicyHelper.runTest("ServiceWorker", {
-  prefs: [
-    ["dom.serviceWorkers.exemptFromPerDomainMax", true],
-    ["dom.ipc.processCount", 1],
-    ["dom.serviceWorkers.enabled", true],
-    ["dom.serviceWorkers.testing.enabled", true],
-  ],
-
-  cookieJarAccessAllowed: async w => {
-    await w.navigator.serviceWorker.register("file_empty.js").then(
-      reg => { ok(true, "ServiceWorker can be used!"); return reg; },
-      _ => { ok(false, "ServiceWorker cannot be used! " + _); }).then(
-      reg => reg.unregister(),
-      _ => { ok(false, "unregister failed"); }).
-      catch(e => ok(false, "Promise rejected: " + e));
-  },
-
-  cookieJarAccessDenied: async w => {
-    await w.navigator.serviceWorker.register("file_empty.js").then(
-      _ => { ok(false, "ServiceWorker cannot be used!"); },
-      _ => { ok(true, "ServiceWorker cannot be used!"); }).
-      catch(e => ok(false, "Promise rejected: " + e));
-  },
-});
deleted file mode 100644
--- a/netwerk/cookie/test/browser/browser_sharedWorker.js
+++ /dev/null
@@ -1,16 +0,0 @@
-CookiePolicyHelper.runTest("SharedWorker", {
-  cookieJarAccessAllowed: async w => {
-    new w.SharedWorker("a.js", "foo");
-    ok(true, "SharedWorker is allowed");
-  },
-
-  cookieJarAccessDenied: async w => {
-    try {
-      new w.SharedWorker("a.js", "foo");
-      ok(false, "SharedWorker cannot be used!");
-    } catch (e) {
-      ok(true, "SharedWorker cannot be used!");
-      is(e.name, "SecurityError", "We want a security error message.");
-    }
-  },
-});
deleted file mode 100644
--- a/netwerk/cookie/test/browser/browser_storage.js
+++ /dev/null
@@ -1,41 +0,0 @@
-CookiePolicyHelper.runTest("SessionStorage", {
-  cookieJarAccessAllowed: async w => {
-    try {
-      w.sessionStorage.foo = 42;
-      ok(true, "SessionStorage works");
-    } catch (e) {
-      ok(false, "SessionStorage works");
-    }
-  },
-
-  cookieJarAccessDenied: async w => {
-    try {
-      w.sessionStorage.foo = 42;
-      ok(false, "SessionStorage doesn't work");
-    } catch (e) {
-      ok(true, "SessionStorage doesn't work");
-      is(e.name, "SecurityError", "We want a security error message.");
-    }
-  },
-});
-
-CookiePolicyHelper.runTest("LocalStorage", {
-  cookieJarAccessAllowed: async w => {
-    try {
-      w.localStorage.foo = 42;
-      ok(true, "LocalStorage works");
-    } catch (e) {
-      ok(false, "LocalStorage works");
-    }
-  },
-
-  cookieJarAccessDenied: async w => {
-    try {
-      w.localStorage.foo = 42;
-      ok(false, "LocalStorage doesn't work");
-    } catch (e) {
-      ok(true, "LocalStorage doesn't work");
-      is(e.name, "TypeError", "We want a security error message.");
-    }
-  },
-});
deleted file mode 100644
--- a/netwerk/cookie/test/browser/file_empty.js
+++ /dev/null
@@ -1,1 +0,0 @@
-/* nothing here */
deleted file mode 100644
--- a/netwerk/cookie/test/browser/head.js
+++ /dev/null
@@ -1,169 +0,0 @@
-const BEHAVIOR_ACCEPT = Ci.nsICookieService.BEHAVIOR_ACCEPT;
-const BEHAVIOR_REJECT = Ci.nsICookieService.BEHAVIOR_REJECT;
-
-const PERM_DEFAULT = Ci.nsICookiePermission.ACCESS_DEFAULT;
-const PERM_ALLOW = Ci.nsICookiePermission.ACCESS_ALLOW;
-const PERM_DENY = Ci.nsICookiePermission.ACCESS_DENY;
-
-const TEST_DOMAIN = "https://example.com/";
-const TEST_PATH = "browser/netwerk/cookie/test/browser/";
-const TEST_TOP_PAGE = TEST_DOMAIN + TEST_PATH + "file_empty.html";
-
-// Helper to eval() provided cookieJarAccessAllowed and cookieJarAccessDenied
-// toString()ed optionally async function in freshly created tabs with
-// BEHAVIOR_ACCEPT and BEHAVIOR_REJECT configured, respectively, in a number of
-// permutations. This includes verifying that changing the permission while the
-// page is open still results in the state of the permission when the
-// document/global was created still applying. Code will execute in the
-// 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.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.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.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.prefs,
-                     {
-                       fromBehavior: BEHAVIOR_ACCEPT,
-                       toBehavior: BEHAVIOR_ACCEPT,
-                       fromPermission: PERM_DENY,
-                       toPermission: PERM_DEFAULT,
-                     });
-  },
-
-  _createTest(testName, goodCb, badCb, prefs, config) {
-    add_task(async _ => {
-      info("Starting " + testName + ": " + config.toSource());
-
-      await SpecialPowers.flushPrefEnv();
-
-      if (prefs) {
-        await SpecialPowers.pushPrefEnv({"set": prefs });
-      }
-
-      let uri = Services.io.newURI(TEST_DOMAIN);
-
-      // Let's set the first cookie pref.
-      Services.perms.add(uri, "cookie", config.fromPermission);
-      await SpecialPowers.pushPrefEnv({"set": [
-        ["network.cookie.cookieBehavior", config.fromBehavior],
-      ]});
-
-      // Let's open a tab and load content.
-      let tab = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE);
-      gBrowser.selectedTab = tab;
-
-      let browser = gBrowser.getBrowserForTab(tab);
-      await BrowserTestUtils.browserLoaded(browser);
-
-      // Let's create an iframe.
-      await ContentTask.spawn(browser, { url: TEST_TOP_PAGE },
-                              async obj => {
-        return new content.Promise(resolve => {
-          let ifr = content.document.createElement('iframe');
-          ifr.setAttribute("id", "iframe");
-          ifr.src = obj.url;
-          ifr.onload = resolve;
-          content.document.body.appendChild(ifr);
-        });
-      });
-
-      // Let's exec the "good" callback.
-      info("Executing the test after setting the cookie behavior to " + config.fromBehavior + " and permission to " + config.fromPermission);
-      await ContentTask.spawn(browser,
-                              { callback: goodCb.toString() },
-                              async obj => {
-        let runnableStr = `(() => {return (${obj.callback});})();`;
-        let runnable = eval(runnableStr); // eslint-disable-line no-eval
-        await runnable(content);
-
-        let ifr = content.document.getElementById("iframe");
-        await runnable(ifr.contentWindow);
-      });
-
-      // Now, let's change the cookie settings
-      Services.perms.add(uri, "cookie", config.toPermission);
-      await SpecialPowers.pushPrefEnv({"set": [
-        ["network.cookie.cookieBehavior", config.toBehavior],
-      ]});
-
-      // We still want the good callback to succeed.
-      info("Executing the test after setting the cookie behavior to " + config.toBehavior + " and permission to " + config.toPermission);
-      await ContentTask.spawn(browser,
-                              { callback: goodCb.toString() },
-                              async obj => {
-        let runnableStr = `(() => {return (${obj.callback});})();`;
-        let runnable = eval(runnableStr); // eslint-disable-line no-eval
-        await runnable(content);
-
-        let ifr = content.document.getElementById("iframe");
-        await runnable(ifr.contentWindow);
-      });
-
-      // Let's close the tab.
-      BrowserTestUtils.removeTab(tab);
-
-      // Let's open a new tab and load content again.
-      tab = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE);
-      gBrowser.selectedTab = tab;
-
-      browser = gBrowser.getBrowserForTab(tab);
-      await BrowserTestUtils.browserLoaded(browser);
-
-      // Let's exec the "bad" callback.
-      info("Executing the test in a new tab");
-      await ContentTask.spawn(browser,
-                              { callback: badCb.toString() },
-                              async obj => {
-        let runnableStr = `(() => {return (${obj.callback});})();`;
-        let runnable = eval(runnableStr); // eslint-disable-line no-eval
-        await runnable(content);
-      });
-
-      // Let's close the tab.
-      BrowserTestUtils.removeTab(tab);
-
-      // Cleanup.
-      await new Promise(resolve => {
-        Services.clearData.deleteData(Ci.nsIClearDataService.CLEAR_ALL, resolve);
-      });
-    });
-  },
-};
deleted file mode 100644
--- a/netwerk/cookie/test/browser/server.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-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");
-  }
-}
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
-  "extends": [
-    "plugin:mozilla/mochitest-test",
-  ]
-};
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/cookie.sjs
+++ /dev/null
@@ -1,124 +0,0 @@
-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");
-}
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/cookiesHelper.js
+++ /dev/null
@@ -1,50 +0,0 @@
-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_ALL, ___ => {
-          // 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();
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/mochitest.ini
+++ /dev/null
@@ -1,13 +0,0 @@
-[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]
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/test_document_cookie.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!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>
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/test_fetch.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!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>
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/test_image.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!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>
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/test_script.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!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>
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/test_sharedWorker.html
+++ /dev/null
@@ -1,50 +0,0 @@
-<!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>
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/test_worker.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!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>
deleted file mode 100644
--- a/netwerk/cookie/test/mochitest/test_xhr.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!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/dns/TRR.cpp
+++ b/netwerk/dns/TRR.cpp
@@ -231,17 +231,16 @@ nsresult TRR::SendHTTPRequest() {
     LOG(("TRR:SendHTTPRequest: NewURI failed!\n"));
     return rv;
   }
 
   rv = NS_NewChannel(
       getter_AddRefs(mChannel), dnsURI, nsContentUtils::GetSystemPrincipal(),
       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
       nsIContentPolicy::TYPE_OTHER,
-      nullptr,  // nsICookieSettings
       nullptr,  // PerformanceStorage
       nullptr,  // aLoadGroup
       this,
       nsIRequest::LOAD_ANONYMOUS | (mPB ? nsIRequest::INHIBIT_CACHING : 0),
       ios);
   if (NS_FAILED(rv)) {
     LOG(("TRR:SendHTTPRequest: NewChannel failed!\n"));
     return rv;
--- a/netwerk/ipc/NeckoChannelParams.ipdlh
+++ b/netwerk/ipc/NeckoChannelParams.ipdlh
@@ -23,34 +23,16 @@ using struct nsHttpAtom from "nsHttp.h";
 using class mozilla::net::nsHttpResponseHead from "nsHttpResponseHead.h";
 using class mozilla::TimeStamp from "mozilla/TimeStamp.h";
 using nsILoadInfo::CrossOriginOpenerPolicy from "ipc/IPCMessageUtils.h";
 
 namespace mozilla {
 namespace net {
 
 //-----------------------------------------------------------------------------
-// CookieSettings IPDL structs
-//-----------------------------------------------------------------------------
-
-struct CookiePermissionData
-{
-  PrincipalInfo principalInfo;
-  uint32_t cookiePermission;
-};
-
-struct CookieSettingsArgs
-{
-  // Copy of the cookie behavior and permissions for the top-level document.
-  uint32_t cookieBehavior;
-  CookiePermissionData[] cookiePermissions;
-  bool isFixed;
-};
-
-//-----------------------------------------------------------------------------
 // Preferrer alternative data type
 //-----------------------------------------------------------------------------
 
 struct PreferredAlternativeDataTypeParams
 {
   nsCString type;
   nsCString contentType;
   bool deliverAltData;
@@ -138,18 +120,16 @@ struct LoadInfoArgs
   bool                        isPreflight;
   bool                        loadTriggeredFromExternal;
   bool                        serviceWorkerTaintingSynthesized;
   bool                        documentHasUserInteracted;
   bool                        documentHasLoaded;
   nsString                    cspNonce;
   bool                        isFromProcessingFrameAttributes;
   CrossOriginOpenerPolicy     openerPolicy;
-
-  CookieSettingsArgs cookieSettings;
 };
 
 /**
  * This structure is used to carry selected properties of a LoadInfo
  * object to child processes to merge LoadInfo changes from the parent
  * process.  We don't want to use LoadInfoArgs for that since it's
  * too huge and we only care about small subpart of properties anyway.
  */
@@ -173,18 +153,16 @@ struct ParentLoadInfoForwarderArgs
   // by the service worker.
   bool serviceWorkerTaintingSynthesized;
 
   bool documentHasUserInteracted;
   bool documentHasLoaded;
 
   CrossOriginOpenerPolicy openerPolicy;
 
-  CookieSettingsArgs? cookieSettings;
-
   // IMPORTANT: when you add new properites here you must also update
   // LoadInfoToParentLoadInfoForwarder and MergeParentLoadInfoForwarder
   // in BackgroundUtils.cpp/.h!
 };
 
 /**
  * This structure is used to carry selected properties of a LoadInfo
  * object to the parent process that might have changed in the child
--- a/netwerk/test/TestCookie.cpp
+++ b/netwerk/test/TestCookie.cpp
@@ -16,17 +16,16 @@
 #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
@@ -76,17 +75,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, bool aAllowed) {
+                        const char *aServerTime) {
   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);
@@ -96,23 +95,16 @@ 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;
@@ -1007,63 +999,35 @@ 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, true);
+                     "unset=yes", nullptr);
   // samesite attribute present but with no value
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "unspecified=yes; samesite", nullptr, true);
+                     "unspecified=yes; samesite", nullptr);
   // samesite attribute present but with an empty value
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "empty=yes; samesite=", nullptr, true);
+                     "empty=yes; samesite=", nullptr);
   // samesite attribute present but with an invalid value
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "bogus=yes; samesite=bogus", nullptr, true);
+                     "bogus=yes; samesite=bogus", nullptr);
   // samesite=strict
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "strict=yes; samesite=strict", nullptr, true);
+                     "strict=yes; samesite=strict", nullptr);
   // samesite=lax
   SetASameSiteCookie(cookieService, "http://samesite.test", nullptr,
-                     "lax=yes; samesite=lax", nullptr, true);
+                     "lax=yes; samesite=lax", nullptr);
 
   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,20 +58,18 @@ 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,18 +50,16 @@ 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,19 +14,16 @@ 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,20 +59,18 @@ 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,20 +110,18 @@ 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,20 +87,18 @@ 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,19 +9,16 @@ 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,7 +1,6 @@
 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,23 +24,21 @@ 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,8 +1,7 @@
 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/antitracking/AntiTrackingCommon.cpp
+++ b/toolkit/components/antitracking/AntiTrackingCommon.cpp
@@ -151,93 +151,82 @@ void CreatePermissionKey(const nsCString
   aPermissionKey.Append(prefix);
   aPermissionKey.Append(aTrackingOrigin);
   aPermissionKey.AppendLiteral("^");
   aPermissionKey.Append(aGrantedOrigin);
 }
 
 // This internal method returns ACCESS_DENY if the access is denied,
 // ACCESS_DEFAULT if unknown, some other access code if granted.
-uint32_t CheckCookiePermissionForPrincipal(nsICookieSettings* aCookieSettings,
-                                           nsIPrincipal* aPrincipal) {
-  MOZ_ASSERT(aCookieSettings);
-  MOZ_ASSERT(aPrincipal);
-
-  uint32_t cookiePermission = nsICookiePermission::ACCESS_DEFAULT;
+nsCookieAccess CheckCookiePermissionForPrincipal(nsIPrincipal* aPrincipal) {
+  nsCookieAccess access = nsICookiePermission::ACCESS_DEFAULT;
   if (!aPrincipal->GetIsCodebasePrincipal()) {
-    return cookiePermission;
+    return access;
   }
 
-  nsresult rv =
-      aCookieSettings->CookiePermission(aPrincipal, &cookiePermission);
+  nsCOMPtr<nsICookiePermission> cps = nsCookiePermission::GetOrCreate();
+
+  nsresult rv = cps->CanAccess(aPrincipal, &access);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return nsICookiePermission::ACCESS_DEFAULT;
   }
 
   // If we have a custom cookie permission, let's use it.
-  return cookiePermission;
+  return access;
 }
 
-int32_t CookiesBehavior(Document* aTopLevelDocument,
-                        Document* a3rdPartyDocument) {
-  MOZ_ASSERT(aTopLevelDocument);
-  MOZ_ASSERT(a3rdPartyDocument);
+// This internal method returns ACCESS_DENY if the access is denied,
+// ACCESS_DEFAULT if unknown, some other access code if granted.
+nsCookieAccess CheckCookiePermissionForURI(nsIURI* aURI) {
+  nsCookieAccess access = nsICookiePermission::ACCESS_DEFAULT;
+
+  nsCOMPtr<nsICookiePermission> cps = nsCookiePermission::GetOrCreate();
 
+  nsresult rv = cps->CanAccessURI(aURI, &access);
+  if (NS_WARN_IF(NS_FAILED(rv))) {
+    return nsICookiePermission::ACCESS_DEFAULT;
+  }
+
+  // If we have a custom cookie permission, let's use it.
+  return access;
+}
+
+int32_t CookiesBehavior(nsIPrincipal* aTopLevelPrincipal,
+                        nsIPrincipal* a3rdPartyPrincipal) {
   // WebExtensions principals always get BEHAVIOR_ACCEPT as cookieBehavior
   // (See Bug 1406675 for rationale).
-  if (BasePrincipal::Cast(aTopLevelDocument->NodePrincipal())->AddonPolicy()) {
+  if (BasePrincipal::Cast(aTopLevelPrincipal)->AddonPolicy()) {
     return nsICookieService::BEHAVIOR_ACCEPT;
   }
 
-  if (BasePrincipal::Cast(a3rdPartyDocument->NodePrincipal())->AddonPolicy()) {
+  if (a3rdPartyPrincipal &&
+      BasePrincipal::Cast(a3rdPartyPrincipal)->AddonPolicy()) {
     return nsICookieService::BEHAVIOR_ACCEPT;
   }
 
-  return a3rdPartyDocument->CookieSettings()->GetCookieBehavior();
+  return StaticPrefs::network_cookie_cookieBehavior();
 }
 
-int32_t CookiesBehavior(nsILoadInfo* aLoadInfo,
-                        nsIPrincipal* aTopLevelPrincipal,
+int32_t CookiesBehavior(nsIPrincipal* aTopLevelPrincipal,
                         nsIURI* a3rdPartyURI) {
-  MOZ_ASSERT(aLoadInfo);
-  MOZ_ASSERT(aTopLevelPrincipal);
-  MOZ_ASSERT(a3rdPartyURI);
-
   // WebExtensions principals always get BEHAVIOR_ACCEPT as cookieBehavior
   // (See Bug 1406675 for rationale).
   if (BasePrincipal::Cast(aTopLevelPrincipal)->AddonPolicy()) {
     return nsICookieService::BEHAVIOR_ACCEPT;
   }
 
   // This is semantically equivalent to the principal having a AddonPolicy().
   bool is3rdPartyMozExt = false;
-  if (NS_SUCCEEDED(
+  if (a3rdPartyURI &&
+      NS_SUCCEEDED(
           a3rdPartyURI->SchemeIs("moz-extension", &is3rdPartyMozExt)) &&
       is3rdPartyMozExt) {
     return nsICookieService::BEHAVIOR_ACCEPT;
   }
 
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  nsresult rv = aLoadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    return nsICookieService::BEHAVIOR_REJECT;
-  }
-
-  return cookieSettings->GetCookieBehavior();
-}
-
-int32_t CookiesBehavior(nsIPrincipal* aPrincipal) {
-  MOZ_ASSERT(aPrincipal);
-
-  // WebExtensions principals always get BEHAVIOR_ACCEPT as cookieBehavior
-  // (See Bug 1406675 for rationale).
-  if (BasePrincipal::Cast(aPrincipal)->AddonPolicy()) {
-    return nsICookieService::BEHAVIOR_ACCEPT;
-  }
-
   return StaticPrefs::network_cookie_cookieBehavior();
 }
 
 struct ContentBlockingAllowListKey {
   ContentBlockingAllowListKey() : mHash(mozilla::HashGeneric(uintptr_t(0))) {}
 
   // Ensure that we compute a different hash for window and channel pointers of
   // the same numeric value, in the off chance that we get unlucky and encounter
@@ -988,51 +977,46 @@ AntiTrackingCommon::SaveFirstPartyStorag
     LOG(
         ("Setting 'any site' permission expiry: %u, proceeding to save in the "
          "permission manager",
          expirationTime));
 
     rv = permManager->AddFromPrincipal(
         aTrackingPrincipal, NS_LITERAL_CSTRING("cookie"),
         nsICookiePermission::ACCESS_ALLOW, expirationType, when);
-    Unused << NS_WARN_IF(NS_FAILED(rv));
-  }
-
-  // We must grant the storage permission also if we allow it for any site
-  // because the setting 'cookie' permission is not applied to existing
-  // documents (See CookieSettings documentation).
+  } else {
+    uint32_t privateBrowsingId = 0;
+    rv = aParentPrincipal->GetPrivateBrowsingId(&privateBrowsingId);
+    if ((!NS_WARN_IF(NS_FAILED(rv)) && privateBrowsingId > 0) ||
+        (aAllowMode == eAllowAutoGrant)) {
+      // If we are coming from a private window or are automatically granting a
+      // permission, make sure to store a session-only permission which won't
+      // get persisted to disk.
+      expirationType = nsIPermissionManager::EXPIRE_SESSION;
+      when = 0;
+    }
 
-  uint32_t privateBrowsingId = 0;
-  rv = aParentPrincipal->GetPrivateBrowsingId(&privateBrowsingId);
-  if ((!NS_WARN_IF(NS_FAILED(rv)) && privateBrowsingId > 0) ||
-      (aAllowMode == eAllowAutoGrant)) {
-    // If we are coming from a private window or are automatically granting a
-    // permission, make sure to store a session-only permission which won't
-    // get persisted to disk.
-    expirationType = nsIPermissionManager::EXPIRE_SESSION;
-    when = 0;
-  }
+    nsAutoCString type;
+    CreatePermissionKey(aTrackingOrigin, aGrantedOrigin, type);
 
-  nsAutoCString type;
-  CreatePermissionKey(aTrackingOrigin, aGrantedOrigin, type);
-
-  LOG(
-      ("Computed permission key: %s, expiry: %u, proceeding to save in the "
-       "permission manager",
-       type.get(), expirationTime));
+    LOG(
+        ("Computed permission key: %s, expiry: %u, proceeding to save in the "
+         "permission manager",
+         type.get(), expirationTime));
 
-  rv = permManager->AddFromPrincipal(aParentPrincipal, type,
-                                     nsIPermissionManager::ALLOW_ACTION,
-                                     expirationType, when);
-  Unused << NS_WARN_IF(NS_FAILED(rv));
+    rv = permManager->AddFromPrincipal(aParentPrincipal, type,
+                                       nsIPermissionManager::ALLOW_ACTION,
+                                       expirationType, when);
 
-  if (NS_SUCCEEDED(rv) && (aAllowMode == eAllowAutoGrant)) {
-    // Make sure temporary access grants do not survive more than 24 hours.
-    TemporaryAccessGrantObserver::Create(permManager, aParentPrincipal, type);
+    if (NS_SUCCEEDED(rv) && (aAllowMode == eAllowAutoGrant)) {
+      // Make sure temporary access grants do not survive more than 24 hours.
+      TemporaryAccessGrantObserver::Create(permManager, aParentPrincipal, type);
+    }
   }
+  Unused << NS_WARN_IF(NS_FAILED(rv));
 
   LOG(("Result: %s", NS_SUCCEEDED(rv) ? "success" : "failure"));
   return FirstPartyStorageAccessGrantPromise::CreateAndResolve(rv, __func__);
 }
 
 // static
 bool AntiTrackingCommon::IsStorageAccessPermission(nsIPermission* aPermission,
                                                    nsIPrincipal* aPrincipal) {
@@ -1077,87 +1061,66 @@ bool AntiTrackingCommon::IsFirstPartySto
   if (!aRejectedReason) {
     aRejectedReason = &rejectedReason;
   }
 
   LOG_SPEC(("Computing whether window %p has access to URI %s", aWindow, _spec),
            aURI);
 
   nsGlobalWindowInner* innerWindow = nsGlobalWindowInner::Cast(aWindow);
-  Document* document = innerWindow->GetExtantDoc();
-  if (!document) {
-    LOG(("Our window has no document"));
-    return false;
-  }
-
-  nsGlobalWindowOuter* outerWindow =
-      nsGlobalWindowOuter::Cast(aWindow->GetOuterWindow());
-  if (!outerWindow) {
-    LOG(("Our window has no outer window"));
-    return false;
-  }
-
-  nsCOMPtr<nsPIDOMWindowOuter> topOuterWindow = outerWindow->GetTop();
-  nsGlobalWindowOuter* topWindow = nsGlobalWindowOuter::Cast(topOuterWindow);
-  if (NS_WARN_IF(!topWindow)) {
-    LOG(("No top outer window"));
+  nsIPrincipal* windowPrincipal = innerWindow->GetPrincipal();
+  if (!windowPrincipal) {
+    LOG(("Our window has no principal"));
     return false;
   }
 
-  nsPIDOMWindowInner* topInnerWindow = topWindow->GetCurrentInnerWindow();
-  if (NS_WARN_IF(!topInnerWindow)) {
-    LOG(("No top inner window."));
-    return false;
+  nsIPrincipal* toplevelPrincipal = innerWindow->GetTopLevelPrincipal();
+  if (!toplevelPrincipal) {
+    // We are already the top-level principal. Let's use the window's principal.
+    LOG(
+        ("Our inner window lacks a top-level principal, use the window's "
+         "principal instead"));
+    toplevelPrincipal = windowPrincipal;
   }
 
-  Document* toplevelDocument = topInnerWindow->GetExtantDoc();
-  if (!toplevelDocument) {
-    LOG(("No top level document."));
-    return false;
-  }
+  MOZ_ASSERT(toplevelPrincipal);
 
-  MOZ_ASSERT(toplevelDocument);
-
-  uint32_t cookiePermission = CheckCookiePermissionForPrincipal(
-      toplevelDocument->CookieSettings(), toplevelDocument->NodePrincipal());
-  if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  nsCookieAccess access = CheckCookiePermissionForPrincipal(toplevelPrincipal);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
         ("CheckCookiePermissionForPrincipal() returned a non-default access "
          "code (%d) for top-level window's principal, returning %s",
-         int(cookiePermission),
-         cookiePermission != nsICookiePermission::ACCESS_DENY ? "success"
-                                                              : "failure"));
-    if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
+         int(access),
+         access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
+    if (access != nsICookiePermission::ACCESS_DENY) {
       return true;
     }
 
     *aRejectedReason =
         nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;
     return false;
   }
 
-  cookiePermission = CheckCookiePermissionForPrincipal(
-      toplevelDocument->CookieSettings(), document->NodePrincipal());
-  if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  access = CheckCookiePermissionForPrincipal(windowPrincipal);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
         ("CheckCookiePermissionForPrincipal() returned a non-default access "
          "code (%d) for window's principal, returning %s",
-         int(cookiePermission),
-         cookiePermission != nsICookiePermission::ACCESS_DENY ? "success"
-                                                              : "failure"));
-    if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
+         int(access),
+         access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
+    if (access != nsICookiePermission::ACCESS_DENY) {
       return true;
     }
 
     *aRejectedReason =
         nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;
     return false;
   }
 
-  int32_t behavior = CookiesBehavior(toplevelDocument, document);
+  int32_t behavior = CookiesBehavior(toplevelPrincipal, windowPrincipal);
   if (behavior == nsICookieService::BEHAVIOR_ACCEPT) {
     LOG(("The cookie behavior pref mandates accepting all cookies!"));
     return true;
   }
 
   if (CheckContentBlockingAllowList(aWindow)) {
     return true;
   }
@@ -1226,32 +1189,53 @@ bool AntiTrackingCommon::IsFirstPartySto
 
   nsAutoCString grantedOrigin;
   nsresult rv = nsContentUtils::GetASCIIOrigin(aURI, grantedOrigin);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     LOG_SPEC(("Failed to compute the origin from %s", _spec), aURI);
     return false;
   }
 
+  nsGlobalWindowOuter* outerWindow =
+      nsGlobalWindowOuter::Cast(aWindow->GetOuterWindow());
+  if (NS_WARN_IF(!outerWindow)) {
+    LOG(("No outer window."));
+    return false;
+  }
+
+  nsCOMPtr<nsPIDOMWindowOuter> topOuterWindow = outerWindow->GetTop();
+  nsGlobalWindowOuter* topWindow = nsGlobalWindowOuter::Cast(topOuterWindow);
+  if (NS_WARN_IF(!topWindow)) {
+    LOG(("No top outer window."));
+    return false;
+  }
+
+  nsPIDOMWindowInner* topInnerWindow = topWindow->GetCurrentInnerWindow();
+  if (NS_WARN_IF(!topInnerWindow)) {
+    LOG(("No top inner window."));
+    return false;
+  }
+
   nsAutoCString type;
   CreatePermissionKey(trackingOrigin, grantedOrigin, type);
 
   if (topInnerWindow->HasStorageAccessGranted(type)) {
     LOG(("Permission stored in the window. All good."));
     return true;
   }
 
   nsPermissionManager* permManager = nsPermissionManager::GetInstance();
   if (NS_WARN_IF(!permManager)) {
     LOG(("Failed to obtain the permission manager"));
     return false;
   }
 
   uint32_t result = 0;
-  rv = permManager->TestPermissionFromPrincipal(parentPrincipal, type, &result);
+  rv = permManager->TestPermissionWithoutDefaultsFromPrincipal(parentPrincipal,
+                                                               type, &result);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     LOG(("Failed to test the permission"));
     return false;
   }
 
   LOG_SPEC(
       ("Testing permission type %s for %s resulted in %d (%s)", type.get(),
        _spec, int(result),
@@ -1272,20 +1256,16 @@ bool AntiTrackingCommon::IsFirstPartySto
   MOZ_ASSERT(aChannel);
 
   // Let's avoid a null check on aRejectedReason everywhere else.
   uint32_t rejectedReason = 0;
   if (!aRejectedReason) {
     aRejectedReason = &rejectedReason;
   }
 
-  nsIScriptSecurityManager* ssm =
-      nsScriptSecurityManager::GetScriptSecurityManager();
-  MOZ_ASSERT(ssm);
-
   nsCOMPtr<nsIURI> channelURI;
   nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
   if (NS_FAILED(rv)) {
     LOG(("Failed to get the channel final URI, bail out early"));
     return true;
   }
   LOG_SPEC(
       ("Computing whether channel %p has access to URI %s", aChannel, _spec),
@@ -1311,16 +1291,18 @@ bool AntiTrackingCommon::IsFirstPartySto
   if (!toplevelPrincipal) {
     LOG(
         ("We don't have a loading principal, let's see if this is a document "
          "channel"
          " that belongs to a top-level window"));
     bool isDocument = false;
     rv = aChannel->GetIsMainDocumentChannel(&isDocument);
     if (NS_SUCCEEDED(rv) && isDocument) {
+      nsIScriptSecurityManager* ssm =
+          nsScriptSecurityManager::GetScriptSecurityManager();
       rv = ssm->GetChannelResultPrincipal(aChannel,
                                           getter_AddRefs(toplevelPrincipal));
       if (NS_SUCCEEDED(rv)) {
         LOG(("Yes, we guessed right!"));
       } else {
         LOG(
             ("Yes, we guessed right, but minting the channel result principal "
              "failed"));
@@ -1338,75 +1320,54 @@ bool AntiTrackingCommon::IsFirstPartySto
     toplevelPrincipal = loadInfo->TriggeringPrincipal();
   }
 
   if (NS_WARN_IF(!toplevelPrincipal)) {
     LOG(("No top-level principal! Bail out early"));
     return false;
   }
 
-  nsCOMPtr<nsICookieSettings> cookieSettings;
-  rv = loadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    LOG(
-        ("Failed to get the cookie settings from the loadinfo, bail out "
-         "early"));
-    return true;
-  }
-
-  uint32_t cookiePermission =
-      CheckCookiePermissionForPrincipal(cookieSettings, toplevelPrincipal);
-  if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  nsCookieAccess access = CheckCookiePermissionForPrincipal(toplevelPrincipal);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
         ("CheckCookiePermissionForPrincipal() returned a non-default access "
          "code (%d) for top-level window's principal, returning %s",
-         int(cookiePermission),
-         cookiePermission != nsICookiePermission::ACCESS_DENY ? "success"
-                                                              : "failure"));
-    if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
+         int(access),
+         access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
+    if (access != nsICookiePermission::ACCESS_DENY) {
       return true;
     }
 
     *aRejectedReason =
         nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;
     return false;
   }
 
-  nsCOMPtr<nsIPrincipal> channelPrincipal;
-  rv = ssm->GetChannelResultPrincipal(aChannel,
-                                      getter_AddRefs(channelPrincipal));
-  if (NS_WARN_IF(NS_FAILED(rv))) {
+  if (NS_WARN_IF(NS_FAILED(rv) || !channelURI)) {
     LOG(("No channel principal, bail out early"));
     return false;
   }
 
-  cookiePermission =
-      CheckCookiePermissionForPrincipal(cookieSettings, channelPrincipal);
-  if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  access = CheckCookiePermissionForURI(channelURI);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
         ("CheckCookiePermissionForPrincipal() returned a non-default access "
          "code (%d) for channel's principal, returning %s",
-         int(cookiePermission),
-         cookiePermission != nsICookiePermission::ACCESS_DENY ? "success"
-                                                              : "failure"));
-    if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
+         int(access),
+         access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
+    if (access != nsICookiePermission::ACCESS_DENY) {
       return true;
     }
 
     *aRejectedReason =
         nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;