Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / caps / OriginAttributes.cpp
blob45bf991416c5f1ed98e6023c280c1be176ead2ba
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 aForeignByAncestorContext,
26 bool aUseSite, 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 if (aForeignByAncestorContext) {
45 site.Append(",f");
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,
56 aTopLevelInfo);
59 static void PopulateTopLevelInfoFromURI(const bool aIsTopLevelDocument,
60 nsIURI* aURI,
61 bool aForeignByAncestorContext,
62 bool aIsFirstPartyEnabled, bool aForced,
63 bool aUseSite,
64 nsString OriginAttributes::*aTarget,
65 OriginAttributes& aOriginAttributes) {
66 nsresult rv;
68 if (!aURI) {
69 return;
72 // If the prefs are off or this is not a top level load, bail out.
73 if ((!aIsFirstPartyEnabled || !aIsTopLevelDocument) && !aForced) {
74 return;
77 nsAString& topLevelInfo = aOriginAttributes.*aTarget;
79 nsAutoCString scheme;
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;
84 do {
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);
97 return;
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);
112 return;
115 // Add-on principals should never get any first-party domain
116 // attributes in order to guarantee their storage integrity when switching
117 // FPI on and off.
118 if (scheme.EqualsLiteral("moz-extension")) {
119 return;
122 nsCOMPtr<nsIPrincipal> blobPrincipal;
123 if (dom::BlobURLProtocolHandler::GetBlobURLPrincipal(
124 uri, getter_AddRefs(blobPrincipal))) {
125 MOZ_ASSERT(blobPrincipal);
126 topLevelInfo = blobPrincipal->OriginAttributesRef().*aTarget;
127 return;
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,
139 topLevelInfo);
140 return;
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);
147 int32_t port;
148 rv = uri->GetPort(&port);
149 NS_ENSURE_SUCCESS_VOID(rv);
151 nsAutoCString host;
152 rv = uri->GetHost(host);
153 NS_ENSURE_SUCCESS_VOID(rv);
155 if (isIpAddress) {
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("[");
165 ipAddr.Append(host);
166 ipAddr.AppendLiteral("]");
167 } else {
168 ipAddr = host;
171 MakeTopLevelInfo(scheme, ipAddr, port, aForeignByAncestorContext, aUseSite,
172 topLevelInfo);
173 return;
176 if (aUseSite) {
177 MakeTopLevelInfo(scheme, host, port, aForeignByAncestorContext, aUseSite,
178 topLevelInfo);
179 return;
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);
188 return;
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,
208 bool aForced) {
209 // If the pref is off or this is not a top level load, bail out.
210 if ((!IsFirstPartyEnabled() || !aIsTopLevelDocument) && !aForced) {
211 return;
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 {
235 URLParams params;
236 nsAutoCString value;
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
242 // naming.
245 if (mUserContextId != nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) {
246 value.Truncate();
247 value.AppendInt(mUserContextId);
248 params.Set("userContextId"_ns, value);
251 if (mPrivateBrowsingId) {
252 value.Truncate();
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));
278 aStr.Truncate();
280 params.Serialize(value, true);
281 if (!value.IsEmpty()) {
282 aStr.AppendLiteral("^");
283 aStr.Append(value);
286 // In debug builds, check the whole string for illegal characters too (just in
287 // case).
288 #ifdef DEBUG
289 nsAutoCString str;
290 str.Assign(aStr);
291 MOZ_ASSERT(str.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) ==
292 kNotFound);
293 #endif
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()) {
318 return true;
321 if (aStr[0] != '^') {
322 return false;
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")) {
343 return false;
346 return true;
349 if (aName.EqualsLiteral("addonId") || aName.EqualsLiteral("appId")) {
350 // No longer supported. Silently ignore so that legacy origin strings
351 // don't cause failures.
352 return true;
355 if (aName.EqualsLiteral("userContextId")) {
356 nsresult rv;
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);
362 return true;
365 if (aName.EqualsLiteral("privateBrowsingId")) {
366 nsresult rv;
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);
372 return true;
375 if (aName.EqualsLiteral("firstPartyDomain")) {
376 nsAutoCString firstPartyDomain(aValue);
377 firstPartyDomain.ReplaceChar(kSanitizedChar, kSourceChar);
378 mFirstPartyDomain.Assign(NS_ConvertUTF8toUTF16(firstPartyDomain));
379 return true;
382 if (aName.EqualsLiteral("geckoViewUserContextId")) {
383 mGeckoViewSessionContextId.Assign(NS_ConvertUTF8toUTF16(aValue));
384 return true;
387 if (aName.EqualsLiteral("partitionKey")) {
388 nsAutoCString partitionKey(aValue);
389 partitionKey.ReplaceChar(kSanitizedChar, kSourceChar);
390 mPartitionKey.Assign(NS_ConvertUTF8toUTF16(partitionKey));
391 return true;
394 // No other attributes are supported.
395 return false;
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;
407 return true;
410 aOriginNoSuffix = Substring(origin, 0, pos);
411 return PopulateFromSuffix(Substring(origin, pos));
414 void OriginAttributes::SyncAttributesWithPrivateBrowsing(
415 bool aInPrivateBrowsing) {
416 mPrivateBrowsingId = aInPrivateBrowsing ? 1 : 0;
419 /* static */
420 bool OriginAttributes::IsPrivateBrowsing(const nsACString& aOrigin) {
421 nsAutoCString dummy;
422 OriginAttributes attrs;
423 if (NS_WARN_IF(!attrs.PopulateFromOrigin(aOrigin, dummy))) {
424 return false;
427 return !!attrs.mPrivateBrowsingId;
430 /* static */
431 bool OriginAttributes::ParsePartitionKey(const nsAString& aPartitionKey,
432 nsAString& outScheme,
433 nsAString& outBaseDomain,
434 int32_t& outPort,
435 bool& outForeignByAncestorContext) {
436 outScheme.Truncate();
437 outBaseDomain.Truncate();
438 outPort = -1;
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()) {
450 return true;
453 // PartitionKey contains only the host.
454 if (!StaticPrefs::privacy_dynamic_firstparty_use_site()) {
455 outBaseDomain = aPartitionKey;
456 return true;
459 // Smallest possible partitionKey is "(x,x)". Scheme and base domain are
460 // mandatory.
461 if (NS_WARN_IF(aPartitionKey.Length() < 5)) {
462 return false;
465 if (NS_WARN_IF(aPartitionKey.First() != '(' || aPartitionKey.Last() != ')')) {
466 return false;
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.
476 return false;
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;
487 } else {
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);
491 // Invalid port.
492 if (NS_WARN_IF(port == 0)) {
493 return false;
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.");
502 return false;
504 outForeignByAncestorContext = true;
505 } else {
506 NS_WARNING("Invalid partitionKey. Too many tokens");
507 return false;
510 fieldIndex++;
513 // scheme and base domain are required.
514 return fieldIndex > 1;
517 } // namespace mozilla