Bug 1735777 [wpt PR 31236] - webrtc wpt: fix invalid unicode indexOf method call...
[gecko.git] / caps / ExpandedPrincipal.cpp
blob04e39f91b757db315b068686e162b39c24233a7a
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,
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 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) { mCSP = aCSP; }
176 NS_IMETHODIMP
177 ExpandedPrincipal::GetCsp(nsIContentSecurityPolicy** aCsp) {
178 NS_IF_ADDREF(*aCsp = mCSP);
179 return NS_OK;
182 nsIPrincipal* ExpandedPrincipal::PrincipalToInherit(nsIURI* aRequestedURI) {
183 if (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
189 // allowlist.
190 for (const auto& principal : mPrincipals) {
191 if (Cast(principal)->MayLoadInternal(aRequestedURI)) {
192 return principal;
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) {
202 if (i != 0) {
203 aStr.AppendLiteral(", ");
206 nsAutoCString spec;
207 nsresult rv =
208 nsJSPrincipals::get(mPrincipals.ElementAt(i))->GetScriptLocation(spec);
209 NS_ENSURE_SUCCESS(rv, rv);
211 aStr.Append(spec);
213 aStr.AppendLiteral("]]");
214 return NS_OK;
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;
225 NS_IMETHODIMP
226 ExpandedPrincipal::Deserializer::Read(nsIObjectInputStream* aStream) {
227 uint32_t version;
228 nsresult rv = aStream->Read32(&version);
229 if (version != kSerializationVersion) {
230 MOZ_ASSERT(false,
231 "We really need to add handling of the old(?) version here");
232 return NS_ERROR_UNEXPECTED;
235 uint32_t count;
236 rv = aStream->Read32(&count);
237 if (NS_FAILED(rv)) {
238 return rv;
241 nsTArray<nsCOMPtr<nsIPrincipal>> principals;
242 if (!principals.SetCapacity(count, fallible)) {
243 return NS_ERROR_OUT_OF_MEMORY;
246 OriginComparator c;
247 for (uint32_t i = 0; i < count; ++i) {
248 nsCOMPtr<nsISupports> read;
249 rv = aStream->ReadObject(true, getter_AddRefs(read));
250 if (NS_FAILED(rv)) {
251 return rv;
254 nsCOMPtr<nsIPrincipal> principal = do_QueryInterface(read);
255 if (!principal) {
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());
265 return NS_OK;
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) {
274 SiteIdentifier site;
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);
285 return NS_OK;
288 nsresult ExpandedPrincipal::PopulateJSONObject(Json::Value& aObject) {
289 nsAutoCString principalList;
290 // First item through we have a blank separator and append the next result
291 nsAutoCString sep;
292 for (auto& principal : mPrincipals) {
293 nsAutoCString JSON;
294 BasePrincipal::Cast(principal)->ToJSON(JSON);
295 // This is blank for the first run through so the last in the list doesn't
296 // add a separator
297 principalList.Append(sep);
298 sep = ',';
299 // Values currently only copes with strings so encode into base64 to allow a
300 // CSV safely.
301 nsresult rv;
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();
313 return NS_OK;
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) {
324 switch (field.key) {
325 case ExpandedPrincipal::eSpecs:
326 if (!field.valueWasSerialized) {
327 MOZ_ASSERT(false,
328 "Expanded principals require specs in serialized JSON");
329 return nullptr;
331 for (const nsACString& each : field.value.Split(',')) {
332 nsAutoCString result;
333 nsresult rv;
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);
341 break;
342 case ExpandedPrincipal::eSuffix:
343 if (field.valueWasSerialized) {
344 bool ok = attrs.PopulateFromSuffix(field.value);
345 if (!ok) {
346 return nullptr;
349 break;
353 if (allowList.Length() == 0) {
354 return nullptr;
357 RefPtr<ExpandedPrincipal> expandedPrincipal =
358 ExpandedPrincipal::Create(allowList, attrs);
360 return expandedPrincipal.forget();
363 NS_IMETHODIMP
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()) {
377 *aRes = true;
378 return NS_OK;
381 return Cast(mPrincipals[0])->IsThirdPartyURI(aURI, aRes);