Bug 1597285 test each of audio, video, audio+video combinations r=jib
[gecko.git] / caps / ExpandedPrincipal.cpp
blob8c2ef4628aef295b0e06d25cd816e2cb62fdb448
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"
13 using namespace mozilla;
15 NS_IMPL_CLASSINFO(ExpandedPrincipal, nullptr, nsIClassInfo::MAIN_THREAD_ONLY,
16 NS_EXPANDEDPRINCIPAL_CID)
17 NS_IMPL_QUERY_INTERFACE_CI(ExpandedPrincipal, nsIPrincipal,
18 nsIExpandedPrincipal)
19 NS_IMPL_CI_INTERFACE_GETTER(ExpandedPrincipal, nsIPrincipal,
20 nsIExpandedPrincipal)
22 struct OriginComparator {
23 bool LessThan(nsIPrincipal* a, nsIPrincipal* b) const {
24 nsAutoCString originA;
25 DebugOnly<nsresult> rv = a->GetOrigin(originA);
26 MOZ_ASSERT(NS_SUCCEEDED(rv));
27 nsAutoCString originB;
28 rv = b->GetOrigin(originB);
29 MOZ_ASSERT(NS_SUCCEEDED(rv));
30 return originA < originB;
33 bool Equals(nsIPrincipal* a, nsIPrincipal* b) const {
34 nsAutoCString originA;
35 DebugOnly<nsresult> rv = a->GetOrigin(originA);
36 MOZ_ASSERT(NS_SUCCEEDED(rv));
37 nsAutoCString originB;
38 rv = b->GetOrigin(originB);
39 MOZ_ASSERT(NS_SUCCEEDED(rv));
40 return a == b;
44 ExpandedPrincipal::ExpandedPrincipal(
45 nsTArray<nsCOMPtr<nsIPrincipal>>&& aPrincipals,
46 const nsACString& aOriginNoSuffix, const OriginAttributes& aAttrs)
47 : BasePrincipal(eExpandedPrincipal, aOriginNoSuffix, aAttrs),
48 mPrincipals(std::move(aPrincipals)) {}
50 ExpandedPrincipal::~ExpandedPrincipal() = default;
52 already_AddRefed<ExpandedPrincipal> ExpandedPrincipal::Create(
53 nsTArray<nsCOMPtr<nsIPrincipal>>& aAllowList,
54 const OriginAttributes& aAttrs) {
55 // We force the principals to be sorted by origin so that ExpandedPrincipal
56 // origins can have a canonical form.
57 nsTArray<nsCOMPtr<nsIPrincipal>> principals;
58 OriginComparator c;
59 for (size_t i = 0; i < aAllowList.Length(); ++i) {
60 principals.InsertElementSorted(aAllowList[i], c);
63 nsAutoCString origin;
64 origin.AssignLiteral("[Expanded Principal [");
65 StringJoinAppend(
66 origin, ", "_ns, principals,
67 [](nsACString& dest, const nsCOMPtr<nsIPrincipal>& principal) {
68 nsAutoCString subOrigin;
69 DebugOnly<nsresult> rv = principal->GetOrigin(subOrigin);
70 MOZ_ASSERT(NS_SUCCEEDED(rv));
71 dest.Append(subOrigin);
72 });
73 origin.AppendLiteral("]]");
75 RefPtr<ExpandedPrincipal> ep =
76 new ExpandedPrincipal(std::move(principals), origin, aAttrs);
77 return ep.forget();
80 NS_IMETHODIMP
81 ExpandedPrincipal::GetDomain(nsIURI** aDomain) {
82 *aDomain = nullptr;
83 return NS_OK;
86 NS_IMETHODIMP
87 ExpandedPrincipal::SetDomain(nsIURI* aDomain) { return NS_OK; }
89 bool ExpandedPrincipal::SubsumesInternal(
90 nsIPrincipal* aOther,
91 BasePrincipal::DocumentDomainConsideration aConsideration) {
92 // If aOther is an ExpandedPrincipal too, we break it down into its component
93 // nsIPrincipals, and check subsumes on each one.
94 if (Cast(aOther)->Is<ExpandedPrincipal>()) {
95 auto* expanded = Cast(aOther)->As<ExpandedPrincipal>();
97 for (auto& other : expanded->AllowList()) {
98 // Use SubsumesInternal rather than Subsumes here, since OriginAttribute
99 // checks are only done between non-expanded sub-principals, and we don't
100 // need to incur the extra virtual call overhead.
101 if (!SubsumesInternal(other, aConsideration)) {
102 return false;
105 return true;
108 // We're dealing with a regular principal. One of our principals must subsume
109 // it.
110 for (uint32_t i = 0; i < mPrincipals.Length(); ++i) {
111 if (Cast(mPrincipals[i])->Subsumes(aOther, aConsideration)) {
112 return true;
116 return false;
119 bool ExpandedPrincipal::MayLoadInternal(nsIURI* uri) {
120 for (uint32_t i = 0; i < mPrincipals.Length(); ++i) {
121 if (BasePrincipal::Cast(mPrincipals[i])->MayLoadInternal(uri)) {
122 return true;
126 return false;
129 uint32_t ExpandedPrincipal::GetHashValue() {
130 MOZ_CRASH("extended principal should never be used as key in a hash map");
133 NS_IMETHODIMP
134 ExpandedPrincipal::GetURI(nsIURI** aURI) {
135 *aURI = nullptr;
136 return NS_OK;
139 const nsTArray<nsCOMPtr<nsIPrincipal>>& ExpandedPrincipal::AllowList() {
140 return mPrincipals;
143 NS_IMETHODIMP
144 ExpandedPrincipal::GetBaseDomain(nsACString& aBaseDomain) {
145 return NS_ERROR_NOT_AVAILABLE;
148 NS_IMETHODIMP
149 ExpandedPrincipal::GetAddonId(nsAString& aAddonId) {
150 aAddonId.Truncate();
151 return NS_OK;
154 bool ExpandedPrincipal::AddonHasPermission(const nsAtom* aPerm) {
155 for (size_t i = 0; i < mPrincipals.Length(); ++i) {
156 if (BasePrincipal::Cast(mPrincipals[i])->AddonHasPermission(aPerm)) {
157 return true;
160 return false;
163 bool ExpandedPrincipal::AddonAllowsLoad(nsIURI* aURI,
164 bool aExplicit /* = false */) {
165 for (const auto& principal : mPrincipals) {
166 if (Cast(principal)->AddonAllowsLoad(aURI, aExplicit)) {
167 return true;
170 return false;
173 void ExpandedPrincipal::SetCsp(nsIContentSecurityPolicy* aCSP) { mCSP = aCSP; }
175 NS_IMETHODIMP
176 ExpandedPrincipal::GetCsp(nsIContentSecurityPolicy** aCsp) {
177 NS_IF_ADDREF(*aCsp = mCSP);
178 return NS_OK;
181 nsIPrincipal* ExpandedPrincipal::PrincipalToInherit(nsIURI* aRequestedURI) {
182 if (aRequestedURI) {
183 // If a given sub-principal subsumes the given URI, use that principal for
184 // inheritance. In general, this only happens with certain CORS modes, loads
185 // with forced principal inheritance, and creation of XML documents from
186 // XMLHttpRequests or fetch requests. For URIs that normally inherit a
187 // principal (such as data: URIs), we fall back to the last principal in the
188 // allowlist.
189 for (const auto& principal : mPrincipals) {
190 if (Cast(principal)->MayLoadInternal(aRequestedURI)) {
191 return principal;
195 return mPrincipals.LastElement();
198 nsresult ExpandedPrincipal::GetScriptLocation(nsACString& aStr) {
199 aStr.AssignLiteral("[Expanded Principal [");
200 for (size_t i = 0; i < mPrincipals.Length(); ++i) {
201 if (i != 0) {
202 aStr.AppendLiteral(", ");
205 nsAutoCString spec;
206 nsresult rv =
207 nsJSPrincipals::get(mPrincipals.ElementAt(i))->GetScriptLocation(spec);
208 NS_ENSURE_SUCCESS(rv, rv);
210 aStr.Append(spec);
212 aStr.AppendLiteral("]]");
213 return NS_OK;
216 //////////////////////////////////////////
217 // Methods implementing nsISerializable //
218 //////////////////////////////////////////
220 // We've had way too many issues with unversioned serializations, so
221 // explicitly version this one.
222 static const uint32_t kSerializationVersion = 1;
224 NS_IMETHODIMP
225 ExpandedPrincipal::Deserializer::Read(nsIObjectInputStream* aStream) {
226 uint32_t version;
227 nsresult rv = aStream->Read32(&version);
228 if (version != kSerializationVersion) {
229 MOZ_ASSERT(false,
230 "We really need to add handling of the old(?) version here");
231 return NS_ERROR_UNEXPECTED;
234 uint32_t count;
235 rv = aStream->Read32(&count);
236 if (NS_FAILED(rv)) {
237 return rv;
240 nsTArray<nsCOMPtr<nsIPrincipal>> principals;
241 if (!principals.SetCapacity(count, fallible)) {
242 return NS_ERROR_OUT_OF_MEMORY;
245 OriginComparator c;
246 for (uint32_t i = 0; i < count; ++i) {
247 nsCOMPtr<nsISupports> read;
248 rv = aStream->ReadObject(true, getter_AddRefs(read));
249 if (NS_FAILED(rv)) {
250 return rv;
253 nsCOMPtr<nsIPrincipal> principal = do_QueryInterface(read);
254 if (!principal) {
255 return NS_ERROR_UNEXPECTED;
258 // Play it safe and InsertElementSorted, in case the sort order
259 // changed for some bizarre reason.
260 principals.InsertElementSorted(std::move(principal), c);
263 mPrincipal = ExpandedPrincipal::Create(principals, OriginAttributes());
264 return NS_OK;
267 nsresult ExpandedPrincipal::GetSiteIdentifier(SiteIdentifier& aSite) {
268 // Call GetSiteIdentifier on each of our principals and return a new
269 // ExpandedPrincipal.
271 nsTArray<nsCOMPtr<nsIPrincipal>> allowlist;
272 for (const auto& principal : mPrincipals) {
273 SiteIdentifier site;
274 nsresult rv = Cast(principal)->GetSiteIdentifier(site);
275 NS_ENSURE_SUCCESS(rv, rv);
276 allowlist.AppendElement(site.GetPrincipal());
279 RefPtr<ExpandedPrincipal> expandedPrincipal =
280 ExpandedPrincipal::Create(allowlist, OriginAttributesRef());
281 MOZ_ASSERT(expandedPrincipal, "ExpandedPrincipal::Create returned nullptr?");
283 aSite.Init(expandedPrincipal);
284 return NS_OK;
287 nsresult ExpandedPrincipal::PopulateJSONObject(Json::Value& aObject) {
288 nsAutoCString principalList;
289 // First item through we have a blank separator and append the next result
290 nsAutoCString sep;
291 for (auto& principal : mPrincipals) {
292 nsAutoCString JSON;
293 BasePrincipal::Cast(principal)->ToJSON(JSON);
294 // This is blank for the first run through so the last in the list doesn't
295 // add a separator
296 principalList.Append(sep);
297 sep = ',';
298 // Values currently only copes with strings so encode into base64 to allow a
299 // CSV safely.
300 nsresult rv;
301 rv = Base64EncodeAppend(JSON, principalList);
302 NS_ENSURE_SUCCESS(rv, rv);
304 aObject[std::to_string(eSpecs)] = principalList.get();
306 nsAutoCString suffix;
307 OriginAttributesRef().CreateSuffix(suffix);
308 if (suffix.Length() > 0) {
309 aObject[std::to_string(eSuffix)] = suffix.get();
312 return NS_OK;
315 already_AddRefed<BasePrincipal> ExpandedPrincipal::FromProperties(
316 nsTArray<ExpandedPrincipal::KeyVal>& aFields) {
317 MOZ_ASSERT(aFields.Length() == eMax + 1, "Must have all the keys");
318 nsTArray<nsCOMPtr<nsIPrincipal>> allowList;
319 OriginAttributes attrs;
320 // The odd structure here is to make the code to not compile
321 // 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 NS_IMETHODIMP
363 ExpandedPrincipal::IsThirdPartyURI(nsIURI* aURI, bool* aRes) {
364 // ExpandedPrincipal for extension content scripts consist of two principals,
365 // the document's principal and the extension's principal.
366 // To make sure that the third-party check behaves like the web page on which
367 // the content script is running, ignore the extension's principal.
369 for (const auto& principal : mPrincipals) {
370 if (!Cast(principal)->AddonPolicy()) {
371 return Cast(principal)->IsThirdPartyURI(aURI, aRes);
375 if (mPrincipals.IsEmpty()) {
376 *aRes = true;
377 return NS_OK;
380 return Cast(mPrincipals[0])->IsThirdPartyURI(aURI, aRes);