Backed out 12 changesets (bug 1525245) for failing worker-interception.https.html CLOSED TREE

Backed out changeset 009e7457b990 (bug 1525245)
Backed out changeset efb2e8fca464 (bug 1525245)
Backed out changeset 6a8401de3237 (bug 1525245)
Backed out changeset 38e802661b14 (bug 1525245)
Backed out changeset d02e3f436390 (bug 1525245)
Backed out changeset 10afd61b7582 (bug 1525245)
Backed out changeset 6b92fb3666d1 (bug 1525245)
Backed out changeset 476af2d7efe5 (bug 1525245)
Backed out changeset 43ad14e323a1 (bug 1525245)
Backed out changeset 94295e3fb027 (bug 1525245)
Backed out changeset d01ead2270e9 (bug 1525245)
Backed out changeset 6bdda622a04a (bug 1525245)
This commit is contained in:
Ciure Andrei 2019-02-28 00:55:39 +02:00
Родитель 64539979a9
Коммит 8d2894e70d
66 изменённых файлов: 920 добавлений и 1721 удалений

Просмотреть файл

@ -78,7 +78,6 @@
#include "mozilla/dom/ShadowIncludingTreeIterator.h" #include "mozilla/dom/ShadowIncludingTreeIterator.h"
#include "mozilla/dom/StyleSheetList.h" #include "mozilla/dom/StyleSheetList.h"
#include "mozilla/dom/SVGUseElement.h" #include "mozilla/dom/SVGUseElement.h"
#include "mozilla/net/CookieSettings.h"
#include "nsGenericHTMLElement.h" #include "nsGenericHTMLElement.h"
#include "mozilla/dom/CDATASection.h" #include "mozilla/dom/CDATASection.h"
#include "mozilla/dom/ProcessingInstruction.h" #include "mozilla/dom/ProcessingInstruction.h"
@ -129,7 +128,6 @@
#include "nsIDOMWindow.h" #include "nsIDOMWindow.h"
#include "nsPIDOMWindow.h" #include "nsPIDOMWindow.h"
#include "nsFocusManager.h" #include "nsFocusManager.h"
#include "nsICookiePermission.h"
#include "nsICookieService.h" #include "nsICookieService.h"
#include "nsBidiUtils.h" #include "nsBidiUtils.h"
@ -2572,18 +2570,6 @@ nsresult Document::StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
aChannel->Cancel(NS_ERROR_CSP_FRAME_ANCESTOR_VIOLATION); 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; return NS_OK;
} }
@ -11813,7 +11799,7 @@ DocumentAutoplayPolicy Document::AutoplayPolicy() const {
} }
void Document::MaybeAllowStorageForOpenerAfterUserInteraction() { void Document::MaybeAllowStorageForOpenerAfterUserInteraction() {
if (mCookieSettings->GetCookieBehavior() != if (StaticPrefs::network_cookie_cookieBehavior() !=
nsICookieService::BEHAVIOR_REJECT_TRACKER) { nsICookieService::BEHAVIOR_REJECT_TRACKER) {
return; return;
} }
@ -12329,8 +12315,8 @@ already_AddRefed<mozilla::dom::Promise> Document::RequestStorageAccess(
} }
// Only enforce third-party checks when there is a reason to enforce them. // Only enforce third-party checks when there is a reason to enforce them.
if (mCookieSettings->GetCookieBehavior() != if (StaticPrefs::network_cookie_cookieBehavior() !=
nsICookieService::BEHAVIOR_REJECT_TRACKER) { nsICookieService::BEHAVIOR_ACCEPT) {
// Step 3. If the document's frame is the main frame, resolve. // Step 3. If the document's frame is the main frame, resolve.
if (IsTopLevelContentDocument()) { if (IsTopLevelContentDocument()) {
promise->MaybeResolveWithUndefined(); promise->MaybeResolveWithUndefined();
@ -12382,7 +12368,7 @@ already_AddRefed<mozilla::dom::Promise> Document::RequestStorageAccess(
return promise.forget(); return promise.forget();
} }
if (mCookieSettings->GetCookieBehavior() == if (StaticPrefs::network_cookie_cookieBehavior() ==
nsICookieService::BEHAVIOR_REJECT_TRACKER && nsICookieService::BEHAVIOR_REJECT_TRACKER &&
inner) { inner) {
// Only do something special for third-party tracking content. // Only do something special for third-party tracking content.
@ -12640,15 +12626,5 @@ void Document::RecomputeLanguageFromCharset() {
mLanguageFromCharset = language.forget(); 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 dom
} // namespace mozilla } // namespace mozilla

Просмотреть файл

@ -12,8 +12,7 @@
#include "nsCOMArray.h" // for member #include "nsCOMArray.h" // for member
#include "nsCompatibility.h" // for member #include "nsCompatibility.h" // for member
#include "nsCOMPtr.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 "nsIApplicationCache.h"
#include "nsIApplicationCacheContainer.h" #include "nsIApplicationCacheContainer.h"
#include "nsIContentViewer.h" #include "nsIContentViewer.h"
@ -1506,9 +1505,6 @@ class Document : public nsINode,
// Sets the cache sizes for the current generation. // Sets the cache sizes for the current generation.
void SetCachedSizes(nsTabSizes* aSizes); void SetCachedSizes(nsTabSizes* aSizes);
// Returns the cookie settings for this and sub contexts.
nsICookieSettings* CookieSettings();
protected: protected:
friend class nsUnblockOnloadEvent; friend class nsUnblockOnloadEvent;
@ -4667,8 +4663,6 @@ class Document : public nsINode,
int32_t mCachedTabSizeGeneration; int32_t mCachedTabSizeGeneration;
nsTabSizes mCachedTabSizes; nsTabSizes mCachedTabSizes;
nsCOMPtr<nsICookieSettings> mCookieSettings;
public: public:
// Needs to be public because the bindings code pokes at it. // Needs to be public because the bindings code pokes at it.
js::ExpandoAndGeneration mExpandoAndGeneration; js::ExpandoAndGeneration mExpandoAndGeneration;

Просмотреть файл

@ -8229,30 +8229,31 @@ nsContentUtils::StorageAccess nsContentUtils::StorageAllowedForServiceWorker(
} }
// static, private // static, private
void nsContentUtils::GetCookieLifetimePolicyFromCookieSettings( void nsContentUtils::GetCookieLifetimePolicyForPrincipal(
nsICookieSettings* aCookieSettings, nsIPrincipal* aPrincipal, nsIPrincipal* aPrincipal, uint32_t* aLifetimePolicy) {
uint32_t* aLifetimePolicy) {
*aLifetimePolicy = sCookiesLifetimePolicy; *aLifetimePolicy = sCookiesLifetimePolicy;
if (aCookieSettings) { // Any permissions set for the given principal will override our default
uint32_t cookiePermission = 0; // settings from preferences.
nsresult rv = nsCOMPtr<nsIPermissionManager> permissionManager =
aCookieSettings->CookiePermission(aPrincipal, &cookiePermission); services::GetPermissionManager();
if (NS_WARN_IF(NS_FAILED(rv))) { if (!permissionManager) {
return; return;
} }
switch (cookiePermission) { uint32_t perm;
case nsICookiePermission::ACCESS_ALLOW: permissionManager->TestPermissionFromPrincipal(
*aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY; aPrincipal, NS_LITERAL_CSTRING("cookie"), &perm);
break; switch (perm) {
case nsICookiePermission::ACCESS_DENY: case nsICookiePermission::ACCESS_ALLOW:
*aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY; *aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
break; break;
case nsICookiePermission::ACCESS_SESSION: case nsICookiePermission::ACCESS_DENY:
*aLifetimePolicy = nsICookieService::ACCEPT_SESSION; *aLifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
break; break;
} case nsICookiePermission::ACCESS_SESSION:
*aLifetimePolicy = nsICookieService::ACCEPT_SESSION;
break;
} }
} }
@ -8423,7 +8424,6 @@ nsContentUtils::StorageAccess nsContentUtils::InternalStorageAllowedCheck(
aRejectedReason = 0; aRejectedReason = 0;
StorageAccess access = StorageAccess::eAllow; StorageAccess access = StorageAccess::eAllow;
nsCOMPtr<nsICookieSettings> cookieSettings;
// We don't allow storage on the null principal, in general. Even if the // We don't allow storage on the null principal, in general. Even if the
// calling context is chrome. // calling context is chrome.
@ -8442,15 +8442,6 @@ nsContentUtils::StorageAccess nsContentUtils::InternalStorageAllowedCheck(
if (IsInPrivateBrowsing(document)) { if (IsInPrivateBrowsing(document)) {
access = StorageAccess::ePrivateBrowsing; access = StorageAccess::ePrivateBrowsing;
} }
if (document) {
cookieSettings = document->CookieSettings();
}
}
if (aChannel) {
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
loadInfo->GetCookieSettings(getter_AddRefs(cookieSettings));
} }
uint32_t lifetimePolicy; uint32_t lifetimePolicy;
@ -8462,8 +8453,7 @@ nsContentUtils::StorageAccess nsContentUtils::InternalStorageAllowedCheck(
if (policy) { if (policy) {
lifetimePolicy = nsICookieService::ACCEPT_NORMALLY; lifetimePolicy = nsICookieService::ACCEPT_NORMALLY;
} else { } else {
GetCookieLifetimePolicyFromCookieSettings(cookieSettings, aPrincipal, GetCookieLifetimePolicyForPrincipal(aPrincipal, &lifetimePolicy);
&lifetimePolicy);
} }
// Check if we should only allow storage for the session, and record that fact // Check if we should only allow storage for the session, and record that fact

Просмотреть файл

@ -3385,14 +3385,13 @@ class nsContentUtils {
CallOnRemoteChildFunction aCallback, void* aArg); CallOnRemoteChildFunction aCallback, void* aArg);
/** /**
* Gets the cookie lifetime policy for a given cookieSettings and a given * Gets the current cookie lifetime policy for a given principal by checking
* principal by checking the permission value. * with preferences and the permission manager.
* *
* Used in the implementation of InternalStorageAllowedCheck. * Used in the implementation of InternalStorageAllowedCheck.
*/ */
static void GetCookieLifetimePolicyFromCookieSettings( static void GetCookieLifetimePolicyForPrincipal(nsIPrincipal* aPrincipal,
nsICookieSettings* aCookieSettings, nsIPrincipal* aPrincipal, uint32_t* aLifetimePolicy);
uint32_t* aLifetimePolicy);
/* /*
* Checks if storage for a given principal is permitted by the user's * Checks if storage for a given principal is permitted by the user's

Просмотреть файл

@ -4349,48 +4349,6 @@ Storage* nsGlobalWindowInner::GetSessionStorage(ErrorResult& aError) {
return nullptr; 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; nsresult rv;
nsCOMPtr<nsIDOMStorageManager> storageManager = nsCOMPtr<nsIDOMStorageManager> storageManager =

Просмотреть файл

@ -1264,6 +1264,10 @@ nsGlobalWindowOuter::~nsGlobalWindowOuter() {
if (obs) { if (obs) {
obs->RemoveObserver(this, PERM_CHANGE_NOTIFICATION); obs->RemoveObserver(this, PERM_CHANGE_NOTIFICATION);
} }
nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (prefBranch) {
prefBranch->RemoveObserver("network.cookie.cookieBehavior", this);
}
nsLayoutStatics::Release(); nsLayoutStatics::Release();
} }
@ -2320,18 +2324,20 @@ nsresult nsGlobalWindowOuter::SetNewDocument(Document* aDocument,
mHasStorageAccess = false; mHasStorageAccess = false;
nsIURI* uri = aDocument->GetDocumentURI(); nsIURI* uri = aDocument->GetDocumentURI();
if (newInnerWindow && if (newInnerWindow) {
aDocument->CookieSettings()->GetCookieBehavior() == if (StaticPrefs::network_cookie_cookieBehavior() ==
nsICookieService::BEHAVIOR_REJECT_TRACKER && nsICookieService::BEHAVIOR_REJECT_TRACKER &&
nsContentUtils::IsThirdPartyWindowOrChannel(newInnerWindow, nullptr, nsContentUtils::IsThirdPartyWindowOrChannel(newInnerWindow, nullptr,
uri) && uri) &&
nsContentUtils::IsTrackingResourceWindow(newInnerWindow)) { nsContentUtils::IsTrackingResourceWindow(newInnerWindow)) {
// Grant storage access by default if the first-party storage access // Grant storage access by default if the first-party storage access
// permission has been granted already. // permission has been granted already.
// Don't notify in this case, since we would be notifying the user // Don't notify in this case, since we would be notifying the user
// needlessly. // needlessly.
mHasStorageAccess = AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor( mHasStorageAccess =
newInnerWindow, uri, nullptr); AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
newInnerWindow, uri, nullptr);
}
} }
return NS_OK; return NS_OK;
@ -6969,6 +6975,11 @@ NS_IMETHODIMP
nsGlobalWindowOuter::Observe(nsISupports* aSupports, const char* aTopic, nsGlobalWindowOuter::Observe(nsISupports* aSupports, const char* aTopic,
const char16_t* aData) { const char16_t* aData) {
if (!nsCRT::strcmp(aTopic, PERM_CHANGE_NOTIFICATION)) { 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); nsCOMPtr<nsIPermission> permission = do_QueryInterface(aSupports);
if (!permission) { if (!permission) {
return NS_OK; return NS_OK;
@ -7000,6 +7011,10 @@ nsGlobalWindowOuter::Observe(nsISupports* aSupports, const char* aTopic,
return NS_OK; 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; return NS_OK;
} }
@ -7796,6 +7811,10 @@ mozilla::dom::TabGroup* nsPIDOMWindowOuter::TabGroup() {
obs->AddObserver(window, PERM_CHANGE_NOTIFICATION, true); 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(); return window.forget();
} }

Просмотреть файл

@ -67,13 +67,15 @@ nsIPrincipal* GetPrincipalFromThreadSafeWorkerRef(
class InitializeRunnable final : public WorkerMainThreadRunnable { class InitializeRunnable final : public WorkerMainThreadRunnable {
public: public:
InitializeRunnable(ThreadSafeWorkerRef* aWorkerRef, nsACString& aOrigin, InitializeRunnable(ThreadSafeWorkerRef* aWorkerRef, nsACString& aOrigin,
PrincipalInfo& aPrincipalInfo, ErrorResult& aRv) PrincipalInfo& aPrincipalInfo, bool* aThirdPartyWindow,
ErrorResult& aRv)
: WorkerMainThreadRunnable( : WorkerMainThreadRunnable(
aWorkerRef->Private(), aWorkerRef->Private(),
NS_LITERAL_CSTRING("BroadcastChannel :: Initialize")), NS_LITERAL_CSTRING("BroadcastChannel :: Initialize")),
mWorkerRef(aWorkerRef), mWorkerRef(aWorkerRef),
mOrigin(aOrigin), mOrigin(aOrigin),
mPrincipalInfo(aPrincipalInfo), mPrincipalInfo(aPrincipalInfo),
mThirdPartyWindow(aThirdPartyWindow),
mRv(aRv) { mRv(aRv) {
MOZ_ASSERT(mWorkerRef); MOZ_ASSERT(mWorkerRef);
} }
@ -109,6 +111,9 @@ class InitializeRunnable final : public WorkerMainThreadRunnable {
return true; return true;
} }
*mThirdPartyWindow =
nsContentUtils::IsThirdPartyWindowOrChannel(window, nullptr, nullptr);
return true; return true;
} }
@ -116,6 +121,7 @@ class InitializeRunnable final : public WorkerMainThreadRunnable {
RefPtr<ThreadSafeWorkerRef> mWorkerRef; RefPtr<ThreadSafeWorkerRef> mWorkerRef;
nsACString& mOrigin; nsACString& mOrigin;
PrincipalInfo& mPrincipalInfo; PrincipalInfo& mPrincipalInfo;
bool* mThirdPartyWindow;
ErrorResult& mRv; ErrorResult& mRv;
}; };
@ -241,14 +247,6 @@ JSObject* BroadcastChannel::WrapObject(JSContext* aCx,
return nullptr; 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); aRv = principal->GetOrigin(origin);
if (NS_WARN_IF(aRv.Failed())) { if (NS_WARN_IF(aRv.Failed())) {
return nullptr; return nullptr;
@ -258,6 +256,13 @@ JSObject* BroadcastChannel::WrapObject(JSContext* aCx,
if (NS_WARN_IF(aRv.Failed())) { if (NS_WARN_IF(aRv.Failed())) {
return nullptr; return nullptr;
} }
if (nsContentUtils::IsThirdPartyWindowOrChannel(window, nullptr, nullptr) &&
nsContentUtils::StorageAllowedForWindow(window) !=
nsContentUtils::StorageAccess::eAllow) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr;
}
} else { } else {
JSContext* cx = aGlobal.Context(); JSContext* cx = aGlobal.Context();
@ -275,15 +280,16 @@ JSObject* BroadcastChannel::WrapObject(JSContext* aCx,
RefPtr<ThreadSafeWorkerRef> tsr = new ThreadSafeWorkerRef(workerRef); RefPtr<ThreadSafeWorkerRef> tsr = new ThreadSafeWorkerRef(workerRef);
RefPtr<InitializeRunnable> runnable = bool thirdPartyWindow = false;
new InitializeRunnable(tsr, origin, principalInfo, aRv);
RefPtr<InitializeRunnable> runnable = new InitializeRunnable(
tsr, origin, principalInfo, &thirdPartyWindow, aRv);
runnable->Dispatch(Canceling, aRv); runnable->Dispatch(Canceling, aRv);
if (aRv.Failed()) { if (aRv.Failed()) {
return nullptr; return nullptr;
} }
if (principalInfo.type() != PrincipalInfo::TNullPrincipalInfo && if (thirdPartyWindow && !workerPrivate->IsStorageAllowed()) {
!workerPrivate->IsStorageAllowed()) {
aRv.Throw(NS_ERROR_DOM_SECURITY_ERR); aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
return nullptr; return nullptr;
} }

Просмотреть файл

@ -16,6 +16,8 @@ support-files =
file.js file.js
helpers.js helpers.js
leaving_page_iframe.html leaving_page_iframe.html
third_party_iframe1.html
third_party_iframe2.html
unit/test_abort_deleted_index.js unit/test_abort_deleted_index.js
unit/test_abort_deleted_objectStore.js unit/test_abort_deleted_objectStore.js
unit/test_add_put.js unit/test_add_put.js
@ -254,10 +256,6 @@ scheme=https
[test_table_locks.html] [test_table_locks.html]
[test_table_rollback.html] [test_table_rollback.html]
[test_third_party.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 skip-if = (os == 'android' && debug) # Bug 1311590
[test_traffic_jam.html] [test_traffic_jam.html]
[test_transaction_abort.html] [test_transaction_abort.html]

Просмотреть файл

@ -46,25 +46,29 @@
"third_party_iframe2.html"); "third_party_iframe2.html");
let testIndex = 0; let testIndex = 0;
let openedWindow; let testRunning = false;
// Cookie preference changes are only applied to top-level tabs/windows function iframeLoaded() {
// when they are loaded. We need a window-proxy to continue the test. let message = { source: "parent", href: iframe2URL };
function openWindow() { let iframe = document.getElementById("iframe1");
iframe.contentWindow.postMessage(message.toSource(), "*");
}
function setiframe() {
let iframe = document.getElementById("iframe1");
if (!testRunning) {
testRunning = true;
iframe.addEventListener("load", iframeLoaded);
}
SpecialPowers.pushPrefEnv({ SpecialPowers.pushPrefEnv({
"set": [ "set": [
["network.cookie.cookieBehavior", testData[testIndex].cookieBehavior], ["network.cookie.cookieBehavior", testData[testIndex].cookieBehavior],
], ],
}, () => { }, () => {
openedWindow = window.open("third_party_window.html"); iframe.src = testData[testIndex].host + iframe1Path;
openedWindow.onload = _ => {
openedWindow.postMessage({
source: "parent",
href: iframe2URL,
iframeUrl: testData[testIndex].host + iframe1Path,
}, "*");
};
}); });
// SpecialPowers.setIntPref("network.cookie.cookieBehavior", testData[testIndex].cookieBehavior);
} }
function messageListener(event) { function messageListener(event) {
@ -74,11 +78,9 @@
is(message.source, "iframe", "Good source"); is(message.source, "iframe", "Good source");
is(message.result, testData[testIndex].expectedResult, "Good result"); is(message.result, testData[testIndex].expectedResult, "Good result");
openedWindow.close();
if (testIndex < testData.length - 1) { if (testIndex < testData.length - 1) {
testIndex++; testIndex++;
openWindow(); setiframe();
return; return;
} }
@ -91,13 +93,14 @@
SpecialPowers.addPermission("indexedDB", true, document); SpecialPowers.addPermission("indexedDB", true, document);
window.addEventListener("message", messageListener); window.addEventListener("message", messageListener);
openWindow(); setiframe();
} }
</script> </script>
</head> </head>
<body onload="runTest();"> <body onload="runTest();">
<iframe id="iframe1"></iframe>
</body> </body>
</html> </html>

Просмотреть файл

@ -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>

Просмотреть файл

@ -308,8 +308,6 @@ skip-if = serviceworker_e10s
[test_skip_waiting.html] [test_skip_waiting.html]
[test_strict_mode_warning.html] [test_strict_mode_warning.html]
[test_third_party_iframes.html] [test_third_party_iframes.html]
support-files =
window_party_iframes.html
[test_unregister.html] [test_unregister.html]
[test_unresolved_fetch_interception.html] [test_unresolved_fetch_interception.html]
skip-if = verify || serviceworker_e10s skip-if = verify || serviceworker_e10s

Просмотреть файл

@ -11,6 +11,11 @@
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head> </head>
<body> <body>
<p id="display"></p>
<div id="content" style="display: none">
<iframe></iframe>
</div>
<pre id="test"></pre>
<script class="testbody" type="text/javascript"> <script class="testbody" type="text/javascript">
SimpleTest.waitForExplicitFinish(); SimpleTest.waitForExplicitFinish();
@ -34,7 +39,6 @@ function next() {
onload = next; onload = next;
let iframe; let iframe;
let proxyWindow;
let basePath = "/tests/dom/serviceworkers/test/thirdparty/"; let basePath = "/tests/dom/serviceworkers/test/thirdparty/";
let origin = window.location.protocol + "//" + window.location.host; let origin = window.location.protocol + "//" + window.location.host;
let thirdPartyOrigin = "https://example.com"; let thirdPartyOrigin = "https://example.com";
@ -58,26 +62,22 @@ function loadThirdPartyIframe() {
} }
function runTest(aExpectedResponses) { function runTest(aExpectedResponses) {
// Let's use a proxy window to have the new cookie policy applied. iframe = document.querySelector("iframe");
proxyWindow = window.open("window_party_iframes.html"); iframe.src = thirdPartyOrigin + basePath + "register.html";
proxyWindow.onload = _ => { let responsesIndex = 0;
iframe = proxyWindow.document.querySelector("iframe"); window.onmessage = function(e) {
iframe.src = thirdPartyOrigin + basePath + "register.html"; let status = e.data.status;
let responsesIndex = 0; let expected = aExpectedResponses[responsesIndex];
window.onmessage = function(e) { if (status == expected.status) {
let status = e.data.status; ok(true, "Received expected " + expected.status);
let expected = aExpectedResponses[responsesIndex]; if (expected.next) {
if (status == expected.status) { expected.next();
ok(true, "Received expected " + expected.status);
if (expected.next) {
expected.next();
}
} else {
ok(false, "Expected " + expected.status + " got " + status);
} }
responsesIndex++; } else {
}; ok(false, "Expected " + expected.status + " got " + status);
} }
responsesIndex++;
};
} }
// Verify that we can register and intercept a 3rd party iframe with // Verify that we can register and intercept a 3rd party iframe with
@ -113,7 +113,6 @@ function testShouldIntercept(behavior, lifetime, done) {
status: "unregistrationdone", status: "unregistrationdone",
next: function() { next: function() {
window.onmessage = null; window.onmessage = null;
proxyWindow.close();
ok(true, "Test finished successfully"); ok(true, "Test finished successfully");
done(); done();
} }
@ -145,7 +144,6 @@ function testShouldNotRegister(behavior, lifetime, done) {
status: "worker-networkresponse", status: "worker-networkresponse",
next: function() { next: function() {
window.onmessage = null; window.onmessage = null;
proxyWindow.close();
ok(true, "Test finished successfully"); ok(true, "Test finished successfully");
done(); done();
} }
@ -166,17 +164,12 @@ function testShouldNotIntercept(behavior, lifetime, done) {
}, { }, {
status: "registrationdone", status: "registrationdone",
next: function() { next: function() {
iframe.addEventListener("load", testIframeLoaded);
SpecialPowers.pushPrefEnv({"set": [ SpecialPowers.pushPrefEnv({"set": [
["network.cookie.cookieBehavior", behavior], ["network.cookie.cookieBehavior", behavior],
["network.cookie.lifetimePolicy", lifetime], ["network.cookie.lifetimePolicy", lifetime],
]}, function() { ]}, function() {
proxyWindow.close(); iframe.src = origin + basePath + "iframe1.html";
proxyWindow = window.open("window_party_iframes.html");
proxyWindow.onload = _ => {
iframe = proxyWindow.document.querySelector("iframe");
iframe.addEventListener("load", testIframeLoaded);
iframe.src = origin + basePath + "iframe1.html";
}
}); });
} }
}, { }, {
@ -200,13 +193,7 @@ function testShouldNotIntercept(behavior, lifetime, done) {
["network.cookie.cookieBehavior", BEHAVIOR_ACCEPT], ["network.cookie.cookieBehavior", BEHAVIOR_ACCEPT],
["network.cookie.lifetimePolicy", LIFETIME_EXPIRE], ["network.cookie.lifetimePolicy", LIFETIME_EXPIRE],
]}, function() { ]}, function() {
proxyWindow.close(); iframe.src = thirdPartyOrigin + basePath + "unregister.html";
proxyWindow = window.open("window_party_iframes.html");
proxyWindow.onload = _ => {
iframe = proxyWindow.document.querySelector("iframe");
iframe.addEventListener("load", testIframeLoaded);
iframe.src = thirdPartyOrigin + basePath + "unregister.html";
}
}); });
} }
}, { }, {
@ -215,7 +202,6 @@ function testShouldNotIntercept(behavior, lifetime, done) {
status: "unregistrationdone", status: "unregistrationdone",
next: function() { next: function() {
window.onmessage = null; window.onmessage = null;
proxyWindow.close();
ok(true, "Test finished successfully"); ok(true, "Test finished successfully");
done(); done();
} }

Просмотреть файл

@ -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>

Просмотреть файл

@ -77,6 +77,7 @@ LocalStorageCache::LocalStorageCache(const nsACString* aOriginNoSuffix)
mLoadResult(NS_OK), mLoadResult(NS_OK),
mInitialized(false), mInitialized(false),
mPersistent(false), mPersistent(false),
mSessionOnlyDataSetActive(false),
mPreloadTelemetryRecorded(false) { mPreloadTelemetryRecorded(false) {
MOZ_COUNT_CTOR(LocalStorageCache); MOZ_COUNT_CTOR(LocalStorageCache);
} }
@ -182,7 +183,29 @@ const nsCString LocalStorageCache::Origin() const {
LocalStorageCache::Data& LocalStorageCache::DataSet( LocalStorageCache::Data& LocalStorageCache::DataSet(
const LocalStorage* aStorage) { 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, bool LocalStorageCache::ProcessUsageDelta(const LocalStorage* aStorage,
@ -518,6 +541,7 @@ void LocalStorageCache::UnloadItems(uint32_t aUnloadFlags) {
if (aUnloadFlags & kUnloadSession) { if (aUnloadFlags & kUnloadSession) {
mData[kSessionSet].mKeys.Clear(); mData[kSessionSet].mKeys.Clear();
ProcessUsageDelta(kSessionSet, -mData[kSessionSet].mOriginQuotaUsage); ProcessUsageDelta(kSessionSet, -mData[kSessionSet].mOriginQuotaUsage);
mSessionOnlyDataSetActive = false;
} }
#ifdef DOM_STORAGE_TESTS #ifdef DOM_STORAGE_TESTS

Просмотреть файл

@ -267,6 +267,12 @@ class LocalStorageCache : public LocalStorageCacheBridge {
// default data set.) // default data set.)
bool mPersistent : 1; 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 // Whether we have already captured state of the cache preload on our first
// access. // access.
bool mPreloadTelemetryRecorded : 1; bool mPreloadTelemetryRecorded : 1;

Просмотреть файл

@ -164,5 +164,11 @@ bool SessionStorage::IsForkOf(const Storage* aOther) const {
return mCache == static_cast<const SessionStorage*>(aOther)->mCache; return mCache == static_cast<const SessionStorage*>(aOther)->mCache;
} }
bool SessionStorage::ShouldThrowWhenStorageAccessDenied(
uint32_t aRejectedReason) {
return aRejectedReason !=
nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN;
}
} // namespace dom } // namespace dom
} // namespace mozilla } // namespace mozilla

Просмотреть файл

@ -65,6 +65,8 @@ class SessionStorage final : public Storage {
const nsAString& aOldValue, const nsAString& aOldValue,
const nsAString& aNewValue); const nsAString& aNewValue);
bool ShouldThrowWhenStorageAccessDenied(uint32_t aRejectedReason) override;
RefPtr<SessionStorageCache> mCache; RefPtr<SessionStorageCache> mCache;
RefPtr<SessionStorageManager> mManager; RefPtr<SessionStorageManager> mManager;

Просмотреть файл

@ -9,7 +9,7 @@
namespace mozilla { namespace mozilla {
namespace dom { namespace dom {
SessionStorageCache::SessionStorageCache() = default; SessionStorageCache::SessionStorageCache() : mSessionDataSetActive(false) {}
SessionStorageCache::DataSet* SessionStorageCache::Set( SessionStorageCache::DataSet* SessionStorageCache::Set(
DataSetType aDataSetType) { DataSetType aDataSetType) {
@ -19,6 +19,16 @@ SessionStorageCache::DataSet* SessionStorageCache::Set(
MOZ_ASSERT(aDataSetType == eSessionSetType); 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; return &mSessionSet;
} }
@ -111,11 +121,17 @@ void SessionStorageCache::Clear(DataSetType aDataSetType,
DataSet* dataSet = Set(aDataSetType); DataSet* dataSet = Set(aDataSetType);
dataSet->ProcessUsageDelta(-dataSet->mOriginQuotaUsage); dataSet->ProcessUsageDelta(-dataSet->mOriginQuotaUsage);
dataSet->mKeys.Clear(); dataSet->mKeys.Clear();
if (!aByUserInteraction && aDataSetType == eSessionSetType) {
mSessionDataSetActive = false;
}
} }
already_AddRefed<SessionStorageCache> SessionStorageCache::Clone() const { already_AddRefed<SessionStorageCache> SessionStorageCache::Clone() const {
RefPtr<SessionStorageCache> cache = new SessionStorageCache(); RefPtr<SessionStorageCache> cache = new SessionStorageCache();
cache->mSessionDataSetActive = mSessionDataSetActive;
cache->mDefaultSet.mOriginQuotaUsage = mDefaultSet.mOriginQuotaUsage; cache->mDefaultSet.mOriginQuotaUsage = mDefaultSet.mOriginQuotaUsage;
for (auto iter = mDefaultSet.mKeys.ConstIter(); !iter.Done(); iter.Next()) { for (auto iter = mDefaultSet.mKeys.ConstIter(); !iter.Done(); iter.Next()) {
cache->mDefaultSet.mKeys.Put(iter.Key(), iter.Data()); cache->mDefaultSet.mKeys.Put(iter.Key(), iter.Data());

Просмотреть файл

@ -60,6 +60,7 @@ class SessionStorageCache final {
DataSet mDefaultSet; DataSet mDefaultSet;
DataSet mSessionSet; DataSet mSessionSet;
bool mSessionDataSetActive;
}; };
} // namespace dom } // namespace dom

Просмотреть файл

@ -29,20 +29,6 @@ NS_INTERFACE_MAP_END
Storage::Storage(nsPIDOMWindowInner* aWindow, nsIPrincipal* aPrincipal) Storage::Storage(nsPIDOMWindowInner* aWindow, nsIPrincipal* aPrincipal)
: mWindow(aWindow), mPrincipal(aPrincipal), mIsSessionOnly(false) { : mWindow(aWindow), mPrincipal(aPrincipal), mIsSessionOnly(false) {
MOZ_ASSERT(aPrincipal); 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() {} Storage::~Storage() {}
@ -52,10 +38,28 @@ Storage::~Storage() {}
} }
bool Storage::CanUseStorage(nsIPrincipal& aSubjectPrincipal) { bool Storage::CanUseStorage(nsIPrincipal& aSubjectPrincipal) {
// This method is responsible for correct setting of mIsSessionOnly.
if (!StoragePrefIsEnabled()) { if (!StoragePrefIsEnabled()) {
return false; 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); return aSubjectPrincipal.Subsumes(mPrincipal);
} }

Просмотреть файл

@ -134,10 +134,23 @@ class Storage : public nsISupports, public nsWrapperCache {
virtual ~Storage(); virtual ~Storage();
// The method checks whether the caller can use a 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); bool CanUseStorage(nsIPrincipal& aSubjectPrincipal);
virtual void LastRelease() {} 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: private:
nsCOMPtr<nsPIDOMWindowInner> mWindow; nsCOMPtr<nsPIDOMWindowInner> mWindow;
nsCOMPtr<nsIPrincipal> mPrincipal; nsCOMPtr<nsIPrincipal> mPrincipal;

Просмотреть файл

@ -149,7 +149,6 @@ skip-if = toolkit == 'android'
[test_bug1112040.html] [test_bug1112040.html]
[test_bug1160342_marquee.html] [test_bug1160342_marquee.html]
[test_bug1171215.html] [test_bug1171215.html]
support-files = window_bug1171215.html
[test_bug1530292.html] [test_bug1530292.html]
[test_no_find_showDialog.html] [test_no_find_showDialog.html]
skip-if = toolkit == 'android' # Bug 1358633 - window.find doesn't work for Android skip-if = toolkit == 'android' # Bug 1358633 - window.find doesn't work for Android

Просмотреть файл

@ -9,8 +9,11 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1022869
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="application/javascript" src="/tests/SimpleTest/AddTask.js"></script> <script type="application/javascript" src="/tests/SimpleTest/AddTask.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
<iframe src="about:blank"></iframe>
<script type="text/javascript"> <script type="text/javascript">
var f = document.getElementsByTagName("iframe")[0];
SimpleTest.waitForExplicitFinish(); SimpleTest.waitForExplicitFinish();
/** Test for Bug 1022869 **/ /** Test for Bug 1022869 **/
@ -18,32 +21,69 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1022869
// Initialize our cookie. // Initialize our cookie.
document.cookie = "a=b"; document.cookie = "a=b";
SpecialPowers.pushPrefEnv({ set: [["network.cookie.cookieBehavior", 1]] }).then(_ => { // Set a cookie in example.org so we can test that we can't read it in
let w = window.open("window_bug1171215.html"); // third-party cases.
onmessage = e => { f.contentWindow.location =
if (e.data.type == "finish") { "http://example.org/tests/dom/tests/mochitest/bugs/file_prime_cookie.html";
w.close(); waitForLoad().then(function() {
SimpleTest.finish(); // Cookies are set up, disallow third-party cookies and start the test.
return; SpecialPowers.pushPrefEnv({ set: [
} ["network.cookie.cookieBehavior", 1],
]}, () => { continueTest(); });
}).catch((e) => { ok(false, `Got exception: ${e}`) });
}
if (e.data.type == "info") { function waitForLoad() {
info(e.data.msg); return new Promise((resolve) => {
return; window.addEventListener("message", function(msg) {
} info(`got message ${msg.data}`);
resolve(msg.data);
if (e.data.type == "test") { }, {once: true});
ok(e.data.test, e.data.msg);
return;
}
ok(false, "Unknown message");
};
}); });
} }
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");
SimpleTest.finish();
}
</script> </script>
</head> </head>
<body onload="startTest()"> <body onload="startTest()">
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1022869">Mozilla Bug 1022869</a> <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> </body>
</html> </html>

Просмотреть файл

@ -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>

Просмотреть файл

@ -50,7 +50,6 @@ support-files =
workerStorageAllowed.js workerStorageAllowed.js
workerStoragePrevented.js workerStoragePrevented.js
storagePermissionsUtils.js storagePermissionsUtils.js
window_storagePermissions.html
frameSelectEvents.html frameSelectEvents.html
!/image/test/mochitest/big.png !/image/test/mochitest/big.png
!/image/test/mochitest/blue.png !/image/test/mochitest/blue.png

Просмотреть файл

@ -242,33 +242,4 @@ function task(fn) {
} }
} }
// 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/"; var thirdparty = "https://example.com/tests/dom/tests/mochitest/general/";

