Bug 1735777 [wpt PR 31236] - webrtc wpt: fix invalid unicode indexOf method call...
[gecko.git] / caps / BasePrincipal.h
blobe8835418b5d9179fca193b832e0fe4ce209be697
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 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 #ifndef mozilla_BasePrincipal_h
8 #define mozilla_BasePrincipal_h
10 #include <stdint.h>
11 #include "ErrorList.h"
12 #include "js/TypeDecls.h"
13 #include "mozilla/AlreadyAddRefed.h"
14 #include "mozilla/Assertions.h"
15 #include "mozilla/OriginAttributes.h"
16 #include "mozilla/RefPtr.h"
17 #include "nsAtom.h"
18 #include "nsIObjectOutputStream.h"
19 #include "nsIPrincipal.h"
20 #include "nsJSPrincipals.h"
21 #include "nsStringFwd.h"
22 #include "nscore.h"
24 class ExpandedPrincipal;
25 class mozIDOMWindow;
26 class nsIChannel;
27 class nsIReferrerInfo;
28 class nsISupports;
29 class nsIURI;
30 namespace Json {
31 class Value;
34 namespace mozilla {
36 namespace dom {
37 enum class ReferrerPolicy : uint8_t;
40 namespace extensions {
41 class WebExtensionPolicy;
44 class BasePrincipal;
46 // Content principals (and content principals embedded within expanded
47 // principals) stored in SiteIdentifier are guaranteed to contain only the
48 // eTLD+1 part of the original domain. This is used to determine whether two
49 // origins are same-site: if it's possible for two origins to access each other
50 // (maybe after mutating document.domain), then they must have the same site
51 // identifier.
52 class SiteIdentifier {
53 public:
54 void Init(BasePrincipal* aPrincipal) {
55 MOZ_ASSERT(aPrincipal);
56 mPrincipal = aPrincipal;
59 bool IsInitialized() const { return !!mPrincipal; }
61 bool Equals(const SiteIdentifier& aOther) const;
63 private:
64 friend class ::ExpandedPrincipal;
66 BasePrincipal* GetPrincipal() const {
67 MOZ_ASSERT(IsInitialized());
68 return mPrincipal;
71 RefPtr<BasePrincipal> mPrincipal;
75 * Base class from which all nsIPrincipal implementations inherit. Use this for
76 * default implementations and other commonalities between principal
77 * implementations.
79 * We should merge nsJSPrincipals into this class at some point.
81 class BasePrincipal : public nsJSPrincipals {
82 public:
83 // Warning: this enum impacts Principal serialization into JSON format.
84 // Only update if you know exactly what you are doing
85 enum PrincipalKind {
86 eNullPrincipal = 0,
87 eContentPrincipal,
88 eExpandedPrincipal,
89 eSystemPrincipal,
90 eKindMax = eSystemPrincipal
93 template <typename T>
94 bool Is() const {
95 return mKind == T::Kind();
98 template <typename T>
99 T* As() {
100 MOZ_ASSERT(Is<T>());
101 return static_cast<T*>(this);
104 enum DocumentDomainConsideration {
105 DontConsiderDocumentDomain,
106 ConsiderDocumentDomain
108 bool Subsumes(nsIPrincipal* aOther,
109 DocumentDomainConsideration aConsideration);
111 NS_IMETHOD GetOrigin(nsACString& aOrigin) final;
112 NS_IMETHOD GetAsciiOrigin(nsACString& aOrigin) override;
113 NS_IMETHOD GetOriginNoSuffix(nsACString& aOrigin) final;
114 NS_IMETHOD Equals(nsIPrincipal* other, bool* _retval) final;
115 NS_IMETHOD EqualsConsideringDomain(nsIPrincipal* other, bool* _retval) final;
116 NS_IMETHOD EqualsURI(nsIURI* aOtherURI, bool* _retval) override;
117 NS_IMETHOD EqualsForPermission(nsIPrincipal* other, bool aExactHost,
118 bool* _retval) final;
119 NS_IMETHOD Subsumes(nsIPrincipal* other, bool* _retval) final;
120 NS_IMETHOD SubsumesConsideringDomain(nsIPrincipal* other,
121 bool* _retval) final;
122 NS_IMETHOD SubsumesConsideringDomainIgnoringFPD(nsIPrincipal* other,
123 bool* _retval) final;
124 NS_IMETHOD CheckMayLoad(nsIURI* uri, bool allowIfInheritsPrincipal) final;
125 NS_IMETHOD CheckMayLoadWithReporting(nsIURI* uri,
126 bool allowIfInheritsPrincipal,
127 uint64_t innerWindowID) final;
128 NS_IMETHOD GetAddonPolicy(extensions::WebExtensionPolicy** aResult) final;
129 NS_IMETHOD GetIsNullPrincipal(bool* aResult) override;
130 NS_IMETHOD GetIsContentPrincipal(bool* aResult) override;
131 NS_IMETHOD GetIsExpandedPrincipal(bool* aResult) override;
132 NS_IMETHOD GetIsSystemPrincipal(bool* aResult) override;
133 NS_IMETHOD GetScheme(nsACString& aScheme) override;
134 NS_IMETHOD SchemeIs(const char* aScheme, bool* aResult) override;
135 NS_IMETHOD IsURIInPrefList(const char* aPref, bool* aResult) override;
136 NS_IMETHOD IsURIInList(const nsACString& aList, bool* aResult) override;
137 NS_IMETHOD IsL10nAllowed(nsIURI* aURI, bool* aResult) override;
138 NS_IMETHOD GetAboutModuleFlags(uint32_t* flags) override;
139 NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
140 NS_IMETHOD GetOriginAttributes(JSContext* aCx,
141 JS::MutableHandle<JS::Value> aVal) final;
142 NS_IMETHOD GetAsciiSpec(nsACString& aSpec) override;
143 NS_IMETHOD GetSpec(nsACString& aSpec) override;
144 NS_IMETHOD GetExposablePrePath(nsACString& aResult) override;
145 NS_IMETHOD GetExposableSpec(nsACString& aSpec) override;
146 NS_IMETHOD GetHostPort(nsACString& aRes) override;
147 NS_IMETHOD GetHost(nsACString& aRes) override;
148 NS_IMETHOD GetPrePath(nsACString& aResult) override;
149 NS_IMETHOD GetFilePath(nsACString& aResult) override;
150 NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
151 NS_IMETHOD GetIsIpAddress(bool* aIsIpAddress) override;
152 NS_IMETHOD GetIsLocalIpAddress(bool* aIsIpAddress) override;
153 NS_IMETHOD GetIsOnion(bool* aIsOnion) override;
154 NS_IMETHOD GetIsInIsolatedMozBrowserElement(
155 bool* aIsInIsolatedMozBrowserElement) final;
156 NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
157 NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
158 NS_IMETHOD GetSiteOrigin(nsACString& aSiteOrigin) final;
159 NS_IMETHOD GetSiteOriginNoSuffix(nsACString& aSiteOrigin) override;
160 NS_IMETHOD IsThirdPartyURI(nsIURI* uri, bool* aRes) override;
161 NS_IMETHOD IsThirdPartyPrincipal(nsIPrincipal* uri, bool* aRes) override;
162 NS_IMETHOD IsThirdPartyChannel(nsIChannel* aChannel, bool* aRes) override;
163 NS_IMETHOD GetIsOriginPotentiallyTrustworthy(bool* aResult) override;
164 NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool aIsPrivateWin,
165 bool* aRes) override;
166 NS_IMETHOD GetPrefLightCacheKey(nsIURI* aURI, bool aWithCredentials,
167 const OriginAttributes& aOriginAttributes,
168 nsACString& _retval) override;
169 NS_IMETHOD HasFirstpartyStorageAccess(mozIDOMWindow* aCheckWindow,
170 uint32_t* aRejectedReason,
171 bool* aOutAllowed) override;
172 NS_IMETHOD GetAsciiHost(nsACString& aAsciiHost) override;
173 NS_IMETHOD GetLocalStorageQuotaKey(nsACString& aRes) override;
174 NS_IMETHOD AllowsRelaxStrictFileOriginPolicy(nsIURI* aURI,
175 bool* aRes) override;
176 NS_IMETHOD CreateReferrerInfo(mozilla::dom::ReferrerPolicy aReferrerPolicy,
177 nsIReferrerInfo** _retval) override;
178 NS_IMETHOD GetIsScriptAllowedByPolicy(
179 bool* aIsScriptAllowedByPolicy) override;
180 NS_IMETHOD GetStorageOriginKey(nsACString& aOriginKey) override;
182 NS_IMETHOD GetNextSubDomainPrincipal(
183 nsIPrincipal** aNextSubDomainPrincipal) override;
185 NS_IMETHOD GetPrecursorPrincipal(nsIPrincipal** aPrecursor) override;
187 nsresult ToJSON(nsACString& aJSON);
188 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
189 // Method populates a passed Json::Value with serializable fields
190 // which represent all of the fields to deserialize the principal
191 virtual nsresult PopulateJSONObject(Json::Value& aObject);
193 virtual bool AddonHasPermission(const nsAtom* aPerm);
195 virtual bool IsContentPrincipal() const { return false; };
197 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
198 return static_cast<BasePrincipal*>(aPrin);
201 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
202 return *static_cast<BasePrincipal*>(&aPrin);
205 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
206 return static_cast<const BasePrincipal*>(aPrin);
209 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
210 return *static_cast<const BasePrincipal*>(&aPrin);
213 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
214 const nsACString& aOrigin);
216 // These following method may not create a content principal in case it's
217 // not possible to generate a correct origin from the passed URI. If this
218 // happens, a NullPrincipal is returned.
220 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
221 nsIURI* aURI, const OriginAttributes& aAttrs);
223 const OriginAttributes& OriginAttributesRef() final {
224 return mOriginAttributes;
226 extensions::WebExtensionPolicy* AddonPolicy();
227 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
228 uint32_t PrivateBrowsingId() const {
229 return mOriginAttributes.mPrivateBrowsingId;
231 bool IsInIsolatedMozBrowserElement() const {
232 return mOriginAttributes.mInIsolatedMozBrowser;
235 PrincipalKind Kind() const { return mKind; }
237 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
238 const OriginAttributes& aOriginAttributes);
240 // If this is an add-on content script principal, returns its AddonPolicy.
241 // Otherwise returns null.
242 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
244 // Helper to check whether this principal is associated with an addon that
245 // allows unprivileged code to load aURI. aExplicit == true will prevent
246 // use of all_urls permission, requiring the domain in its permissions.
247 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
249 // Call these to avoid the cost of virtual dispatch.
250 inline bool FastEquals(nsIPrincipal* aOther);
251 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
252 inline bool FastSubsumes(nsIPrincipal* aOther);
253 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
254 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
255 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
257 // Fast way to check whether we have a system principal.
258 inline bool IsSystemPrincipal() const;
260 // Returns the principal to inherit when a caller with this principal loads
261 // the given URI.
263 // For most principal types, this returns the principal itself. For expanded
264 // principals, it returns the first sub-principal which subsumes the given URI
265 // (or, if no URI is given, the last allowlist principal).
266 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
268 /* Returns true if this principal's CSP should override a document's CSP for
269 * loads that it triggers. Currently true for expanded principals which
270 * subsume the document principal, and add-on content principals regardless
271 * of whether they subsume the document principal.
273 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal) {
274 MOZ_ASSERT(aDocumentPrincipal);
276 // Expanded principals override CSP if and only if they subsume the document
277 // principal.
278 if (mKind == eExpandedPrincipal) {
279 return FastSubsumes(aDocumentPrincipal);
281 // Extension principals always override the CSP non-extension principals.
282 // This is primarily for the sake of their stylesheets, which are usually
283 // loaded from channels and cannot have expanded principals.
284 return (AddonPolicy() &&
285 !BasePrincipal::Cast(aDocumentPrincipal)->AddonPolicy());
288 uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }
289 uint32_t GetOriginSuffixHash() const { return mOriginSuffix->hash(); }
291 virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;
293 protected:
294 BasePrincipal(PrincipalKind aKind, const nsACString& aOriginNoSuffix,
295 const OriginAttributes& aOriginAttributes);
296 BasePrincipal(BasePrincipal* aOther,
297 const OriginAttributes& aOriginAttributes);
299 virtual ~BasePrincipal();
301 // Note that this does not check OriginAttributes. Callers that depend on
302 // those must call Subsumes instead.
303 virtual bool SubsumesInternal(nsIPrincipal* aOther,
304 DocumentDomainConsideration aConsider) = 0;
306 // Internal, side-effect-free check to determine whether the concrete
307 // principal would allow the load ignoring any common behavior implemented in
308 // BasePrincipal::CheckMayLoad.
309 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
310 friend class ::ExpandedPrincipal;
312 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
313 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
314 bool aReport, uint64_t aInnerWindowID);
316 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
318 // KeyValT holds a principal subtype-specific key value and the associated
319 // parsed value after JSON parsing.
320 template <typename SerializedKey>
321 struct KeyValT {
322 static_assert(sizeof(SerializedKey) == 1,
323 "SerializedKey should be a uint8_t");
324 SerializedKey key;
325 bool valueWasSerialized;
326 nsCString value;
329 // Common base class for all Deserializer implementations in concrete
330 // subclasses. Subclasses will initialize `mPrincipal` in `Read`, and then
331 // calls to `QueryInterface` will QI on the target object.
332 class Deserializer : public nsISerializable {
333 public:
334 NS_DECL_ISUPPORTS
335 NS_IMETHOD Write(nsIObjectOutputStream* aStream) override;
337 protected:
338 virtual ~Deserializer() = default;
339 RefPtr<BasePrincipal> mPrincipal;
342 private:
343 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
344 nsIURI* aURI, const OriginAttributes& aAttrs,
345 const nsACString& aOriginNoSuffix);
347 bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther,
348 DocumentDomainConsideration aConsideration);
350 const RefPtr<nsAtom> mOriginNoSuffix;
351 const RefPtr<nsAtom> mOriginSuffix;
353 const OriginAttributes mOriginAttributes;
354 const PrincipalKind mKind;
355 bool mHasExplicitDomain;
358 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
359 MOZ_ASSERT(aOther);
361 auto other = Cast(aOther);
362 if (Kind() != other->Kind()) {
363 // Principals of different kinds can't be equal.
364 return false;
367 // Two principals are considered to be equal if their origins are the same.
368 // If the two principals are content principals, their origin attributes
369 // (aka the origin suffix) must also match.
370 if (Kind() == eSystemPrincipal) {
371 return this == other;
374 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
375 return mOriginNoSuffix == other->mOriginNoSuffix &&
376 mOriginSuffix == other->mOriginSuffix;
379 MOZ_ASSERT(Kind() == eExpandedPrincipal);
380 return mOriginNoSuffix == other->mOriginNoSuffix;
383 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
384 MOZ_ASSERT(aOther);
386 // If neither of the principals have document.domain set, we use the fast path
387 // in Equals(). Otherwise, we fall back to the slow path below.
388 auto other = Cast(aOther);
389 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
390 return FastEquals(aOther);
393 return Subsumes(aOther, ConsiderDocumentDomain) &&
394 other->Subsumes(this, ConsiderDocumentDomain);
397 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
398 MOZ_ASSERT(aOther);
400 // If two principals are equal, then they both subsume each other.
401 if (FastEquals(aOther)) {
402 return true;
405 // Otherwise, fall back to the slow path.
406 return Subsumes(aOther, DontConsiderDocumentDomain);
409 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
410 MOZ_ASSERT(aOther);
412 // If neither of the principals have document.domain set, we hand off to
413 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
414 // fall back to the slow path below.
415 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
416 return FastSubsumes(aOther);
419 return Subsumes(aOther, ConsiderDocumentDomain);
422 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
423 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
426 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
427 nsIPrincipal* aOther) {
428 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
431 inline bool BasePrincipal::IsSystemPrincipal() const {
432 return Kind() == eSystemPrincipal;
435 } // namespace mozilla
437 inline bool nsIPrincipal::IsSystemPrincipal() const {
438 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
441 #endif /* mozilla_BasePrincipal_h */