Bug 1809679 [wpt PR 37879] - Update wpt metadata, a=testonly
[gecko.git] / caps / OriginAttributes.cpp
blobb6746a54c430b0fc42abe7b857929efb01b3e065
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"
13 #include "nsIURI.h"
14 #include "nsNetCID.h"
15 #include "nsNetUtil.h"
16 #include "nsString.h"
17 #include "nsURLHelper.h"
19 static const char kSourceChar = ':';
20 static const char kSanitizedChar = '+';
22 namespace mozilla {
24 static void MakeTopLevelInfo(const nsACString& aScheme, const nsACString& aHost,
25 int32_t aPort, bool aUseSite,
26 nsAString& aTopLevelInfo) {
27 if (!aUseSite) {
28 aTopLevelInfo.Assign(NS_ConvertUTF8toUTF16(aHost));
29 return;
32 // Note: If you change the serialization of the partition-key, please update
33 // StoragePrincipalHelper.cpp too.
35 nsAutoCString site;
36 site.AssignLiteral("(");
37 site.Append(aScheme);
38 site.Append(",");
39 site.Append(aHost);
40 if (aPort != -1) {
41 site.Append(",");
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) {
59 nsresult rv;
61 if (!aURI) {
62 return;
65 // If the prefs are off or this is not a top level load, bail out.
66 if ((!aIsFirstPartyEnabled || !aIsTopLevelDocument) && !aForced) {
67 return;
70 nsAString& topLevelInfo = aOriginAttributes.*aTarget;
72 nsAutoCString scheme;
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);
79 return;
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);
94 return;
97 // Add-on principals should never get any first-party domain
98 // attributes in order to guarantee their storage integrity when switching
99 // FPI on and off.
100 if (scheme.EqualsLiteral("moz-extension")) {
101 return;
104 nsCOMPtr<nsIPrincipal> blobPrincipal;
105 if (dom::BlobURLProtocolHandler::GetBlobURLPrincipal(
106 aURI, getter_AddRefs(blobPrincipal))) {
107 MOZ_ASSERT(blobPrincipal);
108 topLevelInfo = blobPrincipal->OriginAttributesRef().*aTarget;
109 return;
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);
121 return;
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);
128 int32_t port;
129 rv = aURI->GetPort(&port);
130 NS_ENSURE_SUCCESS_VOID(rv);
132 nsAutoCString host;
133 rv = aURI->GetHost(host);
134 NS_ENSURE_SUCCESS_VOID(rv);
136 if (isIpAddress) {
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("[");
146 ipAddr.Append(host);
147 ipAddr.AppendLiteral("]");
148 } else {
149 ipAddr = host;
152 MakeTopLevelInfo(scheme, ipAddr, port, aUseSite, topLevelInfo);
153 return;
156 if (aUseSite) {
157 MakeTopLevelInfo(scheme, host, port, aUseSite, topLevelInfo);
158 return;
161 if (isInsufficientDomainLevels) {
162 nsAutoCString publicSuffix;
163 rv = tldService->GetPublicSuffix(aURI, publicSuffix);
164 if (NS_SUCCEEDED(rv)) {
165 MakeTopLevelInfo(scheme, publicSuffix, port, aUseSite, topLevelInfo);
166 return;
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,
186 bool aForced) {
187 // If the pref is off or this is not a top level load, bail out.
188 if ((!IsFirstPartyEnabled() || !aIsTopLevelDocument) && !aForced) {
189 return;
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 {
211 URLParams params;
212 nsAutoString value;
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
218 // naming.
221 if (mInIsolatedMozBrowser) {
222 params.Set(u"inBrowser"_ns, u"1"_ns);
225 if (mUserContextId != nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) {
226 value.Truncate();
227 value.AppendInt(mUserContextId);
228 params.Set(u"userContextId"_ns, value);
231 if (mPrivateBrowsingId) {
232 value.Truncate();
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);
259 aStr.Truncate();
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
268 // case).
269 #ifdef DEBUG
270 nsAutoCString str;
271 str.Assign(aStr);
272 MOZ_ASSERT(str.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) ==
273 kNotFound);
274 #endif
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()) {
299 return true;
302 if (aStr[0] != '^') {
303 return false;
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")) {
324 return false;
327 mInIsolatedMozBrowser = true;
328 return 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.
334 return true;
337 if (aName.EqualsLiteral("userContextId")) {
338 nsresult rv;
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);
344 return true;
347 if (aName.EqualsLiteral("privateBrowsingId")) {
348 nsresult rv;
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);
354 return true;
357 if (aName.EqualsLiteral("firstPartyDomain")) {
358 nsAutoString firstPartyDomain(aValue);
359 firstPartyDomain.ReplaceChar(kSanitizedChar, kSourceChar);
360 mFirstPartyDomain.Assign(firstPartyDomain);
361 return true;
364 if (aName.EqualsLiteral("geckoViewUserContextId")) {
365 mGeckoViewSessionContextId.Assign(aValue);
366 return true;
369 if (aName.EqualsLiteral("partitionKey")) {
370 nsAutoString partitionKey(aValue);
371 partitionKey.ReplaceChar(kSanitizedChar, kSourceChar);
372 mPartitionKey.Assign(partitionKey);
373 return true;
376 // No other attributes are supported.
377 return false;
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;
389 return true;
392 aOriginNoSuffix = Substring(origin, 0, pos);
393 return PopulateFromSuffix(Substring(origin, pos));
396 void OriginAttributes::SyncAttributesWithPrivateBrowsing(
397 bool aInPrivateBrowsing) {
398 mPrivateBrowsingId = aInPrivateBrowsing ? 1 : 0;
401 /* static */
402 bool OriginAttributes::IsPrivateBrowsing(const nsACString& aOrigin) {
403 nsAutoCString dummy;
404 OriginAttributes attrs;
405 if (NS_WARN_IF(!attrs.PopulateFromOrigin(aOrigin, dummy))) {
406 return false;
409 return !!attrs.mPrivateBrowsingId;
412 /* static */
413 bool OriginAttributes::ParsePartitionKey(const nsAString& aPartitionKey,
414 nsAString& outScheme,
415 nsAString& outBaseDomain,
416 int32_t& outPort) {
417 outScheme.Truncate();
418 outBaseDomain.Truncate();
419 outPort = -1;
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()) {
429 return true;
432 // PartitionKey contains only the host.
433 if (!StaticPrefs::privacy_dynamic_firstparty_use_site()) {
434 outBaseDomain = aPartitionKey;
435 return true;
438 // Smallest possible partitionKey is "(x,x)". Scheme and base domain are
439 // mandatory.
440 if (NS_WARN_IF(aPartitionKey.Length() < 5)) {
441 return false;
444 if (NS_WARN_IF(aPartitionKey.First() != '(' || aPartitionKey.Last() != ')')) {
445 return false;
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.
455 return false;
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);
466 // Invalid port.
467 if (NS_WARN_IF(port == 0)) {
468 return false;
470 outPort = static_cast<int32_t>(port);
471 } else {
472 NS_WARNING("Invalid partitionKey. Too many tokens");
473 return false;
476 fieldIndex++;
479 // scheme and base domain are required.
480 return fieldIndex > 1;
483 } // namespace mozilla