Просмотреть файл

@ -14,29 +14,27 @@
task(async function() { task(async function() {
await setCookieBehavior(BEHAVIOR_ACCEPT); await setCookieBehavior(BEHAVIOR_ACCEPT);
await runTestInWindow(async function() { // We should be able to access storage
// We should be able to access storage await storageAllowed();
await storageAllowed();
// Same origin iframes should be allowed, unless they redirect to a URI with the null principal // Same origin iframes should be allowed, unless they redirect to a URI with the null principal
await runIFrame("frameStorageAllowed.html"); await runIFrame("frameStorageAllowed.html");
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
await runIFrame("frameStorageChrome.html?allowed=yes"); await runIFrame("frameStorageChrome.html?allowed=yes");
// Sandboxed iframes should have the null principal, and thus can't access storage // Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts'); document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
await runIFrame("frameStoragePrevented.html#nullprincipal"); await runIFrame("frameStoragePrevented.html#nullprincipal");
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
document.querySelector('iframe').removeAttribute('sandbox'); document.querySelector('iframe').removeAttribute('sandbox');
// Thirdparty iframes should be allowed, unless they redirect to a URI with the null principal // Thirdparty iframes should be allowed, unless they redirect to a URI with the null principal
await runIFrame(thirdparty + "frameStorageAllowed.html"); await runIFrame(thirdparty + "frameStorageAllowed.html");
await runIFrame(thirdparty + "frameStorageNullprincipal.sjs"); await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
await runIFrame(thirdparty + "frameStorageChrome.html?allowed=yes"); await runIFrame(thirdparty + "frameStorageChrome.html?allowed=yes");
// Workers should be able to access storage // Workers should be able to access storage
await runWorker("workerStorageAllowed.js"); await runWorker("workerStorageAllowed.js");
});
}); });
</script> </script>

