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
,
20 NS_IMPL_CI_INTERFACE_GETTER(ExpandedPrincipal
, nsIPrincipal
,
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
));
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
;
60 for (size_t i
= 0; i
< aAllowList
.Length(); ++i
) {
61 principals
.InsertElementSorted(aAllowList
[i
], c
);
65 origin
.AssignLiteral("[Expanded Principal [");
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
);
74 origin
.AppendLiteral("]]");
76 RefPtr
<ExpandedPrincipal
> ep
=
77 new ExpandedPrincipal(std::move(principals
), origin
, aAttrs
);
82 ExpandedPrincipal::GetDomain(nsIURI
** aDomain
) {
88 ExpandedPrincipal::SetDomain(nsIURI
* aDomain
) { return NS_OK
; }
90 bool ExpandedPrincipal::SubsumesInternal(
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
)) {
109 // We're dealing with a regular principal. One of our principals must subsume
111 for (uint32_t i
= 0; i
< mPrincipals
.Length(); ++i
) {
112 if (Cast(mPrincipals
[i
])->Subsumes(aOther
, aConsideration
)) {
120 bool ExpandedPrincipal::MayLoadInternal(nsIURI
* uri
) {
121 for (uint32_t i
= 0; i
< mPrincipals
.Length(); ++i
) {
122 if (BasePrincipal::Cast(mPrincipals
[i
])->MayLoadInternal(uri
)) {
130 uint32_t ExpandedPrincipal::GetHashValue() {
131 MOZ_CRASH("extended principal should never be used as key in a hash map");
135 ExpandedPrincipal::GetURI(nsIURI
** aURI
) {
140 const nsTArray
<nsCOMPtr
<nsIPrincipal
>>& ExpandedPrincipal::AllowList() {
145 ExpandedPrincipal::GetBaseDomain(nsACString
& aBaseDomain
) {
146 return NS_ERROR_NOT_AVAILABLE
;
150 ExpandedPrincipal::GetAddonId(nsAString
& aAddonId
) {
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
)) {
164 bool ExpandedPrincipal::AddonAllowsLoad(nsIURI
* aURI
,
165 bool aExplicit
/* = false */) {
166 for (const auto& principal
: mPrincipals
) {
167 if (Cast(principal
)->AddonAllowsLoad(aURI
, aExplicit
)) {
174 void ExpandedPrincipal::SetCsp(nsIContentSecurityPolicy
* aCSP
) {
175 AssertIsOnMainThread();
176 mCSP
= new nsMainThreadPtrHolder
<nsIContentSecurityPolicy
>(
177 "ExpandedPrincipal::mCSP", aCSP
);
181 ExpandedPrincipal::GetCsp(nsIContentSecurityPolicy
** aCsp
) {
182 AssertIsOnMainThread();
183 NS_IF_ADDREF(*aCsp
= mCSP
);
187 nsIPrincipal
* ExpandedPrincipal::PrincipalToInherit(nsIURI
* 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
195 for (const auto& principal
: mPrincipals
) {
196 if (Cast(principal
)->MayLoadInternal(aRequestedURI
)) {
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
) {
208 aStr
.AppendLiteral(", ");
213 nsJSPrincipals::get(mPrincipals
.ElementAt(i
))->GetScriptLocation(spec
);
214 NS_ENSURE_SUCCESS(rv
, rv
);
218 aStr
.AppendLiteral("]]");
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;
231 ExpandedPrincipal::Deserializer::Read(nsIObjectInputStream
* aStream
) {
233 nsresult rv
= aStream
->Read32(&version
);
234 if (version
!= kSerializationVersion
) {
236 "We really need to add handling of the old(?) version here");
237 return NS_ERROR_UNEXPECTED
;
241 rv
= aStream
->Read32(&count
);
246 nsTArray
<nsCOMPtr
<nsIPrincipal
>> principals
;
247 if (!principals
.SetCapacity(count
, fallible
)) {
248 return NS_ERROR_OUT_OF_MEMORY
;
252 for (uint32_t i
= 0; i
< count
; ++i
) {
253 nsCOMPtr
<nsISupports
> read
;
254 rv
= aStream
->ReadObject(true, getter_AddRefs(read
));
259 nsCOMPtr
<nsIPrincipal
> principal
= do_QueryInterface(read
);
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());
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
) {
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
);
293 nsresult
ExpandedPrincipal::PopulateJSONObject(Json::Value
& aObject
) {
294 Json::Value
& principalList
=
295 aObject
[Json::StaticString(JSONEnumKeyString
<eSpecs
>())] =
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
);
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
) {
324 case ExpandedPrincipal::eSpecs
:
325 if (!field
.valueWasSerialized
) {
327 "Expanded principals require specs in serialized JSON");
330 for (const nsACString
& each
: field
.value
.Split(',')) {
331 nsAutoCString result
;
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
);
341 case ExpandedPrincipal::eSuffix
:
342 if (field
.valueWasSerialized
) {
343 bool ok
= attrs
.PopulateFromSuffix(field
.value
);
352 if (allowList
.Length() == 0) {
356 RefPtr
<ExpandedPrincipal
> expandedPrincipal
=
357 ExpandedPrincipal::Create(allowList
, attrs
);
359 return expandedPrincipal
.forget();
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());
375 MOZ_ASSERT(false, "Expanded principals require specs in serialized JSON");
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) {
391 OriginAttributes attrs
;
392 if (aJSON
.isMember(suffix
)) {
393 const auto& value
= aJSON
[suffix
];
394 if (!value
.isString()) {
398 bool ok
= attrs
.PopulateFromSuffix(nsDependentCString(value
.asCString()));
404 RefPtr
<ExpandedPrincipal
> expandedPrincipal
=
405 ExpandedPrincipal::Create(allowList
, attrs
);
407 return expandedPrincipal
.forget();
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()) {
428 return Cast(mPrincipals
[0])->IsThirdPartyURI(aURI
, aRes
);