Bug 1860492 - Change file name in test @ toolkit/components/antitracking/test/browser...
[gecko.git] / caps / OriginAttributes.cpp
blobf599b58d63c5a54e1e724454a9edba8521bc9ead
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 nsAutoString 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(u"userContextId"_ns, value);
251 if (mPrivateBrowsingId) {
252 value.Truncate();
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);
279 aStr.Truncate();
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
288 // case).
289 #ifdef DEBUG
290 nsAutoCString str;
291 str.Assign(aStr);
292 MOZ_ASSERT(str.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) ==
293 kNotFound);
294 #endif
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()) {
319 return true;
322 if (aStr[0] != '^') {
323 return false;
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")) {
344 return false;
347 return true;
350 if (aName.EqualsLiteral("addonId") || aName.EqualsLiteral("appId")) {
351 // No longer supported. Silently ignore so that legacy origin strings
352 // don't cause failures.
353 return true;
356 if (aName.EqualsLiteral("userContextId")) {
357 nsresult rv;
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);
363 return true;
366 if (aName.EqualsLiteral("privateBrowsingId")) {
367 nsresult rv;
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);
373 return true;
376 if (aName.EqualsLiteral("firstPartyDomain")) {
377 nsAutoString firstPartyDomain(aValue);
378 firstPartyDomain.ReplaceChar(kSanitizedChar, kSourceChar);
379 mFirstPartyDomain.Assign(firstPartyDomain);
380 return true;
383 if (aName.EqualsLiteral("geckoViewUserContextId")) {
384 mGeckoViewSessionContextId.Assign(aValue);
385 return true;
388 if (aName.EqualsLiteral("partitionKey")) {
389 nsAutoString partitionKey(aValue);
390 partitionKey.ReplaceChar(kSanitizedChar, kSourceChar);
391 mPartitionKey.Assign(partitionKey);
392 return true;
395 // No other attributes are supported.
396 return false;
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;
408 return true;
411 aOriginNoSuffix = Substring(origin, 0, pos);
412 return PopulateFromSuffix(Substring(origin, pos));
415 void OriginAttributes::SyncAttributesWithPrivateBrowsing(
416 bool aInPrivateBrowsing) {
417 mPrivateBrowsingId = aInPrivateBrowsing ? 1 : 0;
420 /* static */
421 bool OriginAttributes::IsPrivateBrowsing(const nsACString& aOrigin) {
422 nsAutoCString dummy;
423 OriginAttributes attrs;
424 if (NS_WARN_IF(!attrs.PopulateFromOrigin(aOrigin, dummy))) {
425 return false;
428 return !!attrs.mPrivateBrowsingId;
431 /* static */
432 bool OriginAttributes::ParsePartitionKey(const nsAString& aPartitionKey,
433 nsAString& outScheme,
434 nsAString& outBaseDomain,
435 int32_t& outPort,
436 bool& outForeignByAncestorContext) {
437 outScheme.Truncate();
438 outBaseDomain.Truncate();
439 outPort = -1;
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()) {
451 return true;
454 // PartitionKey contains only the host.
455 if (!StaticPrefs::privacy_dynamic_firstparty_use_site()) {
456 outBaseDomain = aPartitionKey;
457 return true;
460 // Smallest possible partitionKey is "(x,x)". Scheme and base domain are
461 // mandatory.
462 if (NS_WARN_IF(aPartitionKey.Length() < 5)) {
463 return false;
466 if (NS_WARN_IF(aPartitionKey.First() != '(' || aPartitionKey.Last() != ')')) {
467 return false;
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.
477 return false;
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;
488 } else {
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);
492 // Invalid port.
493 if (NS_WARN_IF(port == 0)) {
494 return false;
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.");
503 return false;
505 outForeignByAncestorContext = true;
506 } else {
507 NS_WARNING("Invalid partitionKey. Too many tokens");
508 return false;
511 fieldIndex++;
514 // scheme and base domain are required.
515 return fieldIndex > 1;
518 } // namespace mozilla