Просмотреть файл

@ -14,31 +14,29 @@
task(async function() { task(async function() {
await setCookieBehavior(BEHAVIOR_LIMIT_FOREIGN); await setCookieBehavior(BEHAVIOR_LIMIT_FOREIGN);
await runTestInWindow(async function() { // We should be able to access storage
// We should be able to access storage await storageAllowed();
await storageAllowed();
// Same origin iframes should be allowed. // Same origin iframes should be allowed.
await runIFrame("frameStorageAllowed.html"); await runIFrame("frameStorageAllowed.html");
await runIFrame("frameStorageChrome.html?allowed=yes"); await runIFrame("frameStorageChrome.html?allowed=yes");
// Null principal iframes should not. // Null principal iframes should not.
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
// Sandboxed iframes should have the null principal, and thus can't access storage // Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts'); document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
await runIFrame("frameStoragePrevented.html#nullprincipal"); await runIFrame("frameStoragePrevented.html#nullprincipal");
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
document.querySelector('iframe').removeAttribute('sandbox'); document.querySelector('iframe').removeAttribute('sandbox');
// Thirdparty iframes should be blocked, even when accessed from chrome over Xrays. // Thirdparty iframes should be blocked, even when accessed from chrome over Xrays.
await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty"); await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
await runIFrame(thirdparty + "frameStorageNullprincipal.sjs"); await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no"); await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
// Workers should be unable to access storage // Workers should be unable to access storage
await runWorker("workerStorageAllowed.js"); await runWorker("workerStorageAllowed.js");
});
}); });
</script> </script>

