Backed out 11 changesets (bug 1525245) for failing at test_cookies_thirdparty.js on a CLOSED TREE.
authorGurzau Raul <rgurzau@mozilla.com>
Tue, 26 Feb 2019 22:09:25 +0200
changeset 519097 bc51c190590a057206eb960e3eca6ac7461c36a3
parent 519096 da6f15f3a5232c102dda02f3efb13c1f64ceb894
child 519098 ff3a260bd20df53104c0c419bf7c37d4689fbd66
push id10862
push userffxbld-merge
push dateMon, 11 Mar 2019 13:01:11 +0000
treeherdermozilla-beta@a2e7f5c935da [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs1525245
milestone67.0a1
backs out1dcb31a1d5be037dd32d9f9f46ccc79b7329f741
4cde0e38ada8218b273caa8ea90eae0307f9a589
d3e99dd3fc32b95a1f82dcca9d62566f220b4378
a565014fdd8dadda3e6f4280646b9c6c9b1841eb
20f336320ce183a102a8fc02f656425006022b5b
d8ee13b6a17d3cbfa50e721089ebd5e2360594bd
b79ec111bf41921912f9ab73091cbe093c7dd371
858d08371107c0d06f02e57acc65f6edb8b85803
1c359cdcf69f276b4a58de7b8c11a07f7e4e8b9c
d65fb2d2a243d183ee084b84b1d898573dbf04dc
28147c8790d3063656e4b1871e22ec10ab28b4d1
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 11 changesets (bug 1525245) for failing at test_cookies_thirdparty.js on a CLOSED TREE. Backed out changeset 1dcb31a1d5be (bug 1525245) Backed out changeset 4cde0e38ada8 (bug 1525245) Backed out changeset d3e99dd3fc32 (bug 1525245) Backed out changeset a565014fdd8d (bug 1525245) Backed out changeset 20f336320ce1 (bug 1525245) Backed out changeset d8ee13b6a17d (bug 1525245) Backed out changeset b79ec111bf41 (bug 1525245) Backed out changeset 858d08371107 (bug 1525245) Backed out changeset 1c359cdcf69f (bug 1525245) Backed out changeset d65fb2d2a243 (bug 1525245) Backed out changeset 28147c8790d3 (bug 1525245)
dom/base/Document.cpp
dom/base/Document.h
dom/base/nsContentUtils.cpp
dom/base/nsContentUtils.h
dom/base/nsGlobalWindowInner.cpp
dom/base/nsGlobalWindowOuter.cpp
dom/broadcastchannel/BroadcastChannel.cpp
dom/indexedDB/test/mochitest.ini
dom/indexedDB/test/test_third_party.html
dom/indexedDB/test/third_party_window.html
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/workers/RuntimeService.cpp
dom/workers/test/mochitest.ini
dom/workers/test/sharedWorker_thirdparty_window.html
dom/workers/test/test_sharedWorker_thirdparty.html
ipc/glue/BackgroundUtils.cpp
netwerk/base/LoadInfo.cpp
netwerk/base/LoadInfo.h
netwerk/base/nsILoadInfo.idl
netwerk/cookie/CookieSettings.cpp
netwerk/cookie/CookieSettings.h
netwerk/cookie/moz.build
netwerk/cookie/nsICookieSettings.idl
netwerk/cookie/test/browser/browser.ini
netwerk/cookie/test/browser/browser_broadcastChannel.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/ipc/NeckoChannelParams.ipdlh
toolkit/components/antitracking/AntiTrackingCommon.cpp
toolkit/components/antitracking/test/browser/browser_storageAccessWithHeuristics.js
--- 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"
@@ -2567,28 +2565,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);
 
@@ -11808,17 +11794,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.
 
@@ -12324,18 +12310,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();
@@ -12377,17 +12363,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
@@ -12635,20 +12621,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
@@ -1501,19 +1500,16 @@ class Document : public nsINode,
   // cached value and if the document generation hasn't
   // changed since the cache was created.
   // Returns true if sizes were added.
   bool GetCachedSizes(nsTabSizes* aSizes);
 
   // Sets the cache sizes for the current generation.
   void SetCachedSizes(nsTabSizes* aSizes);
 
-  // Returns the cookie settings for this and sub contexts.
-  nsICookieSettings* CookieSettings();
-
  protected:
   friend class nsUnblockOnloadEvent;
 
   nsresult InitCSP(nsIChannel* aChannel);
 
   nsresult InitFeaturePolicy(nsIChannel* aChannel);
 
   void PostUnblockOnloadEvent();
