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(u
"userContextId"_ns
, value
);
251 if (mPrivateBrowsingId
) {
253 value
.AppendInt(mPrivateBrowsingId
);
254 params
.Set(u
"privateBrowsingId"_ns
, value
);
257 if (!mFirstPartyDomain
.IsEmpty()) {
258 nsAutoString
sanitizedFirstPartyDomain(mFirstPartyDomain
);
259 sanitizedFirstPartyDomain
.ReplaceChar(kSourceChar
, kSanitizedChar
);
261 params
.Set(u
"firstPartyDomain"_ns
, sanitizedFirstPartyDomain
);
264 if (!mGeckoViewSessionContextId
.IsEmpty()) {
265 nsAutoString
sanitizedGeckoViewUserContextId(mGeckoViewSessionContextId
);
266 sanitizedGeckoViewUserContextId
.ReplaceChar(
267 dom::quota::QuotaManager::kReplaceChars16
, kSanitizedChar
);
269 params
.Set(u
"geckoViewUserContextId"_ns
, sanitizedGeckoViewUserContextId
);
272 if (!mPartitionKey
.IsEmpty()) {
273 nsAutoString
sanitizedPartitionKey(mPartitionKey
);
274 sanitizedPartitionKey
.ReplaceChar(kSourceChar
, kSanitizedChar
);
276 params
.Set(u
"partitionKey"_ns
, sanitizedPartitionKey
);
281 params
.Serialize(value
, true);
282 if (!value
.IsEmpty()) {
283 aStr
.AppendLiteral("^");
284 aStr
.Append(NS_ConvertUTF16toUTF8(value
));
287 // In debug builds, check the whole string for illegal characters too (just in
292 MOZ_ASSERT(str
.FindCharInSet(dom::quota::QuotaManager::kReplaceChars
) ==
297 already_AddRefed
<nsAtom
> OriginAttributes::CreateSuffixAtom() const {
298 nsAutoCString suffix
;
299 CreateSuffix(suffix
);
300 return NS_Atomize(suffix
);
303 void OriginAttributes::CreateAnonymizedSuffix(nsACString
& aStr
) const {
304 OriginAttributes attrs
= *this;
306 if (!attrs
.mFirstPartyDomain
.IsEmpty()) {
307 attrs
.mFirstPartyDomain
.AssignLiteral("_anonymizedFirstPartyDomain_");
310 if (!attrs
.mPartitionKey
.IsEmpty()) {
311 attrs
.mPartitionKey
.AssignLiteral("_anonymizedPartitionKey_");
314 attrs
.CreateSuffix(aStr
);
317 bool OriginAttributes::PopulateFromSuffix(const nsACString
& aStr
) {
318 if (aStr
.IsEmpty()) {
322 if (aStr
[0] != '^') {
326 // If a non-default mPrivateBrowsingId is passed and is not present in the
327 // suffix, then it will retain the id when it should be default according
328 // to the suffix. Set to default before iterating to fix this.
329 mPrivateBrowsingId
= nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID
;
331 // Checking that we are in a pristine state
333 MOZ_RELEASE_ASSERT(mUserContextId
== 0);
334 MOZ_RELEASE_ASSERT(mPrivateBrowsingId
== 0);
335 MOZ_RELEASE_ASSERT(mFirstPartyDomain
.IsEmpty());
336 MOZ_RELEASE_ASSERT(mGeckoViewSessionContextId
.IsEmpty());
337 MOZ_RELEASE_ASSERT(mPartitionKey
.IsEmpty());
339 return URLParams::Parse(
340 Substring(aStr
, 1, aStr
.Length() - 1), true,
341 [this](const nsAString
& aName
, const nsAString
& aValue
) {
342 if (aName
.EqualsLiteral("inBrowser")) {
343 if (!aValue
.EqualsLiteral("1")) {
350 if (aName
.EqualsLiteral("addonId") || aName
.EqualsLiteral("appId")) {
351 // No longer supported. Silently ignore so that legacy origin strings
352 // don't cause failures.
356 if (aName
.EqualsLiteral("userContextId")) {
358 int64_t val
= aValue
.ToInteger64(&rv
);
359 NS_ENSURE_SUCCESS(rv
, false);
360 NS_ENSURE_TRUE(val
<= UINT32_MAX
, false);
361 mUserContextId
= static_cast<uint32_t>(val
);
366 if (aName
.EqualsLiteral("privateBrowsingId")) {
368 int64_t val
= aValue
.ToInteger64(&rv
);
369 NS_ENSURE_SUCCESS(rv
, false);
370 NS_ENSURE_TRUE(val
>= 0 && val
<= UINT32_MAX
, false);
371 mPrivateBrowsingId
= static_cast<uint32_t>(val
);
376 if (aName
.EqualsLiteral("firstPartyDomain")) {
377 nsAutoString
firstPartyDomain(aValue
);
378 firstPartyDomain
.ReplaceChar(kSanitizedChar
, kSourceChar
);
379 mFirstPartyDomain
.Assign(firstPartyDomain
);
383 if (aName
.EqualsLiteral("geckoViewUserContextId")) {
384 mGeckoViewSessionContextId
.Assign(aValue
);
388 if (aName
.EqualsLiteral("partitionKey")) {
389 nsAutoString
partitionKey(aValue
);
390 partitionKey
.ReplaceChar(kSanitizedChar
, kSourceChar
);
391 mPartitionKey
.Assign(partitionKey
);
395 // No other attributes are supported.
400 bool OriginAttributes::PopulateFromOrigin(const nsACString
& aOrigin
,
401 nsACString
& aOriginNoSuffix
) {
402 // RFindChar is only available on nsCString.
403 nsCString
origin(aOrigin
);
404 int32_t pos
= origin
.RFindChar('^');
406 if (pos
== kNotFound
) {
407 aOriginNoSuffix
= origin
;
411 aOriginNoSuffix
= Substring(origin
, 0, pos
);
412 return PopulateFromSuffix(Substring(origin
, pos
));
415 void OriginAttributes::SyncAttributesWithPrivateBrowsing(
416 bool aInPrivateBrowsing
) {
417 mPrivateBrowsingId
= aInPrivateBrowsing
? 1 : 0;
421 bool OriginAttributes::IsPrivateBrowsing(const nsACString
& aOrigin
) {
423 OriginAttributes attrs
;
424 if (NS_WARN_IF(!attrs
.PopulateFromOrigin(aOrigin
, dummy
))) {
428 return !!attrs
.mPrivateBrowsingId
;
432 bool OriginAttributes::ParsePartitionKey(const nsAString
& aPartitionKey
,
433 nsAString
& outScheme
,
434 nsAString
& outBaseDomain
,
436 bool& outForeignByAncestorContext
) {
437 outScheme
.Truncate();
438 outBaseDomain
.Truncate();
440 outForeignByAncestorContext
= false;
442 // Partition keys have the format
443 // "(<scheme>,<baseDomain>[,port][,foreignancestorbit])". The port and
444 // ancestor bits are optional. For example: "(https,example.com,8443)" or
445 // "(http,example.org)", or "(http,example.info,f)", or
446 // "(http,example.biz,8443,f)". When privacy.dynamic_firstparty.use_site =
447 // false, the partitionKey contains only the host, e.g. "example.com". See
448 // MakeTopLevelInfo for the partitionKey serialization code.
450 if (aPartitionKey
.IsEmpty()) {
454 // PartitionKey contains only the host.
455 if (!StaticPrefs::privacy_dynamic_firstparty_use_site()) {
456 outBaseDomain
= aPartitionKey
;
460 // Smallest possible partitionKey is "(x,x)". Scheme and base domain are
462 if (NS_WARN_IF(aPartitionKey
.Length() < 5)) {
466 if (NS_WARN_IF(aPartitionKey
.First() != '(' || aPartitionKey
.Last() != ')')) {
470 // Remove outer brackets so we can string split.
471 nsAutoString
str(Substring(aPartitionKey
, 1, aPartitionKey
.Length() - 2));
473 uint32_t fieldIndex
= 0;
474 for (const nsAString
& field
: str
.Split(',')) {
475 if (NS_WARN_IF(field
.IsEmpty())) {
476 // There cannot be empty fields.
480 if (fieldIndex
== 0) {
481 outScheme
.Assign(field
);
482 } else if (fieldIndex
== 1) {
483 outBaseDomain
.Assign(field
);
484 } else if (fieldIndex
== 2) {
485 // The first optional argument is either "f" or a port number
486 if (field
.EqualsLiteral("f")) {
487 outForeignByAncestorContext
= true;
489 // Parse the port which is represented in the partitionKey string as a
490 // decimal (base 10) number.
491 long port
= strtol(NS_ConvertUTF16toUTF8(field
).get(), nullptr, 10);
493 if (NS_WARN_IF(port
== 0)) {
496 outPort
= static_cast<int32_t>(port
);
498 } else if (fieldIndex
== 3) {
499 // The second optional argument, if it exists, is "f" and the first
500 // optional argument was a port
501 if (!field
.EqualsLiteral("f") || outPort
!= -1) {
502 NS_WARNING("Invalid partitionKey. Invalid token.");
505 outForeignByAncestorContext
= true;
507 NS_WARNING("Invalid partitionKey. Too many tokens");
514 // scheme and base domain are required.
515 return fieldIndex
> 1;
518 } // namespace mozilla