Bug 1769321 [wpt PR 34062] - Update wpt metadata, a=testonly
[gecko.git] / caps / OriginAttributes.cpp
blob5403868be31ecfda33461622e09a394c36fac063
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 "nsURLHelper.h"
18 static const char kSourceChar = ':';
19 static const char kSanitizedChar = '+';
21 namespace mozilla {
23 static void MakeTopLevelInfo(const nsACString& aScheme, const nsACString& aHost,
24 int32_t aPort, bool aUseSite,
25 nsAString& aTopLevelInfo) {
26 if (!aUseSite) {
27 aTopLevelInfo.Assign(NS_ConvertUTF8toUTF16(aHost));
28 return;
31 // Note: If you change the serialization of the partition-key, please update
32 // StoragePrincipalHelper.cpp too.
34 nsAutoCString site;
35 site.AssignLiteral("(");
36 site.Append(aScheme);
37 site.Append(",");
38 site.Append(aHost);
39 if (aPort != -1) {
40 site.Append(",");
41 site.AppendInt(aPort);
43 site.AppendLiteral(")");
45 aTopLevelInfo.Assign(NS_ConvertUTF8toUTF16(site));
48 static void MakeTopLevelInfo(const nsACString& aScheme, const nsACString& aHost,
49 bool aUseSite, nsAString& aTopLevelInfo) {
50 MakeTopLevelInfo(aScheme, aHost, -1, aUseSite, aTopLevelInfo);
53 static void PopulateTopLevelInfoFromURI(const bool aIsTopLevelDocument,
54 nsIURI* aURI, bool aIsFirstPartyEnabled,
55 bool aForced, bool aUseSite,
56 nsString OriginAttributes::*aTarget,
57 OriginAttributes& aOriginAttributes) {
58 nsresult rv;
60 if (!aURI) {
61 return;
64 // If the prefs are off or this is not a top level load, bail out.
65 if ((!aIsFirstPartyEnabled || !aIsTopLevelDocument) && !aForced) {
66 return;
69 nsAString& topLevelInfo = aOriginAttributes.*aTarget;
71 nsAutoCString scheme;
72 rv = aURI->GetScheme(scheme);
73 NS_ENSURE_SUCCESS_VOID(rv);
75 if (scheme.EqualsLiteral("about")) {
76 MakeTopLevelInfo(scheme, nsLiteralCString(ABOUT_URI_FIRST_PARTY_DOMAIN),
77 aUseSite, topLevelInfo);
78 return;
81 // Add-on principals should never get any first-party domain
82 // attributes in order to guarantee their storage integrity when switching
83 // FPI on and off.
84 if (scheme.EqualsLiteral("moz-extension")) {
85 return;
88 nsCOMPtr<nsIPrincipal> blobPrincipal;
89 if (dom::BlobURLProtocolHandler::GetBlobURLPrincipal(
90 aURI, getter_AddRefs(blobPrincipal))) {
91 MOZ_ASSERT(blobPrincipal);
92 topLevelInfo = blobPrincipal->OriginAttributesRef().*aTarget;
93 return;
96 nsCOMPtr<nsIEffectiveTLDService> tldService =
97 do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
98 MOZ_ASSERT(tldService);
99 NS_ENSURE_TRUE_VOID(tldService);
101 nsAutoCString baseDomain;
102 rv = tldService->GetBaseDomain(aURI, 0, baseDomain);
103 if (NS_SUCCEEDED(rv)) {
104 MakeTopLevelInfo(scheme, baseDomain, aUseSite, topLevelInfo);
105 return;
108 // Saving before rv is overwritten.
109 bool isIpAddress = (rv == NS_ERROR_HOST_IS_IP_ADDRESS);
110 bool isInsufficientDomainLevels = (rv == NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS);
112 int32_t port;
113 rv = aURI->GetPort(&port);
114 NS_ENSURE_SUCCESS_VOID(rv);
116 nsAutoCString host;
117 rv = aURI->GetHost(host);
118 NS_ENSURE_SUCCESS_VOID(rv);
120 if (isIpAddress) {
121 // If the host is an IPv4/IPv6 address, we still accept it as a
122 // valid topLevelInfo.
123 nsAutoCString ipAddr;
125 if (net_IsValidIPv6Addr(host)) {
126 // According to RFC2732, the host of an IPv6 address should be an
127 // IPv6reference. The GetHost() of nsIURI will only return the IPv6
128 // address. So, we need to convert it back to IPv6reference here.
129 ipAddr.AssignLiteral("[");
130 ipAddr.Append(host);
131 ipAddr.AppendLiteral("]");
132 } else {
133 ipAddr = host;
136 MakeTopLevelInfo(scheme, ipAddr, port, aUseSite, topLevelInfo);
137 return;
140 if (aUseSite) {
141 MakeTopLevelInfo(scheme, host, port, aUseSite, topLevelInfo);
142 return;
145 if (isInsufficientDomainLevels) {
146 nsAutoCString publicSuffix;
147 rv = tldService->GetPublicSuffix(aURI, publicSuffix);
148 if (NS_SUCCEEDED(rv)) {
149 MakeTopLevelInfo(scheme, publicSuffix, port, aUseSite, topLevelInfo);
150 return;
155 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument,
156 nsIURI* aURI, bool aForced) {
157 PopulateTopLevelInfoFromURI(
158 aIsTopLevelDocument, aURI, IsFirstPartyEnabled(), aForced,
159 StaticPrefs::privacy_firstparty_isolate_use_site(),
160 &OriginAttributes::mFirstPartyDomain, *this);
163 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument,
164 const nsACString& aDomain) {
165 SetFirstPartyDomain(aIsTopLevelDocument, NS_ConvertUTF8toUTF16(aDomain));
168 void OriginAttributes::SetFirstPartyDomain(const bool aIsTopLevelDocument,
169 const nsAString& aDomain,
170 bool aForced) {
171 // If the pref is off or this is not a top level load, bail out.
172 if ((!IsFirstPartyEnabled() || !aIsTopLevelDocument) && !aForced) {
173 return;
176 mFirstPartyDomain = aDomain;
179 void OriginAttributes::SetPartitionKey(nsIURI* aURI) {
180 PopulateTopLevelInfoFromURI(
181 false /* aIsTopLevelDocument */, aURI, IsFirstPartyEnabled(),
182 true /* aForced */, StaticPrefs::privacy_dynamic_firstparty_use_site(),
183 &OriginAttributes::mPartitionKey, *this);
186 void OriginAttributes::SetPartitionKey(const nsACString& aDomain) {
187 SetPartitionKey(NS_ConvertUTF8toUTF16(aDomain));
190 void OriginAttributes::SetPartitionKey(const nsAString& aDomain) {
191 mPartitionKey = aDomain;
194 void OriginAttributes::CreateSuffix(nsACString& aStr) const {
195 URLParams params;
196 nsAutoString value;
199 // Important: While serializing any string-valued attributes, perform a
200 // release-mode assertion to make sure that they don't contain characters that
201 // will break the quota manager when it uses the serialization for file
202 // naming.
205 if (mInIsolatedMozBrowser) {
206 params.Set(u"inBrowser"_ns, u"1"_ns);
209 if (mUserContextId != nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) {
210 value.Truncate();
211 value.AppendInt(mUserContextId);
212 params.Set(u"userContextId"_ns, value);
215 if (mPrivateBrowsingId) {
216 value.Truncate();
217 value.AppendInt(mPrivateBrowsingId);
218 params.Set(u"privateBrowsingId"_ns, value);
221 if (!mFirstPartyDomain.IsEmpty()) {
222 nsAutoString sanitizedFirstPartyDomain(mFirstPartyDomain);
223 sanitizedFirstPartyDomain.ReplaceChar(kSourceChar, kSanitizedChar);
225 params.Set(u"firstPartyDomain"_ns, sanitizedFirstPartyDomain);
228 if (!mGeckoViewSessionContextId.IsEmpty()) {
229 nsAutoString sanitizedGeckoViewUserContextId(mGeckoViewSessionContextId);
230 sanitizedGeckoViewUserContextId.ReplaceChar(
231 dom::quota::QuotaManager::kReplaceChars, kSanitizedChar);
233 params.Set(u"geckoViewUserContextId"_ns, sanitizedGeckoViewUserContextId);
236 if (!mPartitionKey.IsEmpty()) {
237 nsAutoString sanitizedPartitionKey(mPartitionKey);
238 sanitizedPartitionKey.ReplaceChar(kSourceChar, kSanitizedChar);
240 params.Set(u"partitionKey"_ns, sanitizedPartitionKey);
243 aStr.Truncate();
245 params.Serialize(value, true);
246 if (!value.IsEmpty()) {
247 aStr.AppendLiteral("^");
248 aStr.Append(NS_ConvertUTF16toUTF8(value));
251 // In debug builds, check the whole string for illegal characters too (just in
252 // case).
253 #ifdef DEBUG
254 nsAutoCString str;
255 str.Assign(aStr);
256 MOZ_ASSERT(str.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) ==
257 kNotFound);
258 #endif
261 already_AddRefed<nsAtom> OriginAttributes::CreateSuffixAtom() const {
262 nsAutoCString suffix;
263 CreateSuffix(suffix);
264 return NS_Atomize(suffix);
267 void OriginAttributes::CreateAnonymizedSuffix(nsACString& aStr) const {
268 OriginAttributes attrs = *this;
270 if (!attrs.mFirstPartyDomain.IsEmpty()) {
271 attrs.mFirstPartyDomain.AssignLiteral("_anonymizedFirstPartyDomain_");
274 if (!attrs.mPartitionKey.IsEmpty()) {
275 attrs.mPartitionKey.AssignLiteral("_anonymizedPartitionKey_");
278 attrs.CreateSuffix(aStr);
281 bool OriginAttributes::PopulateFromSuffix(const nsACString& aStr) {
282 if (aStr.IsEmpty()) {
283 return true;
286 if (aStr[0] != '^') {
287 return false;
290 // If a non-default mPrivateBrowsingId is passed and is not present in the
291 // suffix, then it will retain the id when it should be default according
292 // to the suffix. Set to default before iterating to fix this.
293 mPrivateBrowsingId = nsIScriptSecurityManager::DEFAULT_PRIVATE_BROWSING_ID;
295 // Checking that we are in a pristine state
297 MOZ_RELEASE_ASSERT(mUserContextId == 0);
298 MOZ_RELEASE_ASSERT(mPrivateBrowsingId == 0);
299 MOZ_RELEASE_ASSERT(mFirstPartyDomain.IsEmpty());
300 MOZ_RELEASE_ASSERT(mGeckoViewSessionContextId.IsEmpty());
301 MOZ_RELEASE_ASSERT(mPartitionKey.IsEmpty());
303 return URLParams::Parse(
304 Substring(aStr, 1, aStr.Length() - 1),
305 [this](const nsAString& aName, const nsAString& aValue) {
306 if (aName.EqualsLiteral("inBrowser")) {
307 if (!aValue.EqualsLiteral("1")) {
308 return false;
311 mInIsolatedMozBrowser = true;
312 return true;
315 if (aName.EqualsLiteral("addonId") || aName.EqualsLiteral("appId")) {
316 // No longer supported. Silently ignore so that legacy origin strings
317 // don't cause failures.
318 return true;
321 if (aName.EqualsLiteral("userContextId")) {
322 nsresult rv;
323 int64_t val = aValue.ToInteger64(&rv);
324 NS_ENSURE_SUCCESS(rv, false);
325 NS_ENSURE_TRUE(val <= UINT32_MAX, false);
326 mUserContextId = static_cast<uint32_t>(val);
328 return true;
331 if (aName.EqualsLiteral("privateBrowsingId")) {
332 nsresult rv;
333 int64_t val = aValue.ToInteger64(&rv);
334 NS_ENSURE_SUCCESS(rv, false);
335 NS_ENSURE_TRUE(val >= 0 && val <= UINT32_MAX, false);
336 mPrivateBrowsingId = static_cast<uint32_t>(val);
338 return true;
341 if (aName.EqualsLiteral("firstPartyDomain")) {
342 nsAutoString firstPartyDomain(aValue);
343 firstPartyDomain.ReplaceChar(kSanitizedChar, kSourceChar);
344 mFirstPartyDomain.Assign(firstPartyDomain);
345 return true;
348 if (aName.EqualsLiteral("geckoViewUserContextId")) {
349 mGeckoViewSessionContextId.Assign(aValue);
350 return true;
353 if (aName.EqualsLiteral("partitionKey")) {
354 nsAutoString partitionKey(aValue);
355 partitionKey.ReplaceChar(kSanitizedChar, kSourceChar);
356 mPartitionKey.Assign(partitionKey);
357 return true;
360 // No other attributes are supported.
361 return false;
365 bool OriginAttributes::PopulateFromOrigin(const nsACString& aOrigin,
366 nsACString& aOriginNoSuffix) {
367 // RFindChar is only available on nsCString.
368 nsCString origin(aOrigin);
369 int32_t pos = origin.RFindChar('^');
371 if (pos == kNotFound) {
372 aOriginNoSuffix = origin;
373 return true;
376 aOriginNoSuffix = Substring(origin, 0, pos);
377 return PopulateFromSuffix(Substring(origin, pos));
380 void OriginAttributes::SyncAttributesWithPrivateBrowsing(
381 bool aInPrivateBrowsing) {
382 mPrivateBrowsingId = aInPrivateBrowsing ? 1 : 0;
385 /* static */
386 bool OriginAttributes::IsPrivateBrowsing(const nsACString& aOrigin) {
387 nsAutoCString dummy;
388 OriginAttributes attrs;
389 if (NS_WARN_IF(!attrs.PopulateFromOrigin(aOrigin, dummy))) {
390 return false;
393 return !!attrs.mPrivateBrowsingId;
396 /* static */
397 bool OriginAttributes::ParsePartitionKey(const nsAString& aPartitionKey,
398 nsAString& outScheme,
399 nsAString& outBaseDomain,
400 int32_t& outPort) {
401 outScheme.Truncate();
402 outBaseDomain.Truncate();
403 outPort = -1;
405 // Partition keys have the format "(<scheme>,<baseDomain>,[port])". The port
406 // is optional. For example: "(https,example.com,8443)" or
407 // "(http,example.org)".
408 // When privacy.dynamic_firstparty.use_site = false, the partitionKey contains
409 // only the host, e.g. "example.com".
410 // See MakeTopLevelInfo for the partitionKey serialization code.
412 if (aPartitionKey.IsEmpty()) {
413 return true;
416 // PartitionKey contains only the host.
417 if (!StaticPrefs::privacy_dynamic_firstparty_use_site()) {
418 outBaseDomain = aPartitionKey;
419 return true;
422 // Smallest possible partitionKey is "(x,x)". Scheme and base domain are
423 // mandatory.
424 if (NS_WARN_IF(aPartitionKey.Length() < 5)) {
425 return false;
428 if (NS_WARN_IF(aPartitionKey.First() != '(' || aPartitionKey.Last() != ')')) {
429 return false;
432 // Remove outer brackets so we can string split.
433 nsAutoString str(Substring(aPartitionKey, 1, aPartitionKey.Length() - 2));
435 uint32_t fieldIndex = 0;
436 for (const nsAString& field : str.Split(',')) {
437 if (NS_WARN_IF(field.IsEmpty())) {
438 // There cannot be empty fields.
439 return false;
442 if (fieldIndex == 0) {
443 outScheme.Assign(field);
444 } else if (fieldIndex == 1) {
445 outBaseDomain.Assign(field);
446 } else if (fieldIndex == 2) {
447 // Parse the port which is represented in the partitionKey string as a
448 // decimal (base 10) number.
449 long port = strtol(NS_ConvertUTF16toUTF8(field).get(), nullptr, 10);
450 // Invalid port.
451 if (NS_WARN_IF(port == 0)) {
452 return false;
454 outPort = static_cast<int32_t>(port);
455 } else {
456 NS_WARNING("Invalid partitionKey. Too many tokens");
457 return false;
460 fieldIndex++;
463 // scheme and base domain are required.
464 return fieldIndex > 1;
467 } // namespace mozilla