Bug 1815532 [wpt PR 38395] - Make inferred roles for CSS toggles influence accessibil...
[gecko.git] / caps / ExpandedPrincipal.cpp
blob6a210058cec6164c477d19010462aa1dcb05c7a0
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 "ExpandedPrincipal.h"
8 #include "nsIClassInfoImpl.h"
9 #include "nsIObjectInputStream.h"
10 #include "nsReadableUtils.h"
11 #include "mozilla/Base64.h"
12 #include "mozilla/extensions/WebExtensionPolicy.h"
13 #include "json/json.h"
15 using namespace mozilla;
17 NS_IMPL_CLASSINFO(ExpandedPrincipal, nullptr, 0, NS_EXPANDEDPRINCIPAL_CID)
18 NS_IMPL_QUERY_INTERFACE_CI(ExpandedPrincipal, nsIPrincipal,
19 nsIExpandedPrincipal)
20 NS_IMPL_CI_INTERFACE_GETTER(ExpandedPrincipal, nsIPrincipal,
21 nsIExpandedPrincipal)
23 struct OriginComparator {
24 bool LessThan(nsIPrincipal* a, nsIPrincipal* b) const {
25 nsAutoCString originA;
26 DebugOnly<nsresult> rv = a->GetOrigin(originA);
27 MOZ_ASSERT(NS_SUCCEEDED(rv));
28 nsAutoCString originB;
29 rv = b->GetOrigin(originB);
30 MOZ_ASSERT(NS_SUCCEEDED(rv));
31 return originA < originB;
34 bool Equals(nsIPrincipal* a, nsIPrincipal* b) const {
35 nsAutoCString originA;
36 DebugOnly<nsresult> rv = a->GetOrigin(originA);
37 MOZ_ASSERT(NS_SUCCEEDED(rv));
38 nsAutoCString originB;
39 rv = b->GetOrigin(originB);
40 MOZ_ASSERT(NS_SUCCEEDED(rv));
41 return a == b;
45 ExpandedPrincipal::ExpandedPrincipal(
46 nsTArray<nsCOMPtr<nsIPrincipal>>&& aPrincipals,
47 const nsACString& aOriginNoSuffix, const OriginAttributes& aAttrs)
48 : BasePrincipal(eExpandedPrincipal, aOriginNoSuffix, aAttrs),
49 mPrincipals(std::move(aPrincipals)) {}
51 ExpandedPrincipal::~ExpandedPrincipal() = default;
53 already_AddRefed<ExpandedPrincipal> ExpandedPrincipal::Create(
54 const nsTArray<nsCOMPtr<nsIPrincipal>>& aAllowList,
55 const OriginAttributes& aAttrs) {
56 // We force the principals to be sorted by origin so that ExpandedPrincipal
57 // origins can have a canonical form.
58 nsTArray<nsCOMPtr<nsIPrincipal>> principals;
59 OriginComparator c;
60 for (size_t i = 0; i < aAllowList.Length(); ++i) {
61 principals.InsertElementSorted(aAllowList[i], c);
64 nsAutoCString origin;
65 origin.AssignLiteral("[Expanded Principal [");
66 StringJoinAppend(
67 origin, ", "_ns, principals,
68 [](nsACString& dest, const nsCOMPtr<nsIPrincipal>& principal) {
69 nsAutoCString subOrigin;
70 DebugOnly<nsresult> rv = principal->GetOrigin(subOrigin);
71 MOZ_ASSERT(NS_SUCCEEDED(rv));
72 dest.Append(subOrigin);
73 });
74 origin.AppendLiteral("]]");
76 RefPtr<ExpandedPrincipal> ep =
77 new ExpandedPrincipal(std::move(principals), origin, aAttrs);
78 return ep.forget();
81 NS_IMETHODIMP
82 ExpandedPrincipal::GetDomain(nsIURI** aDomain) {
83 *aDomain = nullptr;
84 return NS_OK;
87 NS_IMETHODIMP
88 ExpandedPrincipal::SetDomain(nsIURI* aDomain) { return NS_OK; }
90 bool ExpandedPrincipal::SubsumesInternal(
91 nsIPrincipal* aOther,
92 BasePrincipal::DocumentDomainConsideration aConsideration) {
93 // If aOther is an ExpandedPrincipal too, we break it down into its component
94 // nsIPrincipals, and check subsumes on each one.
95 if (Cast(aOther)->Is<ExpandedPrincipal>()) {
96 auto* expanded = Cast(aOther)->As<ExpandedPrincipal>();
98 for (auto& other : expanded->AllowList()) {
99 // Use SubsumesInternal rather than Subsumes here, since OriginAttribute
100 // checks are only done between non-expanded sub-principals, and we don't
101 // need to incur the extra virtual call overhead.
102 if (!SubsumesInternal(other, aConsideration)) {
103 return false;
106 return true;
109 // We're dealing with a regular principal. One of our principals must subsume
110 // it.
111 for (uint32_t i = 0; i < mPrincipals.Length(); ++i) {
112 if (Cast(mPrincipals[i])->Subsumes(aOther, aConsideration)) {
113 return true;
117 return false;
120 bool ExpandedPrincipal::MayLoadInternal(nsIURI* uri) {
121 for (uint32_t i = 0; i < mPrincipals.Length(); ++i) {
122 if (BasePrincipal::Cast(mPrincipals[i])->MayLoadInternal(uri)) {
123 return true;
127 return false;
130 uint32_t ExpandedPrincipal::GetHashValue() {
131 MOZ_CRASH("extended principal should never be used as key in a hash map");
134 NS_IMETHODIMP
135 ExpandedPrincipal::GetURI(nsIURI** aURI) {
136 *aURI = nullptr;
137 return NS_OK;
140 const nsTArray<nsCOMPtr<nsIPrincipal>>& ExpandedPrincipal::AllowList() {
141 return mPrincipals;
144 NS_IMETHODIMP
145 ExpandedPrincipal::GetBaseDomain(nsACString& aBaseDomain) {
146 return NS_ERROR_NOT_AVAILABLE;
149 NS_IMETHODIMP
150 ExpandedPrincipal::GetAddonId(nsAString& aAddonId) {
151 aAddonId.Truncate();
152 return NS_OK;
155 bool ExpandedPrincipal::AddonHasPermission(const nsAtom* aPerm) {
156 for (size_t i = 0; i < mPrincipals.Length(); ++i) {
157 if (BasePrincipal::Cast(mPrincipals[i])->AddonHasPermission(aPerm)) {
158 return true;
161 return false;
164 bool ExpandedPrincipal::AddonAllowsLoad(nsIURI* aURI,
165 bool aExplicit /* = false */) {
166 for (const auto& principal : mPrincipals) {
167 if (Cast(principal)->AddonAllowsLoad(aURI, aExplicit)) {
168 return true;
171 return false;
174 void ExpandedPrincipal::SetCsp(nsIContentSecurityPolicy* aCSP) {
175 AssertIsOnMainThread();
176 mCSP = new nsMainThreadPtrHolder<nsIContentSecurityPolicy>(
177 "ExpandedPrincipal::mCSP", aCSP);
180 NS_IMETHODIMP
181 ExpandedPrincipal::GetCsp(nsIContentSecurityPolicy** aCsp) {
182 AssertIsOnMainThread();
183 NS_IF_ADDREF(*aCsp = mCSP);
184 return NS_OK;
187 nsIPrincipal* ExpandedPrincipal::PrincipalToInherit(nsIURI* aRequestedURI) {
188 if (aRequestedURI) {
189 // If a given sub-principal subsumes the given URI, use that principal for
190 // inheritance. In general, this only happens with certain CORS modes, loads
191 // with forced principal inheritance, and creation of XML documents from
192 // XMLHttpRequests or fetch requests. For URIs that normally inherit a
193 // principal (such as data: URIs), we fall back to the last principal in the
194 // allowlist.
195 for (const auto& principal : mPrincipals) {
196 if (Cast(principal)->MayLoadInternal(aRequestedURI)) {
197 return principal;
201 return mPrincipals.LastElement();
204 nsresult ExpandedPrincipal::GetScriptLocation(nsACString& aStr) {
205 aStr.AssignLiteral("[Expanded Principal [");
206 for (size_t i = 0; i < mPrincipals.Length(); ++i) {
207 if (i != 0) {
208 aStr.AppendLiteral(", ");
211 nsAutoCString spec;
212 nsresult rv =
213 nsJSPrincipals::get(mPrincipals.ElementAt(i))->GetScriptLocation(spec);
214 NS_ENSURE_SUCCESS(rv, rv);
216 aStr.Append(spec);
218 aStr.AppendLiteral("]]");
219 return NS_OK;
222 //////////////////////////////////////////
223 // Methods implementing nsISerializable //
224 //////////////////////////////////////////
226 // We've had way too many issues with unversioned serializations, so
227 // explicitly version this one.
228 static const uint32_t kSerializationVersion = 1;
230 NS_IMETHODIMP
231 ExpandedPrincipal::Deserializer::Read(nsIObjectInputStream* aStream) {
232 uint32_t version;
233 nsresult rv = aStream->Read32(&version);
234 if (version != kSerializationVersion) {
235 MOZ_ASSERT(false,
236 "We really need to add handling of the old(?) version here");
237 return NS_ERROR_UNEXPECTED;
240 uint32_t count;
241 rv = aStream->Read32(&count);
242 if (NS_FAILED(rv)) {
243 return rv;
246 nsTArray<nsCOMPtr<nsIPrincipal>> principals;
247 if (!principals.SetCapacity(count, fallible)) {
248 return NS_ERROR_OUT_OF_MEMORY;
251 OriginComparator c;
252 for (uint32_t i = 0; i < count; ++i) {
253 nsCOMPtr<nsISupports> read;
254 rv = aStream->ReadObject(true, getter_AddRefs(read));
255 if (NS_FAILED(rv)) {
256 return rv;
259 nsCOMPtr<nsIPrincipal> principal = do_QueryInterface(read);
260 if (!principal) {
261 return NS_ERROR_UNEXPECTED;
264 // Play it safe and InsertElementSorted, in case the sort order
265 // changed for some bizarre reason.
266 principals.InsertElementSorted(std::move(principal), c);
269 mPrincipal = ExpandedPrincipal::Create(principals, OriginAttributes());
270 return NS_OK;
273 nsresult ExpandedPrincipal::GetSiteIdentifier(SiteIdentifier& aSite) {
274 // Call GetSiteIdentifier on each of our principals and return a new
275 // ExpandedPrincipal.
277 nsTArray<nsCOMPtr<nsIPrincipal>> allowlist;
278 for (const auto& principal : mPrincipals) {
279 SiteIdentifier site;
280 nsresult rv = Cast(principal)->GetSiteIdentifier(site);
281 NS_ENSURE_SUCCESS(rv, rv);
282 allowlist.AppendElement(site.GetPrincipal());
285 RefPtr<ExpandedPrincipal> expandedPrincipal =
286 ExpandedPrincipal::Create(allowlist, OriginAttributesRef());
287 MOZ_ASSERT(expandedPrincipal, "ExpandedPrincipal::Create returned nullptr?");
289 aSite.Init(expandedPrincipal);
290 return NS_OK;
293 nsresult ExpandedPrincipal::PopulateJSONObject(Json::Value& aObject) {
294 Json::Value& principalList =
295 aObject[Json::StaticString(JSONEnumKeyString<eSpecs>())] =
296 Json::arrayValue;
297 for (const auto& principal : mPrincipals) {
298 Json::Value object = Json::objectValue;
299 nsresult rv = BasePrincipal::Cast(principal)->ToJSON(object);
300 NS_ENSURE_SUCCESS(rv, rv);
302 principalList.append(std::move(object));
305 nsAutoCString suffix;
306 OriginAttributesRef().CreateSuffix(suffix);
307 if (suffix.Length() > 0) {
308 SetJSONValue<eSuffix>(aObject, suffix);
311 return NS_OK;
314 already_AddRefed<BasePrincipal> ExpandedPrincipal::FromProperties(
315 nsTArray<ExpandedPrincipal::KeyVal>& aFields) {
316 MOZ_ASSERT(aFields.Length() == eMax + 1, "Must have all the keys");
317 nsTArray<nsCOMPtr<nsIPrincipal>> allowList;
318 OriginAttributes attrs;
319 // The odd structure here is to make the code to not compile
320 // if all the switch enum cases haven't been codified
322 for (const auto& field : aFields) {
323 switch (field.key) {
324 case ExpandedPrincipal::eSpecs:
325 if (!field.valueWasSerialized) {
326 MOZ_ASSERT(false,
327 "Expanded principals require specs in serialized JSON");
328 return nullptr;
330 for (const nsACString& each : field.value.Split(',')) {
331 nsAutoCString result;
332 nsresult rv;
333 rv = Base64Decode(each, result);
334 MOZ_ASSERT(NS_SUCCEEDED(rv), "failed to decode");
336 NS_ENSURE_SUCCESS(rv, nullptr);
337 nsCOMPtr<nsIPrincipal> principal = BasePrincipal::FromJSON(result);
338 allowList.AppendElement(principal);
340 break;
341 case ExpandedPrincipal::eSuffix:
342 if (field.valueWasSerialized) {
343 bool ok = attrs.PopulateFromSuffix(field.value);
344 if (!ok) {
345 return nullptr;
348 break;
352 if (allowList.Length() == 0) {
353 return nullptr;
356 RefPtr<ExpandedPrincipal> expandedPrincipal =
357 ExpandedPrincipal::Create(allowList, attrs);
359 return expandedPrincipal.forget();
362 /* static */
363 already_AddRefed<BasePrincipal> ExpandedPrincipal::FromProperties(
364 const Json::Value& aJSON) {
365 MOZ_ASSERT(aJSON.size() <= eMax + 1, "Must have at most, all the properties");
366 const std::string specs = std::to_string(eSpecs);
367 const std::string suffix = std::to_string(eSuffix);
368 MOZ_ASSERT(aJSON.isMember(specs), "The eSpecs member is required");
369 MOZ_ASSERT(aJSON.size() == 1 || aJSON.isMember(suffix),
370 "eSuffix is optional");
372 const auto* specsValue =
373 aJSON.find(specs.c_str(), specs.c_str() + specs.length());
374 if (!specsValue) {
375 MOZ_ASSERT(false, "Expanded principals require specs in serialized JSON");
376 return nullptr;
379 nsTArray<nsCOMPtr<nsIPrincipal>> allowList;
380 for (const auto& principalJSON : *specsValue) {
381 if (nsCOMPtr<nsIPrincipal> principal =
382 BasePrincipal::FromJSON(principalJSON)) {
383 allowList.AppendElement(principal);
387 if (allowList.Length() == 0) {
388 return nullptr;
391 OriginAttributes attrs;
392 if (aJSON.isMember(suffix)) {
393 const auto& value = aJSON[suffix];
394 if (!value.isString()) {
395 return nullptr;
398 bool ok = attrs.PopulateFromSuffix(nsDependentCString(value.asCString()));
399 if (!ok) {
400 return nullptr;
404 RefPtr<ExpandedPrincipal> expandedPrincipal =
405 ExpandedPrincipal::Create(allowList, attrs);
407 return expandedPrincipal.forget();
410 NS_IMETHODIMP
411 ExpandedPrincipal::IsThirdPartyURI(nsIURI* aURI, bool* aRes) {
412 // ExpandedPrincipal for extension content scripts consist of two principals,
413 // the document's principal and the extension's principal.
414 // To make sure that the third-party check behaves like the web page on which
415 // the content script is running, ignore the extension's principal.
417 for (const auto& principal : mPrincipals) {
418 if (!Cast(principal)->AddonPolicyCore()) {
419 return Cast(principal)->IsThirdPartyURI(aURI, aRes);
423 if (mPrincipals.IsEmpty()) {
424 *aRes = true;
425 return NS_OK;
428 return Cast(mPrincipals[0])->IsThirdPartyURI(aURI, aRes);