Просмотреть файл

@ -14,29 +14,27 @@
task(async function() { task(async function() {
await setCookieBehavior(BEHAVIOR_REJECT); await setCookieBehavior(BEHAVIOR_REJECT);
await runTestInWindow(async function() { // We should be unable to access storage
// We should be unable to access storage await storagePrevented();
await storagePrevented();
// Same origin iframes should be blocked. // Same origin iframes should be blocked.
await runIFrame("frameStoragePrevented.html"); await runIFrame("frameStoragePrevented.html");
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
await runIFrame("frameStorageChrome.html?allowed=no&blockSessionStorage=yes"); await runIFrame("frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
// Sandboxed iframes should have the null principal, and thus can't access storage // Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts'); document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
await runIFrame("frameStoragePrevented.html#nullprincipal"); await runIFrame("frameStoragePrevented.html#nullprincipal");
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
document.querySelector('iframe').removeAttribute('sandbox'); document.querySelector('iframe').removeAttribute('sandbox');
// thirdparty iframes should be blocked. // thirdparty iframes should be blocked.
await runIFrame(thirdparty + "frameStoragePrevented.html"); await runIFrame(thirdparty + "frameStoragePrevented.html");
await runIFrame(thirdparty + "frameStorageNullprincipal.sjs"); await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no&blockSessionStorage=yes"); await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no&blockSessionStorage=yes");
// Workers should be unable to access storage // Workers should be unable to access storage
await runWorker("workerStoragePrevented.js"); await runWorker("workerStoragePrevented.js");
});
}); });
</script> </script>

Просмотреть файл

@ -14,29 +14,27 @@
task(async function() { task(async function() {
await setCookieBehavior(BEHAVIOR_REJECT_FOREIGN); await setCookieBehavior(BEHAVIOR_REJECT_FOREIGN);
await runTestInWindow(async function() { // We should be able to access storage
// We should be able to access storage await storageAllowed();
await storageAllowed();
// Same origin iframes should be allowed, unless they redirect to a URI with the null principal // Same origin iframes should be allowed, unless they redirect to a URI with the null principal
await runIFrame("frameStorageAllowed.html"); await runIFrame("frameStorageAllowed.html");
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
await runIFrame("frameStorageChrome.html?allowed=yes"); await runIFrame("frameStorageChrome.html?allowed=yes");
// Sandboxed iframes should have the null principal, and thus can't access storage // Sandboxed iframes should have the null principal, and thus can't access storage
document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts'); document.querySelector('iframe').setAttribute('sandbox', 'allow-scripts');
await runIFrame("frameStoragePrevented.html#nullprincipal"); await runIFrame("frameStoragePrevented.html#nullprincipal");
await runIFrame("frameStorageNullprincipal.sjs"); await runIFrame("frameStorageNullprincipal.sjs");
document.querySelector('iframe').removeAttribute('sandbox'); document.querySelector('iframe').removeAttribute('sandbox');
// thirdparty iframes should be blocked. // thirdparty iframes should be blocked.
await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty"); await runIFrame(thirdparty + "frameStoragePrevented.html#thirdparty");
await runIFrame(thirdparty + "frameStorageNullprincipal.sjs"); await runIFrame(thirdparty + "frameStorageNullprincipal.sjs");
await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no"); await runIFrame(thirdparty + "frameStorageChrome.html?allowed=no");
// Workers should be able to access storage // Workers should be able to access storage
await runWorker("workerStorageAllowed.js"); await runWorker("workerStorageAllowed.js");
});
}); });
</script> </script>

Просмотреть файл

@ -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>

Просмотреть файл

@ -2,6 +2,8 @@
<head> <head>
<title>localStorage cookies settings test</title> <title>localStorage cookies settings test</title>
<script type="text/javascript" src="interOriginFrame.js"></script>
</head> </head>
<body> <body>
<script type="text/javascript"> <script type="text/javascript">
@ -11,6 +13,8 @@
} catch(ex) { } catch(ex) {
is(ex.name, "TypeError"); is(ex.name, "TypeError");
} }
finishTest();
</script> </script>
</body> </body>
</html> </html>

Просмотреть файл

@ -17,7 +17,6 @@ support-files =
localStorageCommon.js localStorageCommon.js
frameLocalStorageSessionOnly.html frameLocalStorageSessionOnly.html
file_tryAccessSessionStorage.html file_tryAccessSessionStorage.html
windowProxy.html
[test_brokenUTF-16.html] [test_brokenUTF-16.html]
[test_bug600307-DBOps.html] [test_bug600307-DBOps.html]
@ -25,6 +24,7 @@ support-files =
[test_bug746272-2.html] [test_bug746272-2.html]
skip-if = os == "android" || verify # bug 962029 skip-if = os == "android" || verify # bug 962029
[test_cookieBlock.html] [test_cookieBlock.html]
[test_cookieSession.html]
[test_embededNulls.html] [test_embededNulls.html]
[test_keySync.html] [test_keySync.html]
[test_localStorageBase.html] [test_localStorageBase.html]
@ -49,3 +49,4 @@ skip-if = true # bug 1347690
[test_localStorageReplace.html] [test_localStorageReplace.html]
skip-if = toolkit == 'android' skip-if = toolkit == 'android'
[test_storageConstructor.html] [test_storageConstructor.html]
[test_localStorageSessionPrefOverride.html]

Просмотреть файл

@ -9,28 +9,23 @@
function startTest() function startTest()
{ {
// Let's use a new window to have the cookie permission applied. try {
let w = window.open("windowProxy.html"); localStorage.setItem("blocked", "blockedvalue");
w.onload = _ => { ok(false, "Exception for localStorage.setItem, ACCESS_DENY");
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 {
w.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();
} }
catch (ex) {
ok(true, "Exception for localStorage.setItem, ACCESS_DENY");
}
try {
localStorage.getItem("blocked");
ok(false, "Exception for localStorage.getItem, ACCESS_DENY");
}
catch (ex) {
ok(true, "Exception for localStorage.getItem, ACCESS_DENY");
}
SimpleTest.finish();
} }
SimpleTest.waitForExplicitFinish(); SimpleTest.waitForExplicitFinish();

Просмотреть файл

@ -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>

Просмотреть файл

@ -8,6 +8,7 @@
</head> </head>
<body> <body>
<iframe></iframe>
<script type="text/javascript"> <script type="text/javascript">
@ -19,47 +20,39 @@ SpecialPowers.pushPrefEnv({"set": [
]}, test1); ]}, test1);
function test1() { function test1() {
let w = window.open("windowProxy.html"); try {
w.onload = _ => { localStorage.setItem("contentkey", "test-value");
try { ok(false, "Setting localStorageItem should throw a type error exception");
w.localStorage.setItem("contentkey", "test-value");
ok(false, "Setting localStorageItem should throw a security 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);
} }
catch(ex) {
is(ex.name, "TypeError");
}
// Set cookies behavior to "reject 3rd party"
SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 1]],
"clear": [["network.cookie.lifetimePolicy"]]},
test3);
} }
function test2() { function test3() {
let w = window.open("windowProxy.html"); try {
w.onload = _ => { localStorage.setItem("contentkey", "test-value");
try { ok(true, "Setting localStorageItem should not throw a type error exception");
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");
}
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();
}
} }
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 myframe = document.querySelector("iframe");
myframe.src = fileTest;
}
// Called by interOriginTest.js
function doNextTest() {
SimpleTest.finish();
} }
</script> </script>

Просмотреть файл

@ -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>

Просмотреть файл

@ -1,3 +0,0 @@
<html xmlns="http://www.w3.org/1999/xhtml">
<body></body>
</html>

Просмотреть файл

