Bug 1724844 [wpt PR 29961] - Fuzzy match for css/css-position/position-absolute-ifram...
[gecko.git] / caps / BasePrincipal.h
blob645159fe6efe049728412728387a845beec0de1a
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 IsL10nAllowed(nsIURI* aURI, bool* aResult) override;
137 NS_IMETHOD GetAboutModuleFlags(uint32_t* flags) override;
138 NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
139 NS_IMETHOD GetOriginAttributes(JSContext* aCx,
140 JS::MutableHandle<JS::Value> aVal) final;
141 NS_IMETHOD GetAsciiSpec(nsACString& aSpec) override;
142 NS_IMETHOD GetSpec(nsACString& aSpec) override;
143 NS_IMETHOD GetExposablePrePath(nsACString& aResult) override;
144 NS_IMETHOD GetExposableSpec(nsACString& aSpec) override;
145 NS_IMETHOD GetHostPort(nsACString& aRes) override;
146 NS_IMETHOD GetHost(nsACString& aRes) override;
147 NS_IMETHOD GetPrePath(nsACString& aResult) override;
148 NS_IMETHOD GetFilePath(nsACString& aResult) override;
149 NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
150 NS_IMETHOD GetIsIpAddress(bool* aIsIpAddress) override;
151 NS_IMETHOD GetIsLocalIpAddress(bool* aIsIpAddress) override;
152 NS_IMETHOD GetIsOnion(bool* aIsOnion) override;
153 NS_IMETHOD GetIsInIsolatedMozBrowserElement(
154 bool* aIsInIsolatedMozBrowserElement) final;
155 NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
156 NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
157 NS_IMETHOD GetSiteOrigin(nsACString& aSiteOrigin) final;
158 NS_IMETHOD GetSiteOriginNoSuffix(nsACString& aSiteOrigin) override;
159 NS_IMETHOD IsThirdPartyURI(nsIURI* uri, bool* aRes) override;
160 NS_IMETHOD IsThirdPartyPrincipal(nsIPrincipal* uri, bool* aRes) override;
161 NS_IMETHOD IsThirdPartyChannel(nsIChannel* aChannel, bool* aRes) override;
162 NS_IMETHOD GetIsOriginPotentiallyTrustworthy(bool* aResult) override;
163 NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool aIsPrivateWin,
164 bool* aRes) override;
165 NS_IMETHOD GetPrefLightCacheKey(nsIURI* aURI, bool aWithCredentials,
166 const OriginAttributes& aOriginAttributes,
167 nsACString& _retval) override;
168 NS_IMETHOD HasFirstpartyStorageAccess(mozIDOMWindow* aCheckWindow,
169 uint32_t* aRejectedReason,
170 bool* aOutAllowed) override;
171 NS_IMETHOD GetAsciiHost(nsACString& aAsciiHost) override;
172 NS_IMETHOD GetLocalStorageQuotaKey(nsACString& aRes) override;
173 NS_IMETHOD AllowsRelaxStrictFileOriginPolicy(nsIURI* aURI,
174 bool* aRes) override;
175 NS_IMETHOD CreateReferrerInfo(mozilla::dom::ReferrerPolicy aReferrerPolicy,
176 nsIReferrerInfo** _retval) override;
177 NS_IMETHOD GetIsScriptAllowedByPolicy(
178 bool* aIsScriptAllowedByPolicy) override;
179 NS_IMETHOD GetStorageOriginKey(nsACString& aOriginKey) override;
181 NS_IMETHOD GetNextSubDomainPrincipal(
182 nsIPrincipal** aNextSubDomainPrincipal) override;
184 NS_IMETHOD GetPrecursorPrincipal(nsIPrincipal** aPrecursor) override;
186 nsresult ToJSON(nsACString& aJSON);
187 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
188 // Method populates a passed Json::Value with serializable fields
189 // which represent all of the fields to deserialize the principal
190 virtual nsresult PopulateJSONObject(Json::Value& aObject);
192 virtual bool AddonHasPermission(const nsAtom* aPerm);
194 virtual bool IsContentPrincipal() const { return false; };
196 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
197 return static_cast<BasePrincipal*>(aPrin);
200 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
201 return *static_cast<BasePrincipal*>(&aPrin);
204 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
205 return static_cast<const BasePrincipal*>(aPrin);
208 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
209 return *static_cast<const BasePrincipal*>(&aPrin);
212 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
213 const nsACString& aOrigin);
215 // These following method may not create a content principal in case it's
216 // not possible to generate a correct origin from the passed URI. If this
217 // happens, a NullPrincipal is returned.
219 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
220 nsIURI* aURI, const OriginAttributes& aAttrs);
222 const OriginAttributes& OriginAttributesRef() final {
223 return mOriginAttributes;
225 extensions::WebExtensionPolicy* AddonPolicy();
226 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
227 uint32_t PrivateBrowsingId() const {
228 return mOriginAttributes.mPrivateBrowsingId;
230 bool IsInIsolatedMozBrowserElement() const {
231 return mOriginAttributes.mInIsolatedMozBrowser;
234 PrincipalKind Kind() const { return mKind; }
236 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
237 const OriginAttributes& aOriginAttributes);
239 // If this is an add-on content script principal, returns its AddonPolicy.
240 // Otherwise returns null.
241 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
243 // Helper to check whether this principal is associated with an addon that
244 // allows unprivileged code to load aURI. aExplicit == true will prevent
245 // use of all_urls permission, requiring the domain in its permissions.
246 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
248 // Call these to avoid the cost of virtual dispatch.
249 inline bool FastEquals(nsIPrincipal* aOther);
250 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
251 inline bool FastSubsumes(nsIPrincipal* aOther);
252 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
253 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
254 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
256 // Fast way to check whether we have a system principal.
257 inline bool IsSystemPrincipal() const;
259 // Returns the principal to inherit when a caller with this principal loads
260 // the given URI.
262 // For most principal types, this returns the principal itself. For expanded
263 // principals, it returns the first sub-principal which subsumes the given URI
264 // (or, if no URI is given, the last allowlist principal).
265 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
267 /* Returns true if this principal's CSP should override a document's CSP for
268 * loads that it triggers. Currently true for expanded principals which
269 * subsume the document principal, and add-on content principals regardless
270 * of whether they subsume the document principal.
272 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal) {
273 MOZ_ASSERT(aDocumentPrincipal);
275 // Expanded principals override CSP if and only if they subsume the document
276 // principal.
277 if (mKind == eExpandedPrincipal) {
278 return FastSubsumes(aDocumentPrincipal);
280 // Extension principals always override the CSP non-extension principals.
281 // This is primarily for the sake of their stylesheets, which are usually
282 // loaded from channels and cannot have expanded principals.
283 return (AddonPolicy() &&
284 !BasePrincipal::Cast(aDocumentPrincipal)->AddonPolicy());
287 uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }
288 uint32_t GetOriginSuffixHash() const { return mOriginSuffix->hash(); }
290 virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;
292 protected:
293 BasePrincipal(PrincipalKind aKind, const nsACString& aOriginNoSuffix,
294 const OriginAttributes& aOriginAttributes);
295 BasePrincipal(BasePrincipal* aOther,
296 const OriginAttributes& aOriginAttributes);
298 virtual ~BasePrincipal();
300 // Note that this does not check OriginAttributes. Callers that depend on
301 // those must call Subsumes instead.
302 virtual bool SubsumesInternal(nsIPrincipal* aOther,
303 DocumentDomainConsideration aConsider) = 0;
305 // Internal, side-effect-free check to determine whether the concrete
306 // principal would allow the load ignoring any common behavior implemented in
307 // BasePrincipal::CheckMayLoad.
308 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
309 friend class ::ExpandedPrincipal;
311 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
312 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
313 bool aReport, uint64_t aInnerWindowID);
315 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
317 // KeyValT holds a principal subtype-specific key value and the associated
318 // parsed value after JSON parsing.
319 template <typename SerializedKey>
320 struct KeyValT {
321 static_assert(sizeof(SerializedKey) == 1,
322 "SerializedKey should be a uint8_t");
323 SerializedKey key;
324 bool valueWasSerialized;
325 nsCString value;
328 // Common base class for all Deserializer implementations in concrete
329 // subclasses. Subclasses will initialize `mPrincipal` in `Read`, and then
330 // calls to `QueryInterface` will QI on the target object.
331 class Deserializer : public nsISerializable {
332 public:
333 NS_DECL_ISUPPORTS
334 NS_IMETHOD Write(nsIObjectOutputStream* aStream) override;
336 protected:
337 virtual ~Deserializer() = default;
338 RefPtr<BasePrincipal> mPrincipal;
341 private:
342 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
343 nsIURI* aURI, const OriginAttributes& aAttrs,
344 const nsACString& aOriginNoSuffix);
346 bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther,
347 DocumentDomainConsideration aConsideration);
349 const RefPtr<nsAtom> mOriginNoSuffix;
350 const RefPtr<nsAtom> mOriginSuffix;
352 const OriginAttributes mOriginAttributes;
353 const PrincipalKind mKind;
354 bool mHasExplicitDomain;
357 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
358 MOZ_ASSERT(aOther);
360 auto other = Cast(aOther);
361 if (Kind() != other->Kind()) {
362 // Principals of different kinds can't be equal.
363 return false;
366 // Two principals are considered to be equal if their origins are the same.
367 // If the two principals are content principals, their origin attributes
368 // (aka the origin suffix) must also match.
369 if (Kind() == eSystemPrincipal) {
370 return this == other;
373 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
374 return mOriginNoSuffix == other->mOriginNoSuffix &&
375 mOriginSuffix == other->mOriginSuffix;
378 MOZ_ASSERT(Kind() == eExpandedPrincipal);
379 return mOriginNoSuffix == other->mOriginNoSuffix;
382 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
383 MOZ_ASSERT(aOther);
385 // If neither of the principals have document.domain set, we use the fast path
386 // in Equals(). Otherwise, we fall back to the slow path below.
387 auto other = Cast(aOther);
388 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
389 return FastEquals(aOther);
392 return Subsumes(aOther, ConsiderDocumentDomain) &&
393 other->Subsumes(this, ConsiderDocumentDomain);
396 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
397 MOZ_ASSERT(aOther);
399 // If two principals are equal, then they both subsume each other.
400 if (FastEquals(aOther)) {
401 return true;
404 // Otherwise, fall back to the slow path.
405 return Subsumes(aOther, DontConsiderDocumentDomain);
408 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
409 MOZ_ASSERT(aOther);
411 // If neither of the principals have document.domain set, we hand off to
412 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
413 // fall back to the slow path below.
414 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
415 return FastSubsumes(aOther);
418 return Subsumes(aOther, ConsiderDocumentDomain);
421 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
422 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
425 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
426 nsIPrincipal* aOther) {
427 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
430 inline bool BasePrincipal::IsSystemPrincipal() const {
431 return Kind() == eSystemPrincipal;
434 } // namespace mozilla
436 inline bool nsIPrincipal::IsSystemPrincipal() const {
437 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
440 #endif /* mozilla_BasePrincipal_h */