1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 sw=2 et tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/OriginAttributes.h"
8 #include "mozilla/Assertions.h"
9 #include "mozilla/Preferences.h"
10 #include "mozilla/dom/BlobURLProtocolHandler.h"
11 #include "mozilla/dom/quota/QuotaManager.h"
12 #include "nsIEffectiveTLDService.h"
15 #include "nsNetUtil.h"
17 #include "nsURLHelper.h"
19 static const char kSourceChar
= ':';
20 static const char kSanitizedChar
= '+';
24 static void MakeTopLevelInfo(const nsACString
& aScheme
, const nsACString
& aHost
,
25 int32_t aPort
, bool aUseSite
,
26 nsAString
& aTopLevelInfo
) {
28 aTopLevelInfo
.Assign(NS_ConvertUTF8toUTF16(aHost
));
32 // Note: If you change the serialization of the partition-key, please update
33 // StoragePrincipalHelper.cpp too.
36 site
.AssignLiteral("(");
42 site
.AppendInt(aPort
);
44 site
.AppendLiteral(")");
46 aTopLevelInfo
.Assign(NS_ConvertUTF8toUTF16(site
));
49 static void MakeTopLevelInfo(const nsACString
& aScheme
, const nsACString
& aHost
,
50 bool aUseSite
, nsAString
& aTopLevelInfo
) {
51 MakeTopLevelInfo(aScheme
, aHost
, -1, aUseSite
, aTopLevelInfo
);
54 static void PopulateTopLevelInfoFromURI(const bool aIsTopLevelDocument
,
55 nsIURI
* aURI
, bool aIsFirstPartyEnabled
,
56 bool aForced
, bool aUseSite
,
57 nsString
OriginAttributes::*aTarget
,
58 OriginAttributes
& aOriginAttributes
) {
65 // If the prefs are off or this is not a top level load, bail out.
66 if ((!aIsFirstPartyEnabled
|| !aIsTopLevelDocument
) && !aForced
) {
70 nsAString
& topLevelInfo
= aOriginAttributes
.*aTarget
;
73 rv
= aURI
->GetScheme(scheme
);
74 NS_ENSURE_SUCCESS_VOID(rv
);
76 if (scheme
.EqualsLiteral("about")) {
77 MakeTopLevelInfo(scheme
, nsLiteralCString(ABOUT_URI_FIRST_PARTY_DOMAIN
),
78 aUseSite
, topLevelInfo
);
82 // If a null principal URI was provided, extract the UUID portion of the URI
83 // to use for the first-party domain.
84 if (scheme
.EqualsLiteral("moz-nullprincipal")) {
85 // Get the UUID portion of the URI, ignoring the precursor principal.
86 nsAutoCString filePath
;
87 rv
= aURI
->GetFilePath(filePath
);
88 MOZ_ASSERT(NS_SUCCEEDED(rv
));
89 // Remove the `{}` characters from both ends.
90 filePath
.Mid(filePath
, 1, filePath
.Length() - 2);
91 filePath
.AppendLiteral(".mozilla");
92 // Store the generated file path.
93 topLevelInfo
= NS_ConvertUTF8toUTF16(filePath
);
97 // Add-on principals should never get any first-party domain
98 // attributes in order to guarantee their storage integrity when switching
100 if (scheme
.EqualsLiteral("moz-extension")) {
104 nsCOMPtr
<nsIPrincipal
> blobPrincipal
;
105 if (dom::BlobURLProtocolHandler::GetBlobURLPrincipal(
106 aURI
, getter_AddRefs(blobPrincipal
))) {
107 MOZ_ASSERT(blobPrincipal
);
108 topLevelInfo
= blobPrincipal
->OriginAttributesRef().*aTarget
;
112 nsCOMPtr
<nsIEffectiveTLDService
> tldService
=
113 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID
);
114 MOZ_ASSERT(tldService
);
115 NS_ENSURE_TRUE_VOID(tldService
);
117 nsAutoCString baseDomain
;
118 rv
= tldService
->GetBaseDomain(aURI
, 0, baseDomain
);
119 if (NS_SUCCEEDED(rv
)) {
120 MakeTopLevelInfo(scheme
, baseDomain
, aUseSite
, topLevelInfo
);
124 // Saving before rv is overwritten.
125 bool isIpAddress
= (rv
== NS_ERROR_HOST_IS_IP_ADDRESS
);
126 bool isInsufficientDomainLevels
= (rv
== NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS
);
129 rv
= aURI
->GetPort(&port
);
130 NS_ENSURE_SUCCESS_VOID(rv
);
133 rv
= aURI
->GetHost(host
);
134 NS_ENSURE_SUCCESS_VOID(rv
);
137 // If the host is an IPv4/IPv6 address, we still accept it as a
138 // valid topLevelInfo.
139 nsAutoCString ipAddr
;
141 if (net_IsValidIPv6Addr(host
)) {
142 // According to RFC2732, the host of an IPv6 address should be an
143 // IPv6reference. The GetHost() of nsIURI will only return the IPv6
144 // address. So, we need to convert it back to IPv6reference here.
145 ipAddr
.AssignLiteral("[");
147 ipAddr
.AppendLiteral("]");
152 MakeTopLevelInfo(scheme
, ipAddr
, port
, aUseSite
, topLevelInfo
);
157 MakeTopLevelInfo(scheme
, host
, port
, aUseSite
, topLevelInfo
);
161 if (isInsufficientDomainLevels
) {
162 nsAutoCString publicSuffix
;
163 rv
= tldService
->GetPublicSuffix(aURI
, publicSuffix
);
164 if (NS_SUCCEEDED(rv
)) {
165 MakeTopLevelInfo(scheme
, publicSuffix
, port
, aUseSite
, topLevelInfo
);
171 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument
,
172 nsIURI
* aURI
, bool aForced
) {
173 PopulateTopLevelInfoFromURI(
174 aIsTopLevelDocument
, aURI
, IsFirstPartyEnabled(), aForced
,
175 StaticPrefs::privacy_firstparty_isolate_use_site(),
176 &OriginAttributes::mFirstPartyDomain
, *this);
179 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument
,
180 const nsACString
& aDomain
) {
181 SetFirstPartyDomain(aIsTopLevelDocument
, NS_ConvertUTF8toUTF16(aDomain
));
184 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument
,
185 const nsAString
& aDomain
,
187 // If the pref is off or this is not a top level load, bail out.
188 if ((!IsFirstPartyEnabled() || !aIsTopLevelDocument
) && !aForced
) {
192 mFirstPartyDomain
= aDomain
;
195 void OriginAttributes::SetPartitionKey(nsIURI
* aURI
) {
196 PopulateTopLevelInfoFromURI(
197 false /* aIsTopLevelDocument */, aURI
, IsFirstPartyEnabled(),
198 true /* aForced */, StaticPrefs::privacy_dynamic_firstparty_use_site(),
199 &OriginAttributes::mPartitionKey
, *this);
202 void OriginAttributes::SetPartitionKey(const nsACString
& aDomain
) {
203 SetPartitionKey(NS_ConvertUTF8toUTF16(aDomain
));
206 void OriginAttributes::SetPartitionKey(const nsAString
& aDomain
) {
207 mPartitionKey
= aDomain
;
210 void OriginAttributes::CreateSuffix(nsACString
& aStr
) const {
215 // Important: While serializing any string-valued attributes, perform a
216 // release-mode assertion to make sure that they don't contain characters that
217 // will break the quota manager when it uses the serialization for file
221 if (mInIsolatedMozBrowser
) {
222 params
.Set(u
"inBrowser"_ns
, u
"1"_ns
);
225 if (mUserContextId
!= nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID
) {
227 value
.AppendInt(mUserContextId
);
228 params
.Set(u
"userContextId"_ns
, value
);
231 if (mPrivateBrowsingId
) {
233 value
.AppendInt(mPrivateBrowsingId
);
234 params
.Set(u
"privateBrowsingId"_ns
, value
);
237 if (!mFirstPartyDomain
.IsEmpty()) {
238 nsAutoString
sanitizedFirstPartyDomain(mFirstPartyDomain
);
239 sanitizedFirstPartyDomain
.ReplaceChar(kSourceChar
, kSanitizedChar
);
241 params
.Set(u
"firstPartyDomain"_ns
, sanitizedFirstPartyDomain
);
244 if (!mGeckoViewSessionContextId
.IsEmpty()) {
245 nsAutoString
sanitizedGeckoViewUserContextId(mGeckoViewSessionContextId
);
246 sanitizedGeckoViewUserContextId
.ReplaceChar(
247 dom::quota::QuotaManager::kReplaceChars16
, kSanitizedChar
);
249 params
.Set(u
"geckoViewUserContextId"_ns
, sanitizedGeckoViewUserContextId
);
252 if (!mPartitionKey
.IsEmpty()) {
253 nsAutoString
sanitizedPartitionKey(mPartitionKey
);
254 sanitizedPartitionKey
.ReplaceChar(kSourceChar
, kSanitizedChar
);
256 params
.Set(u
"partitionKey"_ns
, sanitizedPartitionKey
);
261 params
.Serialize(value
, true);
262 if (!value
.IsEmpty()) {
263 aStr
.AppendLiteral("^");
264 aStr
.Append(NS_ConvertUTF16toUTF8(value
));
267 // In debug builds, check the whole string for illegal characters too (just in
272 MOZ_ASSERT(str
.FindCharInSet(dom::quota::QuotaManager::kReplaceChars
) ==
277 already_AddRefed
<nsAtom
> OriginAttributes::CreateSuffixAtom() const {
278 nsAutoCString suffix
;
279 CreateSuffix(suffix
);
280 return NS_Atomize(suffix
);
283 void OriginAttributes::CreateAnonymizedSuffix(nsACString
& aStr
) const {
284 OriginAttributes attrs
= *this;
286 if (!attrs
.mFirstPartyDomain
.IsEmpty()) {
287 attrs
.mFirstPartyDomain
.AssignLiteral("_anonymizedFirstPartyDomain_");
290 if (!attrs
.mPartitionKey
.IsEmpty()) {
291 attrs
.mPartitionKey
.AssignLiteral("_anonymizedPartitionKey_");
294 attrs
.CreateSuffix(aStr
);
297 bool OriginAttributes::PopulateFromSuffix(const nsACString
& aStr
) {
298 if (aStr
.IsEmpty()) {
302 if (aStr
[0] != '^') {
306 // If a non-default mPrivateBrowsingId is passed and is not present in the
307 // suffix, then it will retain the id when it should be default according
308 // to the suffix. Set to default before iterating to fix this.
309 mPrivateBrowsingId
= nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID
;
311 // Checking that we are in a pristine state
313 MOZ_RELEASE_ASSERT(mUserContextId
== 0);
314 MOZ_RELEASE_ASSERT(mPrivateBrowsingId
== 0);
315 MOZ_RELEASE_ASSERT(mFirstPartyDomain
.IsEmpty());
316 MOZ_RELEASE_ASSERT(mGeckoViewSessionContextId
.IsEmpty());
317 MOZ_RELEASE_ASSERT(mPartitionKey
.IsEmpty());
319 return URLParams::Parse(
320 Substring(aStr
, 1, aStr
.Length() - 1),
321 [this](const nsAString
& aName
, const nsAString
& aValue
) {
322 if (aName
.EqualsLiteral("inBrowser")) {
323 if (!aValue
.EqualsLiteral("1")) {
327 mInIsolatedMozBrowser
= true;
331 if (aName
.EqualsLiteral("addonId") || aName
.EqualsLiteral("appId")) {
332 // No longer supported. Silently ignore so that legacy origin strings
333 // don't cause failures.
337 if (aName
.EqualsLiteral("userContextId")) {
339 int64_t val
= aValue
.ToInteger64(&rv
);
340 NS_ENSURE_SUCCESS(rv
, false);
341 NS_ENSURE_TRUE(val
<= UINT32_MAX
, false);
342 mUserContextId
= static_cast<uint32_t>(val
);
347 if (aName
.EqualsLiteral("privateBrowsingId")) {
349 int64_t val
= aValue
.ToInteger64(&rv
);
350 NS_ENSURE_SUCCESS(rv
, false);
351 NS_ENSURE_TRUE(val
>= 0 && val
<= UINT32_MAX
, false);
352 mPrivateBrowsingId
= static_cast<uint32_t>(val
);
357 if (aName
.EqualsLiteral("firstPartyDomain")) {
358 nsAutoString
firstPartyDomain(aValue
);
359 firstPartyDomain
.ReplaceChar(kSanitizedChar
, kSourceChar
);
360 mFirstPartyDomain
.Assign(firstPartyDomain
);
364 if (aName
.EqualsLiteral("geckoViewUserContextId")) {
365 mGeckoViewSessionContextId
.Assign(aValue
);
369 if (aName
.EqualsLiteral("partitionKey")) {
370 nsAutoString
partitionKey(aValue
);
371 partitionKey
.ReplaceChar(kSanitizedChar
, kSourceChar
);
372 mPartitionKey
.Assign(partitionKey
);
376 // No other attributes are supported.
381 bool OriginAttributes::PopulateFromOrigin(const nsACString
& aOrigin
,
382 nsACString
& aOriginNoSuffix
) {
383 // RFindChar is only available on nsCString.
384 nsCString
origin(aOrigin
);
385 int32_t pos
= origin
.RFindChar('^');
387 if (pos
== kNotFound
) {
388 aOriginNoSuffix
= origin
;
392 aOriginNoSuffix
= Substring(origin
, 0, pos
);
393 return PopulateFromSuffix(Substring(origin
, pos
));
396 void OriginAttributes::SyncAttributesWithPrivateBrowsing(
397 bool aInPrivateBrowsing
) {
398 mPrivateBrowsingId
= aInPrivateBrowsing
? 1 : 0;
402 bool OriginAttributes::IsPrivateBrowsing(const nsACString
& aOrigin
) {
404 OriginAttributes attrs
;
405 if (NS_WARN_IF(!attrs
.PopulateFromOrigin(aOrigin
, dummy
))) {
409 return !!attrs
.mPrivateBrowsingId
;
413 bool OriginAttributes::ParsePartitionKey(const nsAString
& aPartitionKey
,
414 nsAString
& outScheme
,
415 nsAString
& outBaseDomain
,
417 outScheme
.Truncate();
418 outBaseDomain
.Truncate();
421 // Partition keys have the format "(<scheme>,<baseDomain>,[port])". The port
422 // is optional. For example: "(https,example.com,8443)" or
423 // "(http,example.org)".
424 // When privacy.dynamic_firstparty.use_site = false, the partitionKey contains
425 // only the host, e.g. "example.com".
426 // See MakeTopLevelInfo for the partitionKey serialization code.
428 if (aPartitionKey
.IsEmpty()) {
432 // PartitionKey contains only the host.
433 if (!StaticPrefs::privacy_dynamic_firstparty_use_site()) {
434 outBaseDomain
= aPartitionKey
;
438 // Smallest possible partitionKey is "(x,x)". Scheme and base domain are
440 if (NS_WARN_IF(aPartitionKey
.Length() < 5)) {
444 if (NS_WARN_IF(aPartitionKey
.First() != '(' || aPartitionKey
.Last() != ')')) {
448 // Remove outer brackets so we can string split.
449 nsAutoString
str(Substring(aPartitionKey
, 1, aPartitionKey
.Length() - 2));
451 uint32_t fieldIndex
= 0;
452 for (const nsAString
& field
: str
.Split(',')) {
453 if (NS_WARN_IF(field
.IsEmpty())) {
454 // There cannot be empty fields.
458 if (fieldIndex
== 0) {
459 outScheme
.Assign(field
);
460 } else if (fieldIndex
== 1) {
461 outBaseDomain
.Assign(field
);
462 } else if (fieldIndex
== 2) {
463 // Parse the port which is represented in the partitionKey string as a
464 // decimal (base 10) number.
465 long port
= strtol(NS_ConvertUTF16toUTF8(field
).get(), nullptr, 10);
467 if (NS_WARN_IF(port
== 0)) {
470 outPort
= static_cast<int32_t>(port
);
472 NS_WARNING("Invalid partitionKey. Too many tokens");
479 // scheme and base domain are required.
480 return fieldIndex
> 1;
483 } // namespace mozilla