@ -8,6 +8,7 @@ support-files =
interOriginSlave.js interOriginSlave.js
interOriginTest.js interOriginTest.js
[test_cookieSession.html]
[test_sessionStorageBase.html] [test_sessionStorageBase.html]
[test_sessionStorageBaseSessionOnly.html] [test_sessionStorageBaseSessionOnly.html]
[test_sessionStorageClone.html] [test_sessionStorageClone.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>

Просмотреть файл

@ -2017,10 +2017,8 @@ void RuntimeService::PropagateFirstPartyStorageAccessGranted(
nsPIDOMWindowInner* aWindow) { nsPIDOMWindowInner* aWindow) {
AssertIsOnMainThread(); AssertIsOnMainThread();
MOZ_ASSERT(aWindow); MOZ_ASSERT(aWindow);
MOZ_ASSERT_IF( MOZ_ASSERT(StaticPrefs::network_cookie_cookieBehavior() ==
aWindow->GetExtantDoc(), nsICookieService::BEHAVIOR_REJECT_TRACKER);
aWindow->GetExtantDoc()->CookieSettings()->GetCookieBehavior() ==
nsICookieService::BEHAVIOR_REJECT_TRACKER);
nsTArray<WorkerPrivate*> workers; nsTArray<WorkerPrivate*> workers;
GetWorkersForWindow(aWindow, workers); GetWorkersForWindow(aWindow, workers);
@ -2401,10 +2399,8 @@ void ResumeWorkersForWindow(nsPIDOMWindowInner* aWindow) {
void PropagateFirstPartyStorageAccessGrantedToWorkers( void PropagateFirstPartyStorageAccessGrantedToWorkers(
nsPIDOMWindowInner* aWindow) { nsPIDOMWindowInner* aWindow) {
AssertIsOnMainThread(); AssertIsOnMainThread();
MOZ_ASSERT_IF( MOZ_ASSERT(StaticPrefs::network_cookie_cookieBehavior() ==
aWindow->GetExtantDoc(), nsICookieService::BEHAVIOR_REJECT_TRACKER);
aWindow->GetExtantDoc()->CookieSettings()->GetCookieBehavior() ==
nsICookieService::BEHAVIOR_REJECT_TRACKER);
RuntimeService* runtime = RuntimeService::GetService(); RuntimeService* runtime = RuntimeService::GetService();
if (runtime) { if (runtime) {

Просмотреть файл

@ -55,6 +55,7 @@ support-files =
redirect_to_foreign.sjs redirect_to_foreign.sjs
rvals_worker.js rvals_worker.js
sharedWorker_sharedWorker.js sharedWorker_sharedWorker.js
sharedWorker_thirdparty_frame.html
simpleThread_worker.js simpleThread_worker.js
suspend_window.html suspend_window.html
suspend_worker.js suspend_worker.js
@ -172,9 +173,6 @@ skip-if = toolkit == 'android'
[test_rvals.html] [test_rvals.html]
[test_sharedWorker.html] [test_sharedWorker.html]
[test_sharedWorker_thirdparty.html] [test_sharedWorker_thirdparty.html]
support-files =
sharedWorker_thirdparty_frame.html
sharedWorker_thirdparty_window.html
[test_simpleThread.html] [test_simpleThread.html]
[test_suspend.html] [test_suspend.html]
[test_terminate.html] [test_terminate.html]

Просмотреть файл

@ -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>

Просмотреть файл

@ -11,18 +11,22 @@
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
</head> </head>
<body> <body>
<p id="display"></p>
<div id="content" style="display: none"></div>
<pre id="test">
<script class="testbody"> <script class="testbody">
function testThirdPartyFrame(name) { function testThirdPartyFrame(name) {
return new Promise(resolve => { return new Promise(resolve => {
// Let's use a window, loading the same origin, in order to have the new let frame = document.createElement('iframe');
// cookie-policy applied. frame.src =
let w = window.open("sharedWorker_thirdparty_window.html?name=" + name); 'http://example.org/tests/dom/workers/test/sharedWorker_thirdparty_frame.html?name=' + name;
document.body.appendChild(frame);
window.addEventListener('message', function messageListener(evt) { window.addEventListener('message', function messageListener(evt) {
if (evt.data.name !== name) { if (evt.data.name !== name) {
return; return;
} }
w.close(); frame.remove();
window.removeEventListener('message', messageListener); window.removeEventListener('message', messageListener);
resolve(evt.data.result); resolve(evt.data.result);
}); });
@ -51,5 +55,6 @@
}); });
</script> </script>
</pre>
</body> </body>
</html> </html>

Просмотреть файл

@ -6,99 +6,57 @@
// 2) with channel, but with no docshell parent // 2) with channel, but with no docshell parent
function run_test() { function run_test() {
Services.prefs.setBoolPref("network.cookieSettings.unblocked_for_testing", true);
// Create URIs and channels pointing to foo.com and bar.com. // Create URIs and channels pointing to foo.com and bar.com.
// We will use these to put foo.com into first and third party contexts. // We will use these to put foo.com into first and third party contexts.
let spec1 = "http://foo.com/foo.html"; var spec1 = "http://foo.com/foo.html";
let spec2 = "http://bar.com/bar.html"; var spec2 = "http://bar.com/bar.html";
let uri1 = NetUtil.newURI(spec1); var uri1 = NetUtil.newURI(spec1);
let uri2 = NetUtil.newURI(spec2); var uri2 = NetUtil.newURI(spec2);
var channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true});
var channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
// test with cookies enabled // test with cookies enabled
{ Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
Services.cookies.removeAll();
let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); Services.cookies.removeAll();
do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
Services.cookies.removeAll();
do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
Services.cookies.removeAll();
}
// test with third party cookies blocked // test with third party cookies blocked
{ Services.prefs.setIntPref("network.cookie.cookieBehavior", 1);
Services.prefs.setIntPref("network.cookie.cookieBehavior", 1); do_set_cookies(uri1, channel1, true, [0, 0, 0, 0]);
Services.cookies.removeAll();
let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); Services.cookies.removeAll();
do_set_cookies(uri1, channel1, true, [0, 0, 0, 0]);
Services.cookies.removeAll();
do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
Services.cookies.removeAll();
}
// Force the channel URI to be used when determining the originating URI of // Force the channel URI to be used when determining the originating URI of
// the channel. // the channel.
// test with third party cookies blocked var httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal);
var httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
httpchannel1.forceAllowThirdPartyCookie = true;
httpchannel2.forceAllowThirdPartyCookie = true;
// test with cookies enabled // test with cookies enabled
{ Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
Services.prefs.setIntPref("network.cookie.cookieBehavior", 0); do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
Services.cookies.removeAll();
let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal); Services.cookies.removeAll();
httpchannel1.forceAllowThirdPartyCookie = true;
let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
httpchannel2.forceAllowThirdPartyCookie = true;
do_set_cookies(uri1, channel1, true, [1, 2, 3, 4]);
Services.cookies.removeAll();
do_set_cookies(uri1, channel2, true, [1, 2, 3, 4]);
Services.cookies.removeAll();
}
// test with third party cookies blocked // test with third party cookies blocked
{ Services.prefs.setIntPref("network.cookie.cookieBehavior", 1);
Services.prefs.setIntPref("network.cookie.cookieBehavior", 1); do_set_cookies(uri1, channel1, true, [0, 1, 1, 2]);
Services.cookies.removeAll();
let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal); Services.cookies.removeAll();
httpchannel1.forceAllowThirdPartyCookie = true;
let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true});
let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
httpchannel2.forceAllowThirdPartyCookie = true;
do_set_cookies(uri1, channel1, true, [0, 1, 1, 2]);
Services.cookies.removeAll();
do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
Services.cookies.removeAll();
}
// test with third party cookies limited // test with third party cookies limited
{ Services.prefs.setIntPref("network.cookie.cookieBehavior", 3);
Services.prefs.setIntPref("network.cookie.cookieBehavior", 3); do_set_cookies(uri1, channel1, true, [0, 1, 2, 3]);
Services.cookies.removeAll();
let channel1 = NetUtil.newChannel({uri: uri1, loadUsingSystemPrincipal: true}); do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
let httpchannel1 = channel1.QueryInterface(Ci.nsIHttpChannelInternal); Services.cookies.removeAll();
httpchannel1.forceAllowThirdPartyCookie = true; do_set_single_http_cookie(uri1, channel1, 1);
do_set_cookies(uri1, channel2, true, [2, 3, 4, 5]);
let channel2 = NetUtil.newChannel({uri: uri2, loadUsingSystemPrincipal: true}); Services.cookies.removeAll();
let httpchannel2 = channel2.QueryInterface(Ci.nsIHttpChannelInternal);
httpchannel2.forceAllowThirdPartyCookie = true;
do_set_cookies(uri1, channel1, true, [0, 1, 2, 3]);
Services.cookies.removeAll();
do_set_cookies(uri1, channel2, true, [0, 0, 0, 0]);
Services.cookies.removeAll();
do_set_single_http_cookie(uri1, channel1, 1);
do_set_cookies(uri1, channel2, true, [2, 3, 4, 5]);
Services.cookies.removeAll();
}
} }

Просмотреть файл

@ -12,7 +12,6 @@
#include "mozilla/NullPrincipal.h" #include "mozilla/NullPrincipal.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h" #include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "mozilla/ipc/URIUtils.h" #include "mozilla/ipc/URIUtils.h"
#include "mozilla/net/CookieSettings.h"
#include "mozilla/net/NeckoChannelParams.h" #include "mozilla/net/NeckoChannelParams.h"
#include "ExpandedPrincipal.h" #include "ExpandedPrincipal.h"
#include "nsIScriptSecurityManager.h" #include "nsIScriptSecurityManager.h"
@ -461,14 +460,6 @@ nsresult LoadInfoToLoadInfoArgs(nsILoadInfo* aLoadInfo,
nsAutoString cspNonce; nsAutoString cspNonce;
Unused << NS_WARN_IF(NS_FAILED(aLoadInfo->GetCspNonce(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( *aOptionalLoadInfoArgs = LoadInfoArgs(
loadingPrincipalInfo, triggeringPrincipalInfo, principalToInheritInfo, loadingPrincipalInfo, triggeringPrincipalInfo, principalToInheritInfo,
sandboxedLoadingPrincipalInfo, topLevelPrincipalInfo, sandboxedLoadingPrincipalInfo, topLevelPrincipalInfo,
@ -499,7 +490,7 @@ nsresult LoadInfoToLoadInfoArgs(nsILoadInfo* aLoadInfo,
aLoadInfo->GetDocumentHasUserInteracted(), aLoadInfo->GetDocumentHasUserInteracted(),
aLoadInfo->GetDocumentHasLoaded(), cspNonce, aLoadInfo->GetDocumentHasLoaded(), cspNonce,
aLoadInfo->GetIsFromProcessingFrameAttributes(), aLoadInfo->GetIsFromProcessingFrameAttributes(),
aLoadInfo->GetOpenerPolicy(), cookieSettingsArgs); aLoadInfo->GetOpenerPolicy());
return NS_OK; return NS_OK;
} }
@ -628,15 +619,11 @@ nsresult LoadInfoArgsToLoadInfo(
loadInfoArgs.controller().get_IPCServiceWorkerDescriptor())); loadInfoArgs.controller().get_IPCServiceWorkerDescriptor()));
} }
nsCOMPtr<nsICookieSettings> cookieSettings;
CookieSettings::Deserialize(loadInfoArgs.cookieSettings(),
getter_AddRefs(cookieSettings));
RefPtr<mozilla::LoadInfo> loadInfo = new mozilla::LoadInfo( RefPtr<mozilla::LoadInfo> loadInfo = new mozilla::LoadInfo(
loadingPrincipal, triggeringPrincipal, principalToInherit, loadingPrincipal, triggeringPrincipal, principalToInherit,
sandboxedLoadingPrincipal, topLevelPrincipal, sandboxedLoadingPrincipal, topLevelPrincipal,
topLevelStorageAreaPrincipal, resultPrincipalURI, cookieSettings, topLevelStorageAreaPrincipal, resultPrincipalURI, clientInfo,
clientInfo, reservedClientInfo, initialClientInfo, controller, reservedClientInfo, initialClientInfo, controller,
loadInfoArgs.securityFlags(), loadInfoArgs.contentPolicyType(), loadInfoArgs.securityFlags(), loadInfoArgs.contentPolicyType(),
static_cast<LoadTainting>(loadInfoArgs.tainting()), static_cast<LoadTainting>(loadInfoArgs.tainting()),
loadInfoArgs.upgradeInsecureRequests(), loadInfoArgs.upgradeInsecureRequests(),
@ -679,7 +666,7 @@ void LoadInfoToParentLoadInfoForwarder(
false, // serviceWorkerTaintingSynthesized false, // serviceWorkerTaintingSynthesized
false, // documentHasUserInteracted false, // documentHasUserInteracted
false, // documentHasLoaded false, // documentHasLoaded
nsILoadInfo::OPENER_POLICY_NULL, void_t()); nsILoadInfo::OPENER_POLICY_NULL);
return; return;
} }
@ -695,23 +682,11 @@ void LoadInfoToParentLoadInfoForwarder(
nsILoadInfo::CrossOriginOpenerPolicy openerPolicy = nsILoadInfo::CrossOriginOpenerPolicy openerPolicy =
aLoadInfo->GetOpenerPolicy(); 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( *aForwarderArgsOut = ParentLoadInfoForwarderArgs(
aLoadInfo->GetAllowInsecureRedirectToDataURI(), ipcController, tainting, aLoadInfo->GetAllowInsecureRedirectToDataURI(), ipcController, tainting,
aLoadInfo->GetServiceWorkerTaintingSynthesized(), aLoadInfo->GetServiceWorkerTaintingSynthesized(),
aLoadInfo->GetDocumentHasUserInteracted(), aLoadInfo->GetDocumentHasUserInteracted(),
aLoadInfo->GetDocumentHasLoaded(), openerPolicy, cookieSettingsArgs); aLoadInfo->GetDocumentHasLoaded(), openerPolicy);
} }
nsresult MergeParentLoadInfoForwarder( nsresult MergeParentLoadInfoForwarder(
@ -748,19 +723,6 @@ nsresult MergeParentLoadInfoForwarder(
MOZ_ALWAYS_SUCCEEDS( MOZ_ALWAYS_SUCCEEDS(
aLoadInfo->SetDocumentHasLoaded(aForwarderArgs.documentHasLoaded())); 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; return NS_OK;
} }

Просмотреть файл

@ -1739,14 +1739,6 @@ VARCACHE_PREF(
bool, true bool, true
) )
// Allow CookieSettings to be unblocked for channels without a document.
// This is for testing only.
VARCACHE_PREF(
"network.cookieSettings.unblocked_for_testing",
network_cookieSettings_unblocked_for_testing,
bool, false
)
VARCACHE_PREF( VARCACHE_PREF(
"network.predictor.enable-hover-on-ssl", "network.predictor.enable-hover-on-ssl",
network_predictor_enable_hover_on_ssl, network_predictor_enable_hover_on_ssl,

Просмотреть файл

@ -13,17 +13,13 @@
#include "mozilla/dom/TabChild.h" #include "mozilla/dom/TabChild.h"
#include "mozilla/dom/ToJSValue.h" #include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/BrowsingContext.h" #include "mozilla/dom/BrowsingContext.h"
#include "mozilla/net/CookieSettings.h"
#include "mozilla/NullPrincipal.h" #include "mozilla/NullPrincipal.h"
#include "mozilla/StaticPrefs.h"
#include "mozIThirdPartyUtil.h" #include "mozIThirdPartyUtil.h"
#include "nsFrameLoader.h" #include "nsFrameLoader.h"
#include "nsFrameLoaderOwner.h" #include "nsFrameLoaderOwner.h"
#include "nsIContentSecurityPolicy.h" #include "nsIContentSecurityPolicy.h"
#include "nsIDocShell.h" #include "nsIDocShell.h"
#include "mozilla/dom/Document.h" #include "mozilla/dom/Document.h"
#include "nsCookiePermission.h"
#include "nsICookieService.h"
#include "nsIInterfaceRequestorUtils.h" #include "nsIInterfaceRequestorUtils.h"
#include "nsISupportsImpl.h" #include "nsISupportsImpl.h"
#include "nsISupportsUtils.h" #include "nsISupportsUtils.h"
@ -209,10 +205,6 @@ LoadInfo::LoadInfo(
} }
} }
} }
// Let's inherit the cookie behavior and permission from the parent
// document.
mCookieSettings = aLoadingContext->OwnerDoc()->CookieSettings();
} }
mInnerWindowID = aLoadingContext->OwnerDoc()->InnerWindowID(); mInnerWindowID = aLoadingContext->OwnerDoc()->InnerWindowID();
@ -282,17 +274,6 @@ LoadInfo::LoadInfo(
} }
} }
// Create a new CookieSettings for SharedWorkers and ServiceWorkers because
// they cannot inherit it from other contexts:
// - ServiceWorkers does not belong to any windows.
// - SharedWorkers belong to many windows which could have different
// CookieSettings objects.
if (!mCookieSettings &&
(aContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER ||
aContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER)) {
mCookieSettings = CookieSettings::Create();
}
// If CSP requires SRI (require-sri-for), then store that information // If CSP requires SRI (require-sri-for), then store that information
// in the loadInfo so we can enforce SRI before loading the subresource. // in the loadInfo so we can enforce SRI before loading the subresource.
if (!mEnforceSRI) { if (!mEnforceSRI) {
@ -445,11 +426,6 @@ LoadInfo::LoadInfo(nsPIDOMWindowOuter* aOuterWindow,
"chrome docshell shouldn't have mPrivateBrowsingId set."); "chrome docshell shouldn't have mPrivateBrowsingId set.");
} }
#endif #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) LoadInfo::LoadInfo(const LoadInfo& rhs)
@ -460,7 +436,6 @@ LoadInfo::LoadInfo(const LoadInfo& rhs)
mTopLevelPrincipal(rhs.mTopLevelPrincipal), mTopLevelPrincipal(rhs.mTopLevelPrincipal),
mTopLevelStorageAreaPrincipal(rhs.mTopLevelStorageAreaPrincipal), mTopLevelStorageAreaPrincipal(rhs.mTopLevelStorageAreaPrincipal),
mResultPrincipalURI(rhs.mResultPrincipalURI), mResultPrincipalURI(rhs.mResultPrincipalURI),
mCookieSettings(rhs.mCookieSettings),
mClientInfo(rhs.mClientInfo), mClientInfo(rhs.mClientInfo),
// mReservedClientSource must be handled specially during redirect // mReservedClientSource must be handled specially during redirect
// mReservedClientInfo must be handled specially during redirect // mReservedClientInfo must be handled specially during redirect
@ -519,7 +494,7 @@ LoadInfo::LoadInfo(
nsIPrincipal* aPrincipalToInherit, nsIPrincipal* aSandboxedLoadingPrincipal, nsIPrincipal* aPrincipalToInherit, nsIPrincipal* aSandboxedLoadingPrincipal,
nsIPrincipal* aTopLevelPrincipal, nsIPrincipal* aTopLevelPrincipal,
nsIPrincipal* aTopLevelStorageAreaPrincipal, nsIURI* aResultPrincipalURI, nsIPrincipal* aTopLevelStorageAreaPrincipal, nsIURI* aResultPrincipalURI,
nsICookieSettings* aCookieSettings, const Maybe<ClientInfo>& aClientInfo, const Maybe<ClientInfo>& aClientInfo,
const Maybe<ClientInfo>& aReservedClientInfo, const Maybe<ClientInfo>& aReservedClientInfo,
const Maybe<ClientInfo>& aInitialClientInfo, const Maybe<ClientInfo>& aInitialClientInfo,
const Maybe<ServiceWorkerDescriptor>& aController, const Maybe<ServiceWorkerDescriptor>& aController,
@ -551,7 +526,6 @@ LoadInfo::LoadInfo(
mTopLevelPrincipal(aTopLevelPrincipal), mTopLevelPrincipal(aTopLevelPrincipal),
mTopLevelStorageAreaPrincipal(aTopLevelStorageAreaPrincipal), mTopLevelStorageAreaPrincipal(aTopLevelStorageAreaPrincipal),
mResultPrincipalURI(aResultPrincipalURI), mResultPrincipalURI(aResultPrincipalURI),
mCookieSettings(aCookieSettings),
mClientInfo(aClientInfo), mClientInfo(aClientInfo),
mReservedClientInfo(aReservedClientInfo), mReservedClientInfo(aReservedClientInfo),
mInitialClientInfo(aInitialClientInfo), mInitialClientInfo(aInitialClientInfo),
@ -797,21 +771,6 @@ LoadInfo::GetCookiePolicy(uint32_t* aResult) {
return NS_OK; return NS_OK;
} }
NS_IMETHODIMP
LoadInfo::GetCookieSettings(nsICookieSettings** aCookieSettings) {
if (!mCookieSettings) {
if (StaticPrefs::network_cookieSettings_unblocked_for_testing()) {
mCookieSettings = CookieSettings::Create();
} else {
mCookieSettings = CookieSettings::CreateBlockingAll();
}
}
nsCOMPtr<nsICookieSettings> cookieSettings = mCookieSettings;
cookieSettings.forget(aCookieSettings);
return NS_OK;
}
void LoadInfo::SetIncludeCookiesSecFlag() { void LoadInfo::SetIncludeCookiesSecFlag() {
MOZ_ASSERT((mSecurityFlags & sCookiePolicyMask) == MOZ_ASSERT((mSecurityFlags & sCookiePolicyMask) ==
nsILoadInfo::SEC_COOKIES_DEFAULT); nsILoadInfo::SEC_COOKIES_DEFAULT);

Просмотреть файл

@ -19,7 +19,6 @@
#include "mozilla/dom/ClientInfo.h" #include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/ServiceWorkerDescriptor.h" #include "mozilla/dom/ServiceWorkerDescriptor.h"
class nsICookieSettings;
class nsINode; class nsINode;
class nsPIDOMWindowOuter; class nsPIDOMWindowOuter;
@ -71,7 +70,6 @@ class LoadInfo final : public nsILoadInfo {
// create an exact copy of the loadinfo // create an exact copy of the loadinfo
already_AddRefed<nsILoadInfo> Clone() const; already_AddRefed<nsILoadInfo> Clone() const;
// hands off!!! don't use CloneWithNewSecFlags unless you know // hands off!!! don't use CloneWithNewSecFlags unless you know
// exactly what you are doing - it should only be used within // exactly what you are doing - it should only be used within
// nsBaseChannel::Redirect() // nsBaseChannel::Redirect()
@ -98,7 +96,7 @@ class LoadInfo final : public nsILoadInfo {
nsIPrincipal* aSandboxedLoadingPrincipal, nsIPrincipal* aSandboxedLoadingPrincipal,
nsIPrincipal* aTopLevelPrincipal, nsIPrincipal* aTopLevelPrincipal,
nsIPrincipal* aTopLevelStorageAreaPrincipal, nsIPrincipal* aTopLevelStorageAreaPrincipal,
nsIURI* aResultPrincipalURI, nsICookieSettings* aCookieSettings, nsIURI* aResultPrincipalURI,
const Maybe<mozilla::dom::ClientInfo>& aClientInfo, const Maybe<mozilla::dom::ClientInfo>& aClientInfo,
const Maybe<mozilla::dom::ClientInfo>& aReservedClientInfo, const Maybe<mozilla::dom::ClientInfo>& aReservedClientInfo,
const Maybe<mozilla::dom::ClientInfo>& aInitialClientInfo, const Maybe<mozilla::dom::ClientInfo>& aInitialClientInfo,
@ -157,7 +155,6 @@ class LoadInfo final : public nsILoadInfo {
nsCOMPtr<nsIPrincipal> mTopLevelStorageAreaPrincipal; nsCOMPtr<nsIPrincipal> mTopLevelStorageAreaPrincipal;
nsCOMPtr<nsIURI> mResultPrincipalURI; nsCOMPtr<nsIURI> mResultPrincipalURI;
nsCOMPtr<nsICSPEventListener> mCSPEventListener; nsCOMPtr<nsICSPEventListener> mCSPEventListener;
nsCOMPtr<nsICookieSettings> mCookieSettings;
Maybe<mozilla::dom::ClientInfo> mClientInfo; Maybe<mozilla::dom::ClientInfo> mClientInfo;
UniquePtr<mozilla::dom::ClientSource> mReservedClientSource; UniquePtr<mozilla::dom::ClientSource> mReservedClientSource;

Просмотреть файл

@ -8,7 +8,6 @@
#include "nsIContentPolicy.idl" #include "nsIContentPolicy.idl"
interface nsIChannel; interface nsIChannel;
interface nsICookieSettings;
interface nsICSPEventListener; interface nsICSPEventListener;
interface nsINode; interface nsINode;
interface nsIPrincipal; interface nsIPrincipal;
@ -427,12 +426,6 @@ interface nsILoadInfo : nsISupports
*/ */
[infallible] readonly attribute unsigned long cookiePolicy; [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 * If forceInheritPrincipal is true, the data coming from the channel should
* inherit its principal, even when the data is loaded over http:// or another * inherit its principal, even when the data is loaded over http:// or another

Просмотреть файл

@ -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

Просмотреть файл

@ -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

Просмотреть файл

@ -14,7 +14,6 @@ XPIDL_SOURCES += [
'nsICookieManager.idl', 'nsICookieManager.idl',
'nsICookiePermission.idl', 'nsICookiePermission.idl',
'nsICookieService.idl', 'nsICookieService.idl',
'nsICookieSettings.idl',
] ]
XPIDL_MODULE = 'necko_cookie' XPIDL_MODULE = 'necko_cookie'
@ -23,13 +22,11 @@ if CONFIG['NECKO_COOKIES']:
EXPORTS.mozilla.net = [ EXPORTS.mozilla.net = [
'CookieServiceChild.h', 'CookieServiceChild.h',
'CookieServiceParent.h', 'CookieServiceParent.h',
'CookieSettings.h',
'nsCookieKey.h', 'nsCookieKey.h',
] ]
UNIFIED_SOURCES += [ UNIFIED_SOURCES += [
'CookieServiceChild.cpp', 'CookieServiceChild.cpp',
'CookieServiceParent.cpp', 'CookieServiceParent.cpp',
'CookieSettings.cpp',
'nsCookie.cpp', 'nsCookie.cpp',
] ]
# nsCookieService.cpp can't be unified because of symbol conflicts # nsCookieService.cpp can't be unified because of symbol conflicts
@ -37,7 +34,6 @@ if CONFIG['NECKO_COOKIES']:
'nsCookieService.cpp', 'nsCookieService.cpp',
] ]
LOCAL_INCLUDES += [ LOCAL_INCLUDES += [
'/extensions/cookie',
'/intl/uconv', '/intl/uconv',
] ]

Просмотреть файл

@ -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);
};

Просмотреть файл

@ -1,13 +1,5 @@
[DEFAULT] [DEFAULT]
support-files = support-files =
file_empty.html file_empty.html
file_empty.js
head.js
[browser_broadcastChannel.js]
[browser_domCache.js]
[browser_indexedDB.js]
[browser_originattributes.js] [browser_originattributes.js]
[browser_storage.js]
[browser_serviceWorker.js]
[browser_sharedWorker.js]

Просмотреть файл

@ -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();
}
};
});
}
});