@@ -4662,18 +4658,16 @@ class Document : public nsINode,
 
   // Document generation. Gets incremented everytime it changes.
   int32_t mGeneration;
 
   // Cached TabSizes values for the document.
   int32_t mCachedTabSizeGeneration;
   nsTabSizes mCachedTabSizes;
 
-  nsCOMPtr<nsICookieSettings> mCookieSettings;
-
  public:
   // Needs to be public because the bindings code pokes at it.
   js::ExpandoAndGeneration mExpandoAndGeneration;
 
   bool HasPendingInitialTranslation() { return mPendingInitialTranslation; }
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -8224,40 +8224,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,
@@ -8418,17 +8419,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) {
@@ -8437,38 +8437,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
@@ -3380,24 +3380,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
@@ -4344,58 +4344,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
@@ -1259,16 +1259,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();
 
@@ -2315,28 +2319,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;
@@ -6964,16 +6970,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;
     }
@@ -6995,16 +7006,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) {
@@ -7791,16 +7806,20 @@ mozilla::dom::TabGroup* nsPIDOMWindowOut
   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/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); }
@@ -236,33 +242,32 @@ JSObject* BroadcastChannel::WrapObject(J
     }
 
     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(); });
@@ -270,25 +275,26 @@ JSObject* BroadcastChannel::WrapObject(J
     // 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/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/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,43 +24,47 @@ 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
@@ -143,12 +143,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/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -2012,20 +2012,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();
   }
 }
@@ -2396,20 +2394,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/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/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"
@@ -456,24 +455,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 = LoadInfoArgs(
       loadingPrincipalInfo, triggeringPrincipalInfo, principalToInheritInfo,
       sandboxedLoadingPrincipalInfo, topLevelPrincipalInfo,
       topLevelStorageAreaPrincipalInfo, optionalResultPrincipalURI,
       aLoadInfo->GetSecurityFlags(), aLoadInfo->InternalContentPolicyType(),
       static_cast<uint32_t>(aLoadInfo->GetTainting()),
       aLoadInfo->GetUpgradeInsecureRequests(),
       aLoadInfo->GetBrowserUpgradeInsecureRequests(),
@@ -494,17 +485,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 OptionalLoadInfoArgs& aOptionalLoadInfoArgs,
     nsILoadInfo** outLoadInfo) {
   if (aOptionalLoadInfoArgs.type() == OptionalLoadInfoArgs::Tvoid_t) {
@@ -623,25 +614,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(),
@@ -674,49 +661,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, void_t());
+        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();
 
-  OptionalCookieSettingsArgs 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 = args;
-  } else {
-    cookieSettingsArgs = void_t();
-  }
-
   *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;
   }
 
@@ -743,29 +718,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 OptionalCookieSettingsArgs& cookieSettingsArgs =
-      aForwarderArgs.cookieSettings();
-  if (cookieSettingsArgs.type() != OptionalCookieSettingsArgs::Tvoid_t) {
-    const CookieSettingsArgs& args =
-        cookieSettingsArgs.get_CookieSettingsArgs();
-
-    nsCOMPtr<nsICookieSettings> cookieSettings;
-    nsresult rv = aLoadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
-    if (NS_SUCCEEDED(rv) && cookieSettings) {
-      static_cast<CookieSettings*>(cookieSettings.get())->Merge(args);
-    }
-  }
-
   return NS_OK;
 }
 
 void LoadInfoToChildLoadInfoForwarder(
     nsILoadInfo* aLoadInfo, ChildLoadInfoForwarderArgs* aForwarderArgsOut) {
   if (!aLoadInfo) {
     *aForwarderArgsOut =
         ChildLoadInfoForwarderArgs(void_t(), void_t(), void_t());
--- a/netwerk/base/LoadInfo.cpp
+++ b/netwerk/base/LoadInfo.cpp
@@ -8,26 +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 "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"
@@ -203,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());
@@ -428,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),
@@ -502,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,
@@ -534,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),
@@ -780,27 +766,16 @@ LoadInfo::GetCookiePolicy(uint32_t* aRes
                  ? nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
                  : nsILoadInfo::SEC_COOKIES_INCLUDE;
   }
 
   *aResult = policy;
   return NS_OK;
 }
 
