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 "json/json.h"
14 using namespace mozilla
;
16 NS_IMPL_CLASSINFO(ExpandedPrincipal
, nullptr, nsIClassInfo::MAIN_THREAD_ONLY
,
17 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 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
) { mCSP
= aCSP
; }
177 ExpandedPrincipal::GetCsp(nsIContentSecurityPolicy
** aCsp
) {
178 NS_IF_ADDREF(*aCsp
= mCSP
);
182 nsIPrincipal
* ExpandedPrincipal::PrincipalToInherit(nsIURI
* aRequestedURI
) {
184 // If a given sub-principal subsumes the given URI, use that principal for
185 // inheritance. In general, this only happens with certain CORS modes, loads
186 // with forced principal inheritance, and creation of XML documents from
187 // XMLHttpRequests or fetch requests. For URIs that normally inherit a
188 // principal (such as data: URIs), we fall back to the last principal in the
190 for (const auto& principal
: mPrincipals
) {
191 if (Cast(principal
)->MayLoadInternal(aRequestedURI
)) {
196 return mPrincipals
.LastElement();
199 nsresult
ExpandedPrincipal::GetScriptLocation(nsACString
& aStr
) {
200 aStr
.AssignLiteral("[Expanded Principal [");
201 for (size_t i
= 0; i
< mPrincipals
.Length(); ++i
) {
203 aStr
.AppendLiteral(", ");
208 nsJSPrincipals::get(mPrincipals
.ElementAt(i
))->GetScriptLocation(spec
);
209 NS_ENSURE_SUCCESS(rv
, rv
);
213 aStr
.AppendLiteral("]]");
217 //////////////////////////////////////////
218 // Methods implementing nsISerializable //
219 //////////////////////////////////////////
221 // We've had way too many issues with unversioned serializations, so
222 // explicitly version this one.
223 static const uint32_t kSerializationVersion
= 1;
226 ExpandedPrincipal::Deserializer::Read(nsIObjectInputStream
* aStream
) {
228 nsresult rv
= aStream
->Read32(&version
);
229 if (version
!= kSerializationVersion
) {
231 "We really need to add handling of the old(?) version here");
232 return NS_ERROR_UNEXPECTED
;
236 rv
= aStream
->Read32(&count
);
241 nsTArray
<nsCOMPtr
<nsIPrincipal
>> principals
;
242 if (!principals
.SetCapacity(count
, fallible
)) {
243 return NS_ERROR_OUT_OF_MEMORY
;
247 for (uint32_t i
= 0; i
< count
; ++i
) {
248 nsCOMPtr
<nsISupports
> read
;
249 rv
= aStream
->ReadObject(true, getter_AddRefs(read
));
254 nsCOMPtr
<nsIPrincipal
> principal
= do_QueryInterface(read
);
256 return NS_ERROR_UNEXPECTED
;
259 // Play it safe and InsertElementSorted, in case the sort order
260 // changed for some bizarre reason.
261 principals
.InsertElementSorted(std::move(principal
), c
);
264 mPrincipal
= ExpandedPrincipal::Create(principals
, OriginAttributes());
268 nsresult
ExpandedPrincipal::GetSiteIdentifier(SiteIdentifier
& aSite
) {
269 // Call GetSiteIdentifier on each of our principals and return a new
270 // ExpandedPrincipal.
272 nsTArray
<nsCOMPtr
<nsIPrincipal
>> allowlist
;
273 for (const auto& principal
: mPrincipals
) {
275 nsresult rv
= Cast(principal
)->GetSiteIdentifier(site
);
276 NS_ENSURE_SUCCESS(rv
, rv
);
277 allowlist
.AppendElement(site
.GetPrincipal());
280 RefPtr
<ExpandedPrincipal
> expandedPrincipal
=
281 ExpandedPrincipal::Create(allowlist
, OriginAttributesRef());
282 MOZ_ASSERT(expandedPrincipal
, "ExpandedPrincipal::Create returned nullptr?");
284 aSite
.Init(expandedPrincipal
);
288 nsresult
ExpandedPrincipal::PopulateJSONObject(Json::Value
& aObject
) {
289 nsAutoCString principalList
;
290 // First item through we have a blank separator and append the next result
292 for (auto& principal
: mPrincipals
) {
294 BasePrincipal::Cast(principal
)->ToJSON(JSON
);
295 // This is blank for the first run through so the last in the list doesn't
297 principalList
.Append(sep
);
299 // Values currently only copes with strings so encode into base64 to allow a
302 rv
= Base64EncodeAppend(JSON
, principalList
);
303 NS_ENSURE_SUCCESS(rv
, rv
);
305 aObject
[std::to_string(eSpecs
)] = principalList
.get();
307 nsAutoCString suffix
;
308 OriginAttributesRef().CreateSuffix(suffix
);
309 if (suffix
.Length() > 0) {
310 aObject
[std::to_string(eSuffix
)] = suffix
.get();
316 already_AddRefed
<BasePrincipal
> ExpandedPrincipal::FromProperties(
317 nsTArray
<ExpandedPrincipal::KeyVal
>& aFields
) {
318 MOZ_ASSERT(aFields
.Length() == eMax
+ 1, "Must have all the keys");
319 nsTArray
<nsCOMPtr
<nsIPrincipal
>> allowList
;
320 OriginAttributes attrs
;
321 // The odd structure here is to make the code to not compile
322 // if all the switch enum cases haven't been codified
323 for (const auto& field
: aFields
) {
325 case ExpandedPrincipal::eSpecs
:
326 if (!field
.valueWasSerialized
) {
328 "Expanded principals require specs in serialized JSON");
331 for (const nsACString
& each
: field
.value
.Split(',')) {
332 nsAutoCString result
;
334 rv
= Base64Decode(each
, result
);
335 MOZ_ASSERT(NS_SUCCEEDED(rv
), "failed to decode");
337 NS_ENSURE_SUCCESS(rv
, nullptr);
338 nsCOMPtr
<nsIPrincipal
> principal
= BasePrincipal::FromJSON(result
);
339 allowList
.AppendElement(principal
);
342 case ExpandedPrincipal::eSuffix
:
343 if (field
.valueWasSerialized
) {
344 bool ok
= attrs
.PopulateFromSuffix(field
.value
);
353 if (allowList
.Length() == 0) {
357 RefPtr
<ExpandedPrincipal
> expandedPrincipal
=
358 ExpandedPrincipal::Create(allowList
, attrs
);
360 return expandedPrincipal
.forget();
364 ExpandedPrincipal::IsThirdPartyURI(nsIURI
* aURI
, bool* aRes
) {
365 // ExpandedPrincipal for extension content scripts consist of two principals,
366 // the document's principal and the extension's principal.
367 // To make sure that the third-party check behaves like the web page on which
368 // the content script is running, ignore the extension's principal.
370 for (const auto& principal
: mPrincipals
) {
371 if (!Cast(principal
)->AddonPolicy()) {
372 return Cast(principal
)->IsThirdPartyURI(aURI
, aRes
);
376 if (mPrincipals
.IsEmpty()) {
381 return Cast(mPrincipals
[0])->IsThirdPartyURI(aURI
, aRes
);