Просмотреть файл

@ -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!"); });
},
});

Просмотреть файл

@ -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();
};
});
},
});

Просмотреть файл

@ -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));
},
});

Просмотреть файл

@ -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.");
}
},
});

Просмотреть файл

@ -1,41 +0,0 @@
CookiePolicyHelper.runTest("SessionStorage", {
cookieJarAccessAllowed: async w => {
try {
w.sessionStorage.foo = 42;
ok(true, "SessionStorage works");
} catch (e) {
ok(false, "SessionStorage works");
}
},
cookieJarAccessDenied: async w => {
try {
w.sessionStorage.foo = 42;
ok(false, "SessionStorage doesn't work");
} catch (e) {
ok(true, "SessionStorage doesn't work");
is(e.name, "SecurityError", "We want a security error message.");
}
},
});
CookiePolicyHelper.runTest("LocalStorage", {
cookieJarAccessAllowed: async w => {
try {
w.localStorage.foo = 42;
ok(true, "LocalStorage works");
} catch (e) {
ok(false, "LocalStorage works");
}
},
cookieJarAccessDenied: async w => {
try {
w.localStorage.foo = 42;
ok(false, "LocalStorage doesn't work");
} catch (e) {
ok(true, "LocalStorage doesn't work");
is(e.name, "TypeError", "We want a security error message.");
}
},
});