-NS_IMETHODIMP
-LoadInfo::GetCookieSettings(nsICookieSettings** aCookieSettings) {
-  if (!mCookieSettings) {
-    mCookieSettings = CookieSettings::CreateBlockingAll();
-  }
-
-  nsCOMPtr<nsICookieSettings> cookieSettings = mCookieSettings;
-  cookieSettings.forget(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/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.
-   */
-  readonly 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.
deleted file mode 100644
--- a/netwerk/cookie/CookieSettings.cpp
+++ /dev/null
@@ -1,206 +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;
-  }
-};
-
-}  // namespace
-
-// static
-already_AddRefed<nsICookieSettings> CookieSettings::CreateBlockingAll() {
-  RefPtr<CookieSettings> cookieSettings =
-      new CookieSettings(nsICookieService::BEHAVIOR_REJECT, eFixed);
-  return cookieSettings.forget();
-}
-
-// static
-already_AddRefed<nsICookieSettings> CookieSettings::Create() {
-  RefPtr<CookieSettings> cookieSettings = new CookieSettings(
-      StaticPrefs::network_cookie_cookieBehavior(), eProgressive);
-  return cookieSettings.forget();
-}
-
-CookieSettings::CookieSettings(uint32_t aCookieBehavior, State aState)
-    : mCookieBehavior(aCookieBehavior), mState(aState) {}
-
-CookieSettings::~CookieSettings() = default;
-
-NS_IMETHODIMP
-CookieSettings::GetCookieBehavior(uint32_t* aCookieBehavior) {
-  *aCookieBehavior = mCookieBehavior;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-CookieSettings::CookiePermission(nsIPrincipal* aPrincipal,
-                                 uint32_t* aCookiePermission) {
-  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) {
-  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) {
-  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(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,63 +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;
-
-/**
- * Class that provides an nsICookieSettings implementation.
- */
-class CookieSettings final : public nsICookieSettings {
- public:
-  typedef nsTArray<RefPtr<nsIPermission>> CookiePermissionList;
-
-  NS_DECL_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/moz.build
+++ b/netwerk/cookie/moz.build
@@ -9,40 +9,36 @@ 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 += [
-        '/extensions/cookie',
         '/intl/uconv',
     ]
 
     XPCSHELL_TESTS_MANIFESTS += [
         'test/unit/xpcshell.ini',
     ]
 
     BROWSER_CHROME_MANIFESTS += [
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,13 +1,5 @@
 [DEFAULT]
 support-files =
   file_empty.html
-  file_empty.js
-  head.js
 
-[browser_broadcastChannel.js]
-[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_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, "SecurityError", "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,173 +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.cleanup,
-                     config.prefs,
-                     {
-                       fromBehavior: BEHAVIOR_ACCEPT,
-                       toBehavior: BEHAVIOR_REJECT,
-                       fromPermission: PERM_DEFAULT,
-                       toPermission: PERM_DEFAULT,
-                     });
-
-    // Testing blocked to allowed by cookie behavior
-    this._createTest(testName,
-                     config.cookieJarAccessDenied,
-                     config.cookieJarAccessAllowed,
-                     config.cleanup,
-                     config.prefs,
-                     {
-                       fromBehavior: BEHAVIOR_REJECT,
-                       toBehavior: BEHAVIOR_ACCEPT,
-                       fromPermission: PERM_DEFAULT,
-                       toPermission: PERM_DEFAULT,
-                     });
-
-    // Testing allowed to blocked by cookie permission
-    this._createTest(testName,
-                     config.cookieJarAccessAllowed,
-                     config.cookieJarAccessDenied,
-                     config.cleanup,
-                     config.prefs,
-                     {
-                       fromBehavior: BEHAVIOR_REJECT,
-                       toBehavior: BEHAVIOR_REJECT,
-                       fromPermission: PERM_ALLOW,
-                       toPermission: PERM_DEFAULT,
-                     });
-
-    // Testing blocked to allowed by cookie permission
-    this._createTest(testName,
-                     config.cookieJarAccessDenied,
-                     config.cookieJarAccessAllowed,
-                     config.cleanup,
-                     config.prefs,
-                     {
-                       fromBehavior: BEHAVIOR_ACCEPT,
-                       toBehavior: BEHAVIOR_ACCEPT,
-                       fromPermission: PERM_DENY,
-                       toPermission: PERM_DEFAULT,
-                     });
-  },
-
-  _createTest(testName, goodCb, badCb, cleanupCb, prefs, config) {
-    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);
-      });
-    });
-  },
-};
--- a/netwerk/ipc/NeckoChannelParams.ipdlh
+++ b/netwerk/ipc/NeckoChannelParams.ipdlh
@@ -23,40 +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;
-};
-
-union OptionalCookieSettingsArgs
-{
-  void_t;
-  CookieSettingsArgs;
-};
-
-//-----------------------------------------------------------------------------
 // Preferrer alternative data type
 //-----------------------------------------------------------------------------
 
 struct PreferredAlternativeDataTypeParams
 {
   nsCString type;
   nsCString contentType;
   bool deliverAltData;
@@ -144,18 +120,16 @@ struct LoadInfoArgs
   bool                        isPreflight;
   bool                        loadTriggeredFromExternal;
   bool                        serviceWorkerTaintingSynthesized;
   bool                        documentHasUserInteracted;
   bool                        documentHasLoaded;
   nsString                    cspNonce;
   bool                        isFromProcessingFrameAttributes;
   CrossOriginOpenerPolicy     openerPolicy;
-
-  CookieSettingsArgs cookieSettings;
 };
 
 /**
  * Not every channel necessarily has a loadInfo attached.
  */
 union OptionalLoadInfoArgs
 {
   void_t;
@@ -188,18 +162,16 @@ struct ParentLoadInfoForwarderArgs
   // by the service worker.
   bool serviceWorkerTaintingSynthesized;
 
   bool documentHasUserInteracted;
   bool documentHasLoaded;
 
   CrossOriginOpenerPolicy openerPolicy;
 
-  OptionalCookieSettingsArgs 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/toolkit/components/antitracking/AntiTrackingCommon.cpp
+++ b/toolkit/components/antitracking/AntiTrackingCommon.cpp
@@ -149,73 +149,84 @@ void CreatePermissionKey(const nsCString
   aPermissionKey.SetCapacity(prefix.Length() + 1 + aTrackingOrigin.Length() +
                              aGrantedOrigin.Length());
   aPermissionKey.Append(prefix);
   aPermissionKey.Append(aTrackingOrigin);
   aPermissionKey.AppendLiteral("^");
   aPermissionKey.Append(aGrantedOrigin);
 }
 
-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 CheckCookiePermissionForPrincipal(nsIPrincipal* aPrincipal) {
+  nsCookieAccess access = nsICookiePermission::ACCESS_DEFAULT;
+  if (!aPrincipal->GetIsCodebasePrincipal()) {
+    return access;
+  }
+
+  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 access;
+}
 
+// 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
@@ -1050,88 +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;
-  }
-
-  Document* toplevelDocument = topInnerWindow->GetExtantDoc();
-  if (!toplevelDocument) {
-    LOG(("No top level document."));
-    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;
   }
 
