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 aForeignByAncestorContext
,
26 bool aUseSite
, 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 if (aForeignByAncestorContext
) {
47 site
.AppendLiteral(")");
49 aTopLevelInfo
.Assign(NS_ConvertUTF8toUTF16(site
));
52 static void MakeTopLevelInfo(const nsACString
& aScheme
, const nsACString
& aHost
,
53 bool aForeignByAncestorContext
, bool aUseSite
,
54 nsAString
& aTopLevelInfo
) {
55 MakeTopLevelInfo(aScheme
, aHost
, -1, aForeignByAncestorContext
, aUseSite
,
59 static void PopulateTopLevelInfoFromURI(const bool aIsTopLevelDocument
,
61 bool aForeignByAncestorContext
,
62 bool aIsFirstPartyEnabled
, bool aForced
,
64 nsString
OriginAttributes::*aTarget
,
65 OriginAttributes
& aOriginAttributes
) {
72 // If the prefs are off or this is not a top level load, bail out.
73 if ((!aIsFirstPartyEnabled
|| !aIsTopLevelDocument
) && !aForced
) {
77 nsAString
& topLevelInfo
= aOriginAttributes
.*aTarget
;
80 nsCOMPtr
<nsIURI
> uri
= aURI
;
81 // The URI could be nested (for example view-source:http://example.com), in
82 // that case we want to get the innermost URI (http://example.com).
83 nsCOMPtr
<nsINestedURI
> nestedURI
;
85 NS_ENSURE_SUCCESS_VOID(uri
->GetScheme(scheme
));
86 nestedURI
= do_QueryInterface(uri
);
87 // We can't just use GetInnermostURI on the nested URI, since that would
88 // also unwrap some about: URIs to hidden moz-safe-about: URIs, which we do
89 // not want. Thus we loop through with GetInnerURI until the URI isn't
90 // nested anymore or we encounter a about: scheme.
91 } while (nestedURI
&& !scheme
.EqualsLiteral("about") &&
92 NS_SUCCEEDED(nestedURI
->GetInnerURI(getter_AddRefs(uri
))));
94 if (scheme
.EqualsLiteral("about")) {
95 MakeTopLevelInfo(scheme
, nsLiteralCString(ABOUT_URI_FIRST_PARTY_DOMAIN
),
96 aForeignByAncestorContext
, aUseSite
, topLevelInfo
);
100 // If a null principal URI was provided, extract the UUID portion of the URI
101 // to use for the first-party domain.
102 if (scheme
.EqualsLiteral("moz-nullprincipal")) {
103 // Get the UUID portion of the URI, ignoring the precursor principal.
104 nsAutoCString filePath
;
105 rv
= uri
->GetFilePath(filePath
);
106 MOZ_ASSERT(NS_SUCCEEDED(rv
));
107 // Remove the `{}` characters from both ends.
108 filePath
.Mid(filePath
, 1, filePath
.Length() - 2);
109 filePath
.AppendLiteral(".mozilla");
110 // Store the generated file path.
111 topLevelInfo
= NS_ConvertUTF8toUTF16(filePath
);
115 // Add-on principals should never get any first-party domain
116 // attributes in order to guarantee their storage integrity when switching
118 if (scheme
.EqualsLiteral("moz-extension")) {
122 nsCOMPtr
<nsIPrincipal
> blobPrincipal
;
123 if (dom::BlobURLProtocolHandler::GetBlobURLPrincipal(
124 uri
, getter_AddRefs(blobPrincipal
))) {
125 MOZ_ASSERT(blobPrincipal
);
126 topLevelInfo
= blobPrincipal
->OriginAttributesRef().*aTarget
;
130 nsCOMPtr
<nsIEffectiveTLDService
> tldService
=
131 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID
);
132 MOZ_ASSERT(tldService
);
133 NS_ENSURE_TRUE_VOID(tldService
);
135 nsAutoCString baseDomain
;
136 rv
= tldService
->GetBaseDomain(uri
, 0, baseDomain
);
137 if (NS_SUCCEEDED(rv
)) {
138 MakeTopLevelInfo(scheme
, baseDomain
, aForeignByAncestorContext
, aUseSite
,
143 // Saving before rv is overwritten.
144 bool isIpAddress
= (rv
== NS_ERROR_HOST_IS_IP_ADDRESS
);
145 bool isInsufficientDomainLevels
= (rv
== NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS
);
148 rv
= uri
->GetPort(&port
);
149 NS_ENSURE_SUCCESS_VOID(rv
);
152 rv
= uri
->GetHost(host
);
153 NS_ENSURE_SUCCESS_VOID(rv
);
156 // If the host is an IPv4/IPv6 address, we still accept it as a
157 // valid topLevelInfo.
158 nsAutoCString ipAddr
;
160 if (net_IsValidIPv6Addr(host
)) {
161 // According to RFC2732, the host of an IPv6 address should be an
162 // IPv6reference. The GetHost() of nsIURI will only return the IPv6
163 // address. So, we need to convert it back to IPv6reference here.
164 ipAddr
.AssignLiteral("[");
166 ipAddr
.AppendLiteral("]");
171 MakeTopLevelInfo(scheme
, ipAddr
, port
, aForeignByAncestorContext
, aUseSite
,
177 MakeTopLevelInfo(scheme
, host
, port
, aForeignByAncestorContext
, aUseSite
,
182 if (isInsufficientDomainLevels
) {
183 nsAutoCString publicSuffix
;
184 rv
= tldService
->GetPublicSuffix(uri
, publicSuffix
);
185 if (NS_SUCCEEDED(rv
)) {
186 MakeTopLevelInfo(scheme
, publicSuffix
, port
, aForeignByAncestorContext
,
187 aUseSite
, topLevelInfo
);
193 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument
,
194 nsIURI
* aURI
, bool aForced
) {
195 PopulateTopLevelInfoFromURI(
196 aIsTopLevelDocument
, aURI
, false, IsFirstPartyEnabled(), aForced
,
197 StaticPrefs::privacy_firstparty_isolate_use_site(),
198 &OriginAttributes::mFirstPartyDomain
, *this);
201 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument
,
202 const nsACString
& aDomain
) {
203 SetFirstPartyDomain(aIsTopLevelDocument
, NS_ConvertUTF8toUTF16(aDomain
));
206 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument
,
207 const nsAString
& aDomain
,
209 // If the pref is off or this is not a top level load, bail out.
210 if ((!IsFirstPartyEnabled() || !aIsTopLevelDocument
) && !aForced
) {
214 mFirstPartyDomain
= aDomain
;
217 void OriginAttributes::SetPartitionKey(nsIURI
* aURI
,
218 bool aForeignByAncestorContext
) {
219 PopulateTopLevelInfoFromURI(
220 false /* aIsTopLevelDocument */, aURI
, aForeignByAncestorContext
,
221 IsFirstPartyEnabled(), true /* aForced */,
222 StaticPrefs::privacy_dynamic_firstparty_use_site(),
223 &OriginAttributes::mPartitionKey
, *this);
226 void OriginAttributes::SetPartitionKey(const nsACString
& aOther
) {
227 SetPartitionKey(NS_ConvertUTF8toUTF16(aOther
));
230 void OriginAttributes::SetPartitionKey(const nsAString
& aOther
) {
231 mPartitionKey
= aOther
;
234 void OriginAttributes::CreateSuffix(nsACString
& aStr
) const {
239 // Important: While serializing any string-valued attributes, perform a
240 // release-mode assertion to make sure that they don't contain characters that
241 // will break the quota manager when it uses the serialization for file
245 if (mUserContextId
!= nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID
) {
247 value
.AppendInt(mUserContextId
);
248 params
.Set("userContextId"_ns
, value
);
251 if (mPrivateBrowsingId
) {
253 value
.AppendInt(mPrivateBrowsingId
);
254 params
.Set("privateBrowsingId"_ns
, value
);
257 if (!mFirstPartyDomain
.IsEmpty()) {
258 nsAutoString
sanitizedFirstPartyDomain(mFirstPartyDomain
);
259 sanitizedFirstPartyDomain
.ReplaceChar(kSourceChar
, kSanitizedChar
);
260 params
.Set("firstPartyDomain"_ns
,
261 NS_ConvertUTF16toUTF8(sanitizedFirstPartyDomain
));
264 if (!mGeckoViewSessionContextId
.IsEmpty()) {
265 nsAutoString
sanitizedGeckoViewUserContextId(mGeckoViewSessionContextId
);
266 sanitizedGeckoViewUserContextId
.ReplaceChar(
267 dom::quota::QuotaManager::kReplaceChars16
, kSanitizedChar
);
268 params
.Set("geckoViewUserContextId"_ns
,
269 NS_ConvertUTF16toUTF8(sanitizedGeckoViewUserContextId
));
272 if (!mPartitionKey
.IsEmpty()) {
273 nsAutoString
sanitizedPartitionKey(mPartitionKey
);
274 sanitizedPartitionKey
.ReplaceChar(kSourceChar
, kSanitizedChar
);
275 params
.Set("partitionKey"_ns
, NS_ConvertUTF16toUTF8(sanitizedPartitionKey
));
280 params
.Serialize(value
, true);
281 if (!value
.IsEmpty()) {
282 aStr
.AppendLiteral("^");
286 // In debug builds, check the whole string for illegal characters too (just in
291 MOZ_ASSERT(str
.FindCharInSet(dom::quota::QuotaManager::kReplaceChars
) ==
296 already_AddRefed
<nsAtom
> OriginAttributes::CreateSuffixAtom() const {
297 nsAutoCString suffix
;
298 CreateSuffix(suffix
);
299 return NS_Atomize(suffix
);
302 void OriginAttributes::CreateAnonymizedSuffix(nsACString
& aStr
) const {
303 OriginAttributes attrs
= *this;
305 if (!attrs
.mFirstPartyDomain
.IsEmpty()) {
306 attrs
.mFirstPartyDomain
.AssignLiteral("_anonymizedFirstPartyDomain_");
309 if (!attrs
.mPartitionKey
.IsEmpty()) {
310 attrs
.mPartitionKey
.AssignLiteral("_anonymizedPartitionKey_");
313 attrs
.CreateSuffix(aStr
);
316 bool OriginAttributes::PopulateFromSuffix(const nsACString
& aStr
) {
317 if (aStr
.IsEmpty()) {
321 if (aStr
[0] != '^') {
325 // If a non-default mPrivateBrowsingId is passed and is not present in the
326 // suffix, then it will retain the id when it should be default according
327 // to the suffix. Set to default before iterating to fix this.
328 mPrivateBrowsingId
= nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID
;
330 // Checking that we are in a pristine state
332 MOZ_RELEASE_ASSERT(mUserContextId
== 0);
333 MOZ_RELEASE_ASSERT(mPrivateBrowsingId
== 0);
334 MOZ_RELEASE_ASSERT(mFirstPartyDomain
.IsEmpty());
335 MOZ_RELEASE_ASSERT(mGeckoViewSessionContextId
.IsEmpty());
336 MOZ_RELEASE_ASSERT(mPartitionKey
.IsEmpty());
338 return URLParams::Parse(
339 Substring(aStr
, 1, aStr
.Length() - 1), true,
340 [this](const nsACString
& aName
, const nsACString
& aValue
) {
341 if (aName
.EqualsLiteral("inBrowser")) {
342 if (!aValue
.EqualsLiteral("1")) {
349 if (aName
.EqualsLiteral("addonId") || aName
.EqualsLiteral("appId")) {
350 // No longer supported. Silently ignore so that legacy origin strings
351 // don't cause failures.
355 if (aName
.EqualsLiteral("userContextId")) {
357 int64_t val
= aValue
.ToInteger64(&rv
);
358 NS_ENSURE_SUCCESS(rv
, false);
359 NS_ENSURE_TRUE(val
<= UINT32_MAX
, false);
360 mUserContextId
= static_cast<uint32_t>(val
);
365 if (aName
.EqualsLiteral("privateBrowsingId")) {
367 int64_t val
= aValue
.ToInteger64(&rv
);
368 NS_ENSURE_SUCCESS(rv
, false);
369 NS_ENSURE_TRUE(val
>= 0 && val
<= UINT32_MAX
, false);
370 mPrivateBrowsingId
= static_cast<uint32_t>(val
);
375 if (aName
.EqualsLiteral("firstPartyDomain")) {
376 nsAutoCString
firstPartyDomain(aValue
);
377 firstPartyDomain
.ReplaceChar(kSanitizedChar
, kSourceChar
);
378 mFirstPartyDomain
.Assign(NS_ConvertUTF8toUTF16(firstPartyDomain
));
382 if (aName
.EqualsLiteral("geckoViewUserContextId")) {
383 mGeckoViewSessionContextId
.Assign(NS_ConvertUTF8toUTF16(aValue
));
387 if (aName
.EqualsLiteral("partitionKey")) {
388 nsAutoCString
partitionKey(aValue
);
389 partitionKey
.ReplaceChar(kSanitizedChar
, kSourceChar
);
390 mPartitionKey
.Assign(NS_ConvertUTF8toUTF16(partitionKey
));
394 // No other attributes are supported.
399 bool OriginAttributes::PopulateFromOrigin(const nsACString
& aOrigin
,
400 nsACString
& aOriginNoSuffix
) {
401 // RFindChar is only available on nsCString.
402 nsCString
origin(aOrigin
);
403 int32_t pos
= origin
.RFindChar('^');
405 if (pos
== kNotFound
) {
406 aOriginNoSuffix
= origin
;
410 aOriginNoSuffix
= Substring(origin
, 0, pos
);
411 return PopulateFromSuffix(Substring(origin
, pos
));
414 void OriginAttributes::SyncAttributesWithPrivateBrowsing(
415 bool aInPrivateBrowsing
) {
416 mPrivateBrowsingId
= aInPrivateBrowsing
? 1 : 0;
420 bool OriginAttributes::IsPrivateBrowsing(const nsACString
& aOrigin
) {
422 OriginAttributes attrs
;
423 if (NS_WARN_IF(!attrs
.PopulateFromOrigin(aOrigin
, dummy
))) {
427 return !!attrs
.mPrivateBrowsingId
;
431 bool OriginAttributes::ParsePartitionKey(const nsAString
& aPartitionKey
,
432 nsAString
& outScheme
,
433 nsAString
& outBaseDomain
,
435 bool& outForeignByAncestorContext
) {
436 outScheme
.Truncate();
437 outBaseDomain
.Truncate();
439 outForeignByAncestorContext
= false;
441 // Partition keys have the format
442 // "(<scheme>,<baseDomain>[,port][,foreignancestorbit])". The port and
443 // ancestor bits are optional. For example: "(https,example.com,8443)" or
444 // "(http,example.org)", or "(http,example.info,f)", or
445 // "(http,example.biz,8443,f)". When privacy.dynamic_firstparty.use_site =
446 // false, the partitionKey contains only the host, e.g. "example.com". See
447 // MakeTopLevelInfo for the partitionKey serialization code.
449 if (aPartitionKey
.IsEmpty()) {
453 // PartitionKey contains only the host.
454 if (!StaticPrefs::privacy_dynamic_firstparty_use_site()) {
455 outBaseDomain
= aPartitionKey
;
459 // Smallest possible partitionKey is "(x,x)". Scheme and base domain are
461 if (NS_WARN_IF(aPartitionKey
.Length() < 5)) {
465 if (NS_WARN_IF(aPartitionKey
.First() != '(' || aPartitionKey
.Last() != ')')) {
469 // Remove outer brackets so we can string split.
470 nsAutoString
str(Substring(aPartitionKey
, 1, aPartitionKey
.Length() - 2));
472 uint32_t fieldIndex
= 0;
473 for (const nsAString
& field
: str
.Split(',')) {
474 if (NS_WARN_IF(field
.IsEmpty())) {
475 // There cannot be empty fields.
479 if (fieldIndex
== 0) {
480 outScheme
.Assign(field
);
481 } else if (fieldIndex
== 1) {
482 outBaseDomain
.Assign(field
);
483 } else if (fieldIndex
== 2) {
484 // The first optional argument is either "f" or a port number
485 if (field
.EqualsLiteral("f")) {
486 outForeignByAncestorContext
= true;
488 // Parse the port which is represented in the partitionKey string as a
489 // decimal (base 10) number.
490 long port
= strtol(NS_ConvertUTF16toUTF8(field
).get(), nullptr, 10);
492 if (NS_WARN_IF(port
== 0)) {
495 outPort
= static_cast<int32_t>(port
);
497 } else if (fieldIndex
== 3) {
498 // The second optional argument, if it exists, is "f" and the first
499 // optional argument was a port
500 if (!field
.EqualsLiteral("f") || outPort
!= -1) {
501 NS_WARNING("Invalid partitionKey. Invalid token.");
504 outForeignByAncestorContext
= true;
506 NS_WARNING("Invalid partitionKey. Too many tokens");
513 // scheme and base domain are required.
514 return fieldIndex
> 1;
517 } // namespace mozilla