Просмотреть файл

@ -1 +0,0 @@
/* nothing here */

Просмотреть файл

@ -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);
});
});
},
};

Просмотреть файл

@ -27,30 +27,6 @@ using nsILoadInfo::CrossOriginOpenerPolicy from "ipc/IPCMessageUtils.h";
namespace mozilla { namespace mozilla {
namespace net { 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 // Preferrer alternative data type
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -149,8 +125,6 @@ struct LoadInfoArgs
nsString cspNonce; nsString cspNonce;
bool isFromProcessingFrameAttributes; bool isFromProcessingFrameAttributes;
CrossOriginOpenerPolicy openerPolicy; CrossOriginOpenerPolicy openerPolicy;
CookieSettingsArgs cookieSettings;
}; };
/** /**
@ -193,8 +167,6 @@ struct ParentLoadInfoForwarderArgs
CrossOriginOpenerPolicy openerPolicy; CrossOriginOpenerPolicy openerPolicy;
OptionalCookieSettingsArgs cookieSettings;
// IMPORTANT: when you add new properites here you must also update // IMPORTANT: when you add new properites here you must also update
// LoadInfoToParentLoadInfoForwarder and MergeParentLoadInfoForwarder // LoadInfoToParentLoadInfoForwarder and MergeParentLoadInfoForwarder
// in BackgroundUtils.cpp/.h! // in BackgroundUtils.cpp/.h!

Просмотреть файл

@ -156,51 +156,57 @@ void CreatePermissionKey(const nsCString& aTrackingOrigin,
// This internal method returns ACCESS_DENY if the access is denied, // This internal method returns ACCESS_DENY if the access is denied,
// ACCESS_DEFAULT if unknown, some other access code if granted. // ACCESS_DEFAULT if unknown, some other access code if granted.
uint32_t CheckCookiePermissionForPrincipal(nsICookieSettings* aCookieSettings, nsCookieAccess CheckCookiePermissionForPrincipal(nsIPrincipal* aPrincipal) {
nsIPrincipal* aPrincipal) { nsCookieAccess access = nsICookiePermission::ACCESS_DEFAULT;
MOZ_ASSERT(aCookieSettings);
MOZ_ASSERT(aPrincipal);
uint32_t cookiePermission = nsICookiePermission::ACCESS_DEFAULT;
if (!aPrincipal->GetIsCodebasePrincipal()) { if (!aPrincipal->GetIsCodebasePrincipal()) {
return cookiePermission; return access;
} }
nsresult rv = nsCOMPtr<nsICookiePermission> cps = nsCookiePermission::GetOrCreate();
aCookieSettings->CookiePermission(aPrincipal, &cookiePermission);
nsresult rv = cps->CanAccess(aPrincipal, &access);
if (NS_WARN_IF(NS_FAILED(rv))) { if (NS_WARN_IF(NS_FAILED(rv))) {
return nsICookiePermission::ACCESS_DEFAULT; return nsICookiePermission::ACCESS_DEFAULT;
} }
// If we have a custom cookie permission, let's use it. // If we have a custom cookie permission, let's use it.
return cookiePermission; return access;
} }
int32_t CookiesBehavior(Document* aTopLevelDocument, // This internal method returns ACCESS_DENY if the access is denied,
Document* a3rdPartyDocument) { // ACCESS_DEFAULT if unknown, some other access code if granted.
MOZ_ASSERT(aTopLevelDocument); nsCookieAccess CheckCookiePermissionForURI(nsIURI* aURI) {
MOZ_ASSERT(a3rdPartyDocument); 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 // WebExtensions principals always get BEHAVIOR_ACCEPT as cookieBehavior
// (See Bug 1406675 for rationale). // (See Bug 1406675 for rationale).
if (BasePrincipal::Cast(aTopLevelDocument->NodePrincipal())->AddonPolicy()) { if (BasePrincipal::Cast(aTopLevelPrincipal)->AddonPolicy()) {
return nsICookieService::BEHAVIOR_ACCEPT; return nsICookieService::BEHAVIOR_ACCEPT;
} }
if (BasePrincipal::Cast(a3rdPartyDocument->NodePrincipal())->AddonPolicy()) { if (a3rdPartyPrincipal &&
BasePrincipal::Cast(a3rdPartyPrincipal)->AddonPolicy()) {
return nsICookieService::BEHAVIOR_ACCEPT; return nsICookieService::BEHAVIOR_ACCEPT;
} }
return a3rdPartyDocument->CookieSettings()->GetCookieBehavior(); return StaticPrefs::network_cookie_cookieBehavior();
} }
int32_t CookiesBehavior(nsILoadInfo* aLoadInfo, int32_t CookiesBehavior(nsIPrincipal* aTopLevelPrincipal,
nsIPrincipal* aTopLevelPrincipal,
nsIURI* a3rdPartyURI) { nsIURI* a3rdPartyURI) {
MOZ_ASSERT(aLoadInfo);
MOZ_ASSERT(aTopLevelPrincipal);
MOZ_ASSERT(a3rdPartyURI);
// WebExtensions principals always get BEHAVIOR_ACCEPT as cookieBehavior // WebExtensions principals always get BEHAVIOR_ACCEPT as cookieBehavior
// (See Bug 1406675 for rationale). // (See Bug 1406675 for rationale).
if (BasePrincipal::Cast(aTopLevelPrincipal)->AddonPolicy()) { if (BasePrincipal::Cast(aTopLevelPrincipal)->AddonPolicy()) {
@ -209,30 +215,13 @@ int32_t CookiesBehavior(nsILoadInfo* aLoadInfo,
// This is semantically equivalent to the principal having a AddonPolicy(). // This is semantically equivalent to the principal having a AddonPolicy().
bool is3rdPartyMozExt = false; bool is3rdPartyMozExt = false;
if (NS_SUCCEEDED( if (a3rdPartyURI &&
NS_SUCCEEDED(
a3rdPartyURI->SchemeIs("moz-extension", &is3rdPartyMozExt)) && a3rdPartyURI->SchemeIs("moz-extension", &is3rdPartyMozExt)) &&
is3rdPartyMozExt) { is3rdPartyMozExt) {
return nsICookieService::BEHAVIOR_ACCEPT; 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(); return StaticPrefs::network_cookie_cookieBehavior();
} }
@ -1077,50 +1066,31 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
aURI); aURI);
nsGlobalWindowInner* innerWindow = nsGlobalWindowInner::Cast(aWindow); nsGlobalWindowInner* innerWindow = nsGlobalWindowInner::Cast(aWindow);
Document* document = innerWindow->GetExtantDoc(); nsIPrincipal* windowPrincipal = innerWindow->GetPrincipal();
if (!document) { if (!windowPrincipal) {
LOG(("Our window has no document")); LOG(("Our window has no principal"));
return false; return false;
} }
nsGlobalWindowOuter* outerWindow = nsIPrincipal* toplevelPrincipal = innerWindow->GetTopLevelPrincipal();
nsGlobalWindowOuter::Cast(aWindow->GetOuterWindow()); if (!toplevelPrincipal) {
if (!outerWindow) { // We are already the top-level principal. Let's use the window's principal.
LOG(("Our window has no outer window")); LOG(
return false; ("Our inner window lacks a top-level principal, use the window's "
"principal instead"));
toplevelPrincipal = windowPrincipal;
} }
nsCOMPtr<nsPIDOMWindowOuter> topOuterWindow = outerWindow->GetTop(); MOZ_ASSERT(toplevelPrincipal);
nsGlobalWindowOuter* topWindow = nsGlobalWindowOuter::Cast(topOuterWindow);
if (NS_WARN_IF(!topWindow)) {
LOG(("No top outer window"));
return false;
}
nsPIDOMWindowInner* topInnerWindow = topWindow->GetCurrentInnerWindow(); nsCookieAccess access = CheckCookiePermissionForPrincipal(toplevelPrincipal);
if (NS_WARN_IF(!topInnerWindow)) { if (access != nsICookiePermission::ACCESS_DEFAULT) {
LOG(("No top inner window."));
return false;
}
Document* toplevelDocument = topInnerWindow->GetExtantDoc();
if (!toplevelDocument) {
LOG(("No top level document."));
return false;
}
MOZ_ASSERT(toplevelDocument);
uint32_t cookiePermission = CheckCookiePermissionForPrincipal(
toplevelDocument->CookieSettings(), toplevelDocument->NodePrincipal());
if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
LOG( LOG(
("CheckCookiePermissionForPrincipal() returned a non-default access " ("CheckCookiePermissionForPrincipal() returned a non-default access "
"code (%d) for top-level window's principal, returning %s", "code (%d) for top-level window's principal, returning %s",
int(cookiePermission), int(access),
cookiePermission != nsICookiePermission::ACCESS_DENY ? "success" access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
: "failure")); if (access != nsICookiePermission::ACCESS_DENY) {
if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
return true; return true;
} }
@ -1129,16 +1099,14 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
return false; return false;
} }
cookiePermission = CheckCookiePermissionForPrincipal( access = CheckCookiePermissionForPrincipal(windowPrincipal);
toplevelDocument->CookieSettings(), document->NodePrincipal()); if (access != nsICookiePermission::ACCESS_DEFAULT) {
if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
LOG( LOG(
("CheckCookiePermissionForPrincipal() returned a non-default access " ("CheckCookiePermissionForPrincipal() returned a non-default access "
"code (%d) for window's principal, returning %s", "code (%d) for window's principal, returning %s",
int(cookiePermission), int(access),
cookiePermission != nsICookiePermission::ACCESS_DENY ? "success" access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
: "failure")); if (access != nsICookiePermission::ACCESS_DENY) {
if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
return true; return true;
} }
@ -1147,7 +1115,7 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
return false; return false;
} }
int32_t behavior = CookiesBehavior(toplevelDocument, document); int32_t behavior = CookiesBehavior(toplevelPrincipal, windowPrincipal);
if (behavior == nsICookieService::BEHAVIOR_ACCEPT) { if (behavior == nsICookieService::BEHAVIOR_ACCEPT) {
LOG(("The cookie behavior pref mandates accepting all cookies!")); LOG(("The cookie behavior pref mandates accepting all cookies!"));
return true; return true;
@ -1226,6 +1194,26 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
return false; 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; nsAutoCString type;
CreatePermissionKey(trackingOrigin, grantedOrigin, type); CreatePermissionKey(trackingOrigin, grantedOrigin, type);
@ -1241,7 +1229,8 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
} }
uint32_t result = 0; uint32_t result = 0;
rv = permManager->TestPermissionFromPrincipal(parentPrincipal, type, &result); rv = permManager->TestPermissionWithoutDefaultsFromPrincipal(parentPrincipal,
type, &result);
if (NS_WARN_IF(NS_FAILED(rv))) { if (NS_WARN_IF(NS_FAILED(rv))) {
LOG(("Failed to test the permission")); LOG(("Failed to test the permission"));
return false; return false;
@ -1272,10 +1261,6 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
aRejectedReason = &rejectedReason; aRejectedReason = &rejectedReason;
} }
nsIScriptSecurityManager* ssm =
nsScriptSecurityManager::GetScriptSecurityManager();
MOZ_ASSERT(ssm);
nsCOMPtr<nsIURI> channelURI; nsCOMPtr<nsIURI> channelURI;
nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI)); nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(channelURI));
if (NS_FAILED(rv)) { if (NS_FAILED(rv)) {
@ -1311,6 +1296,8 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
bool isDocument = false; bool isDocument = false;
rv = aChannel->GetIsMainDocumentChannel(&isDocument); rv = aChannel->GetIsMainDocumentChannel(&isDocument);
if (NS_SUCCEEDED(rv) && isDocument) { if (NS_SUCCEEDED(rv) && isDocument) {
nsIScriptSecurityManager* ssm =
nsScriptSecurityManager::GetScriptSecurityManager();
rv = ssm->GetChannelResultPrincipal(aChannel, rv = ssm->GetChannelResultPrincipal(aChannel,
getter_AddRefs(toplevelPrincipal)); getter_AddRefs(toplevelPrincipal));
if (NS_SUCCEEDED(rv)) { if (NS_SUCCEEDED(rv)) {
@ -1338,25 +1325,14 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
return false; return false;
} }
nsCOMPtr<nsICookieSettings> cookieSettings; nsCookieAccess access = CheckCookiePermissionForPrincipal(toplevelPrincipal);
rv = loadInfo->GetCookieSettings(getter_AddRefs(cookieSettings)); if (access != nsICookiePermission::ACCESS_DEFAULT) {
if (NS_WARN_IF(NS_FAILED(rv))) {
LOG(
("Failed to get the cookie settings from the loadinfo, bail out "
"early"));
return true;
}
uint32_t cookiePermission =
CheckCookiePermissionForPrincipal(cookieSettings, toplevelPrincipal);
if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
LOG( LOG(
("CheckCookiePermissionForPrincipal() returned a non-default access " ("CheckCookiePermissionForPrincipal() returned a non-default access "
"code (%d) for top-level window's principal, returning %s", "code (%d) for top-level window's principal, returning %s",
int(cookiePermission), int(access),
cookiePermission != nsICookiePermission::ACCESS_DENY ? "success" access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
: "failure")); if (access != nsICookiePermission::ACCESS_DENY) {
if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
return true; return true;
} }
@ -1365,24 +1341,19 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
return false; return false;
} }
nsCOMPtr<nsIPrincipal> channelPrincipal; if (NS_WARN_IF(NS_FAILED(rv) || !channelURI)) {
rv = ssm->GetChannelResultPrincipal(aChannel,
getter_AddRefs(channelPrincipal));
if (NS_WARN_IF(NS_FAILED(rv))) {
LOG(("No channel principal, bail out early")); LOG(("No channel principal, bail out early"));
return false; return false;
} }
cookiePermission = access = CheckCookiePermissionForURI(channelURI);
CheckCookiePermissionForPrincipal(cookieSettings, channelPrincipal); if (access != nsICookiePermission::ACCESS_DEFAULT) {
if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) {
LOG( LOG(
("CheckCookiePermissionForPrincipal() returned a non-default access " ("CheckCookiePermissionForPrincipal() returned a non-default access "
"code (%d) for channel's principal, returning %s", "code (%d) for channel's principal, returning %s",
int(cookiePermission), int(access),
cookiePermission != nsICookiePermission::ACCESS_DENY ? "success" access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
: "failure")); if (access != nsICookiePermission::ACCESS_DENY) {
if (cookiePermission != nsICookiePermission::ACCESS_DENY) {
return true; return true;
} }
@ -1391,12 +1362,7 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
return false; return false;
} }
if (!channelURI) { int32_t behavior = CookiesBehavior(toplevelPrincipal, channelURI);
LOG(("No channel uri, bail out early"));
return false;
}
int32_t behavior = CookiesBehavior(loadInfo, toplevelPrincipal, channelURI);
if (behavior == nsICookieService::BEHAVIOR_ACCEPT) { if (behavior == nsICookieService::BEHAVIOR_ACCEPT) {
LOG(("The cookie behavior pref mandates accepting all cookies!")); LOG(("The cookie behavior pref mandates accepting all cookies!"));
return true; return true;
@ -1531,17 +1497,13 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
nsIPrincipal* aPrincipal) { nsIPrincipal* aPrincipal) {
MOZ_ASSERT(aPrincipal); MOZ_ASSERT(aPrincipal);
nsCookieAccess access = nsICookiePermission::ACCESS_DEFAULT; nsCookieAccess access = CheckCookiePermissionForPrincipal(aPrincipal);
if (aPrincipal->GetIsCodebasePrincipal()) {
nsCOMPtr<nsICookiePermission> cps = nsCookiePermission::GetOrCreate();
Unused << NS_WARN_IF(NS_FAILED(cps->CanAccess(aPrincipal, &access)));
}
if (access != nsICookiePermission::ACCESS_DEFAULT) { if (access != nsICookiePermission::ACCESS_DEFAULT) {
return access != nsICookiePermission::ACCESS_DENY; return access != nsICookiePermission::ACCESS_DENY;
} }
int32_t behavior = CookiesBehavior(aPrincipal); int32_t behavior =
CookiesBehavior(aPrincipal, static_cast<nsIPrincipal*>(nullptr));
return behavior != nsICookieService::BEHAVIOR_REJECT; return behavior != nsICookieService::BEHAVIOR_REJECT;
} }
@ -1555,14 +1517,7 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
aFirstPartyWindow, _spec), aFirstPartyWindow, _spec),
aURI); aURI);
Document* parentDocument = if (StaticPrefs::network_cookie_cookieBehavior() !=
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() !=
nsICookieService::BEHAVIOR_REJECT_TRACKER) { nsICookieService::BEHAVIOR_REJECT_TRACKER) {
LOG(("Disabled by the pref (%d), bail out early", LOG(("Disabled by the pref (%d), bail out early",
StaticPrefs::network_cookie_cookieBehavior())); StaticPrefs::network_cookie_cookieBehavior()));
@ -1579,16 +1534,21 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
return true; return true;
} }
uint32_t cookiePermission = CheckCookiePermissionForPrincipal( nsCOMPtr<nsIPrincipal> parentPrincipal =
parentDocument->CookieSettings(), parentDocument->NodePrincipal()); nsGlobalWindowInner::Cast(aFirstPartyWindow)->GetPrincipal();
if (cookiePermission != nsICookiePermission::ACCESS_DEFAULT) { 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( LOG(
("CheckCookiePermissionForPrincipal() returned a non-default access " ("CheckCookiePermissionForPrincipal() returned a non-default access "
"code (%d), returning %s", "code (%d), returning %s",
int(cookiePermission), int(access),
cookiePermission != nsICookiePermission::ACCESS_DENY ? "success" access != nsICookiePermission::ACCESS_DENY ? "success" : "failure"));
: "failure")); return access != nsICookiePermission::ACCESS_DENY;
return cookiePermission != nsICookiePermission::ACCESS_DENY;
} }
nsAutoCString origin; nsAutoCString origin;
@ -1608,8 +1568,8 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
} }
uint32_t result = 0; uint32_t result = 0;
rv = permManager->TestPermissionWithoutDefaultsFromPrincipal( rv = permManager->TestPermissionWithoutDefaultsFromPrincipal(parentPrincipal,
parentDocument->NodePrincipal(), type, &result); type, &result);
if (NS_WARN_IF(NS_FAILED(rv))) { if (NS_WARN_IF(NS_FAILED(rv))) {
LOG(("Failed to test the permission")); LOG(("Failed to test the permission"));
return false; return false;
@ -1617,8 +1577,7 @@ bool AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(
if (MOZ_LOG_TEST(gAntiTrackingLog, LogLevel::Debug)) { if (MOZ_LOG_TEST(gAntiTrackingLog, LogLevel::Debug)) {
nsCOMPtr<nsIURI> parentPrincipalURI; nsCOMPtr<nsIURI> parentPrincipalURI;
Unused << parentDocument->NodePrincipal()->GetURI( Unused << parentPrincipal->GetURI(getter_AddRefs(parentPrincipalURI));
getter_AddRefs(parentPrincipalURI));
LOG_SPEC( LOG_SPEC(
("Testing permission type %s for %s resulted in %d (%s)", type.get(), ("Testing permission type %s for %s resulted in %d (%s)", type.get(),
_spec, int(result), _spec, int(result),

Просмотреть файл

@ -267,6 +267,43 @@ add_task(async function testUserInteractionHeuristic() {
}); });
}); });
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"); info("Removing the tab");
BrowserTestUtils.removeTab(tab); BrowserTestUtils.removeTab(tab);
}); });