-  MOZ_ASSERT(toplevelDocument);
+  MOZ_ASSERT(toplevelPrincipal);
 
-  uint32_t cookiePermission = nsICookiePermission::ACCESS_DEFAULT;
-  if (NS_SUCCEEDED(toplevelDocument->CookieSettings()->CookiePermission(
-          toplevelDocument->NodePrincipal(), &cookiePermission)) &&
-      cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  nsCookieAccess access = CheckCookiePermissionForPrincipal(toplevelPrincipal);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
-        ("Top level document returned a non-default access code (%d), "
-         "returning %s",
-         int(cookiePermission),
-         cookiePermission != nsICookiePermission::ACCESS_DENY ? "success"
-                                                              : "failure"));
-    if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
+        ("CheckCookiePermissionForPrincipal() returned a non-default access "
+         "code (%d) for top-level window's principal, returning %s",
+         int(access),
+         access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
+    if (access != nsICookiePermission::ACCESS_DENY) {
       return true;
     }
 
     *aRejectedReason =
         nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;
     return false;
   }
 
-  if (NS_SUCCEEDED(document->CookieSettings()->CookiePermission(
-          document->NodePrincipal(), &cookiePermission)) &&
-      cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  access = CheckCookiePermissionForPrincipal(windowPrincipal);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
-        ("The document 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) {
+        ("CheckCookiePermissionForPrincipal() returned a non-default access "
+         "code (%d) for window's principal, returning %s",
+         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;
   }
@@ -1200,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),
@@ -1246,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),
@@ -1285,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"));
@@ -1312,84 +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))) {
+  nsCookieAccess access = CheckCookiePermissionForPrincipal(toplevelPrincipal);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
-        ("Failed to get the cookie settings from the loadinfo, bail out "
-         "early"));
-    return true;
-  }
-
-  uint32_t cookiePermission = nsICookiePermission::ACCESS_DEFAULT;
-  rv = cookieSettings->CookiePermission(toplevelPrincipal, &cookiePermission);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    LOG(("CookiePermission() failed for top-level principal, bail out early"));
-    return false;
-  }
-
-  if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
-    LOG(
-        ("nsILoadInfo 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) {
+        ("CheckCookiePermissionForPrincipal() returned a non-default access "
+         "code (%d) for top-level window's principal, returning %s",
+         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;
   }
 
-  rv = cookieSettings->CookiePermission(channelPrincipal, &cookiePermission);
-  if (NS_WARN_IF(NS_FAILED(rv))) {
-    LOG(("CookiePermission() failed for channel principal, bail out early"));
-    return false;
-  }
-
-  if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  access = CheckCookiePermissionForURI(channelURI);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
-        ("loadInfo->CookiePermission() 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) {
+        ("CheckCookiePermissionForPrincipal() returned a non-default access "
+         "code (%d) for channel's principal, returning %s",
+         int(access),
+         access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
+    if (access != nsICookiePermission::ACCESS_DENY) {
       return true;
     }
 
     *aRejectedReason =
         nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION;
     return false;
   }
 
-  if (!channelURI) {
-    LOG(("No channel uri, bail out early"));
-    return false;
-  }
-
-  int32_t behavior = CookiesBehavior(loadInfo, toplevelPrincipal, channelURI);
+  int32_t behavior = CookiesBehavior(toplevelPrincipal, channelURI);
   if (behavior == nsICookieService::BEHAVIOR_ACCEPT) {
     LOG(("The cookie behavior pref mandates accepting all cookies!"));
     return true;
   }
 
   if (CheckContentBlockingAllowList(aChannel)) {
     return true;
   }
@@ -1514,75 +1492,68 @@ bool AntiTrackingCommon::IsFirstPartySto
 
   return true;
 }
 
 bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
     nsIPrincipal* aPrincipal) {
   MOZ_ASSERT(aPrincipal);
 
-  nsCookieAccess access = nsICookiePermission::ACCESS_DEFAULT;
-  if (aPrincipal->GetIsCodebasePrincipal()) {
-    nsCOMPtr<nsICookiePermission> cps = nsCookiePermission::GetOrCreate();
-    Unused << NS_WARN_IF(NS_FAILED(cps->CanAccess(aPrincipal, &access)));
-  }
-
+  nsCookieAccess access = CheckCookiePermissionForPrincipal(aPrincipal);
   if (access != nsICookiePermission::ACCESS_DEFAULT) {
     return access != nsICookiePermission::ACCESS_DENY;
   }
 
-  int32_t behavior = CookiesBehavior(aPrincipal);
+  int32_t behavior =
+      CookiesBehavior(aPrincipal, static_cast<nsIPrincipal*>(nullptr));
   return behavior != nsICookieService::BEHAVIOR_REJECT;
 }
 
 /* static */ bool AntiTrackingCommon::MaybeIsFirstPartyStorageAccessGrantedFor(
     nsPIDOMWindowInner* aFirstPartyWindow, nsIURI* aURI) {
   MOZ_ASSERT(aFirstPartyWindow);
   MOZ_ASSERT(aURI);
 
   LOG_SPEC(
       ("Computing a best guess as to whether window %p has access to URI %s",
        aFirstPartyWindow, _spec),
       aURI);
 
-  Document* parentDocument =
-      nsGlobalWindowInner::Cast(aFirstPartyWindow)->GetExtantDoc();
-  if (NS_WARN_IF(!parentDocument)) {
-    LOG(("Failed to get the first party window's document"));
-    return false;
-  }
-
-  if (parentDocument->CookieSettings()->GetCookieBehavior() !=
+  if (StaticPrefs::network_cookie_cookieBehavior() !=
       nsICookieService::BEHAVIOR_REJECT_TRACKER) {
     LOG(("Disabled by the pref (%d), bail out early",
          StaticPrefs::network_cookie_cookieBehavior()));
     return true;
   }
 
   if (CheckContentBlockingAllowList(aFirstPartyWindow)) {
     return true;
   }
 
   if (!nsContentUtils::IsThirdPartyWindowOrChannel(aFirstPartyWindow, nullptr,
                                                    aURI)) {
     LOG(("Our window isn't a third-party window"));
     return true;
   }
 
-  uint32_t cookiePermission = nsICookiePermission::ACCESS_DEFAULT;
-  if (NS_SUCCEEDED(parentDocument->CookieSettings()->CookiePermission(
-          parentDocument->NodePrincipal(), &cookiePermission)) &&
-      cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
+  nsCOMPtr<nsIPrincipal> parentPrincipal =
+      nsGlobalWindowInner::Cast(aFirstPartyWindow)->GetPrincipal();
+  if (NS_WARN_IF(!parentPrincipal)) {
+    LOG(("Failed to get the first party window's principal"));
+    return false;
+  }
+
+  nsCookieAccess access = CheckCookiePermissionForPrincipal(parentPrincipal);
+  if (access != nsICookiePermission::ACCESS_DEFAULT) {
     LOG(
-        ("Parent window's document returned a non-default access code (%d), "
-         "returning %s",
-         int(cookiePermission),
-         cookiePermission != nsICookiePermission::ACCESS_DENY ? "success"
-                                                              : "failure"));
-    return cookiePermission != nsICookiePermission::ACCESS_DENY;
+        ("CheckCookiePermissionForPrincipal() returned a non-default access "
+         "code (%d), returning %s",
+         int(access),
+         access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
+    return access != nsICookiePermission::ACCESS_DENY;
   }
 
   nsAutoCString origin;
   nsresult rv = nsContentUtils::GetASCIIOrigin(aURI, origin);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     LOG_SPEC(("Failed to compute the origin from %s", _spec), aURI);
     return false;
   }
@@ -1592,27 +1563,26 @@ bool AntiTrackingCommon::IsFirstPartySto
 
   nsPermissionManager* permManager = nsPermissionManager::GetInstance();
   if (NS_WARN_IF(!permManager)) {
     LOG(("Failed to obtain the permission manager"));
     return false;
   }
 
   uint32_t result = 0;
-  rv = permManager->TestPermissionWithoutDefaultsFromPrincipal(
-      parentDocument->NodePrincipal(), type, &result);
+  rv = permManager->TestPermissionWithoutDefaultsFromPrincipal(parentPrincipal,
+                                                               type, &result);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     LOG(("Failed to test the permission"));
     return false;
   }
 
   if (MOZ_LOG_TEST(gAntiTrackingLog, LogLevel::Debug)) {
     nsCOMPtr<nsIURI> parentPrincipalURI;
-    Unused << parentDocument->NodePrincipal()->GetURI(
-        getter_AddRefs(parentPrincipalURI));
+    Unused << parentPrincipal->GetURI(getter_AddRefs(parentPrincipalURI));
     LOG_SPEC(
         ("Testing permission type %s for %s resulted in %d (%s)", type.get(),
          _spec, int(result),
          result == nsIPermissionManager::ALLOW_ACTION ? "success" : "failure"),
         parentPrincipalURI);
   }
 
   return result == nsIPermissionManager::ALLOW_ACTION;
--- a/toolkit/components/antitracking/test/browser/browser_storageAccessWithHeuristics.js
+++ b/toolkit/components/antitracking/test/browser/browser_storageAccessWithHeuristics.js
@@ -262,16 +262,53 @@ add_task(async function testUserInteract
         }
 
         ok(false, "Unknown message");
       });
       ifr.contentWindow.postMessage({ callback: msg.nonBlockingCallback }, "*");
     });
   });
 
+  info("Now ensure that the storage access is removed if the cookie policy is changed.");
+  await SpecialPowers.pushPrefEnv({"set": [
+    ["network.cookie.cookieBehavior", Ci.nsICookieService.BEHAVIOR_REJECT],
+  ]});
+  await ContentTask.spawn(browser, {}, async obj => {
+    await new content.Promise(resolve => {
+      let ifr = content.document.querySelectorAll("iframe");
+      ifr = ifr[ifr.length - 1];
+
+      let msg = {};
+      msg.blockingCallback = (async _ => {
+        await noStorageAccessInitially();
+      }).toString();
+
+      content.addEventListener("message", function msg(event) {
+        if (event.data.type == "finish") {
+          content.removeEventListener("message", msg);
+          resolve();
+          return;
+        }
+
+        if (event.data.type == "ok") {
+          ok(event.data.what, event.data.msg);
+          return;
+        }
+
+        if (event.data.type == "info") {
+          info(event.data.msg);
+          return;
+        }
+
+        ok(false, "Unknown message");
+      });
+      ifr.contentWindow.postMessage({ callback: msg.blockingCallback }, "*");
+    });
+  });
+
   info("Removing the tab");
   BrowserTestUtils.removeTab(tab);
 });
 
 add_task(async function() {
   info("Cleaning up.");
   await new Promise(resolve => {
     Services.clearData.deleteData(Ci.nsIClearDataService.CLEAR_ALL, value => resolve());