Bug 1809861 - Part 3: Reorder off-thread compilation methods r=smaug
[gecko.git] / caps / BasePrincipal.h
blob3b845cb7b43d4493c9989288350d9ff8c1765169
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;
42 class WebExtensionPolicyCore;
43 } // namespace extensions
45 class BasePrincipal;
47 // Content principals (and content principals embedded within expanded
48 // principals) stored in SiteIdentifier are guaranteed to contain only the
49 // eTLD+1 part of the original domain. This is used to determine whether two
50 // origins are same-site: if it's possible for two origins to access each other
51 // (maybe after mutating document.domain), then they must have the same site
52 // identifier.
53 class SiteIdentifier {
54 public:
55 void Init(BasePrincipal* aPrincipal) {
56 MOZ_ASSERT(aPrincipal);
57 mPrincipal = aPrincipal;
60 bool IsInitialized() const { return !!mPrincipal; }
62 bool Equals(const SiteIdentifier& aOther) const;
64 private:
65 friend class ::ExpandedPrincipal;
67 BasePrincipal* GetPrincipal() const {
68 MOZ_ASSERT(IsInitialized());
69 return mPrincipal;
72 RefPtr<BasePrincipal> mPrincipal;
76 * Base class from which all nsIPrincipal implementations inherit. Use this for
77 * default implementations and other commonalities between principal
78 * implementations.
80 * We should merge nsJSPrincipals into this class at some point.
82 class BasePrincipal : public nsJSPrincipals {
83 public:
84 // Warning: this enum impacts Principal serialization into JSON format.
85 // Only update if you know exactly what you are doing
86 enum PrincipalKind {
87 eNullPrincipal = 0,
88 eContentPrincipal,
89 eExpandedPrincipal,
90 eSystemPrincipal,
91 eKindMax = eSystemPrincipal
94 template <typename T>
95 bool Is() const {
96 return mKind == T::Kind();
99 template <typename T>
100 T* As() {
101 MOZ_ASSERT(Is<T>());
102 return static_cast<T*>(this);
105 enum DocumentDomainConsideration {
106 DontConsiderDocumentDomain,
107 ConsiderDocumentDomain
109 bool Subsumes(nsIPrincipal* aOther,
110 DocumentDomainConsideration aConsideration);
112 NS_IMETHOD GetOrigin(nsACString& aOrigin) final;
113 NS_IMETHOD GetAsciiOrigin(nsACString& aOrigin) override;
114 NS_IMETHOD GetOriginNoSuffix(nsACString& aOrigin) final;
115 NS_IMETHOD Equals(nsIPrincipal* other, bool* _retval) final;
116 NS_IMETHOD EqualsConsideringDomain(nsIPrincipal* other, bool* _retval) final;
117 NS_IMETHOD EqualsURI(nsIURI* aOtherURI, bool* _retval) override;
118 NS_IMETHOD EqualsForPermission(nsIPrincipal* other, bool aExactHost,
119 bool* _retval) final;
120 NS_IMETHOD Subsumes(nsIPrincipal* other, bool* _retval) final;
121 NS_IMETHOD SubsumesConsideringDomain(nsIPrincipal* other,
122 bool* _retval) final;
123 NS_IMETHOD SubsumesConsideringDomainIgnoringFPD(nsIPrincipal* other,
124 bool* _retval) final;
125 NS_IMETHOD CheckMayLoad(nsIURI* uri, bool allowIfInheritsPrincipal) final;
126 NS_IMETHOD CheckMayLoadWithReporting(nsIURI* uri,
127 bool allowIfInheritsPrincipal,
128 uint64_t innerWindowID) final;
129 NS_IMETHOD GetAddonPolicy(extensions::WebExtensionPolicy** aResult) final;
130 NS_IMETHOD GetContentScriptAddonPolicy(
131 extensions::WebExtensionPolicy** aResult) final;
132 NS_IMETHOD GetIsNullPrincipal(bool* aResult) override;
133 NS_IMETHOD GetIsContentPrincipal(bool* aResult) override;
134 NS_IMETHOD GetIsExpandedPrincipal(bool* aResult) override;
135 NS_IMETHOD GetIsSystemPrincipal(bool* aResult) override;
136 NS_IMETHOD GetScheme(nsACString& aScheme) override;
137 NS_IMETHOD SchemeIs(const char* aScheme, bool* aResult) override;
138 NS_IMETHOD IsURIInPrefList(const char* aPref, bool* aResult) override;
139 NS_IMETHOD IsURIInList(const nsACString& aList, bool* aResult) override;
140 NS_IMETHOD IsL10nAllowed(nsIURI* aURI, bool* aResult) override;
141 NS_IMETHOD GetAboutModuleFlags(uint32_t* flags) override;
142 NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
143 NS_IMETHOD GetOriginAttributes(JSContext* aCx,
144 JS::MutableHandle<JS::Value> aVal) final;
145 NS_IMETHOD GetAsciiSpec(nsACString& aSpec) override;
146 NS_IMETHOD GetSpec(nsACString& aSpec) override;
147 NS_IMETHOD GetExposablePrePath(nsACString& aResult) override;
148 NS_IMETHOD GetExposableSpec(nsACString& aSpec) override;
149 NS_IMETHOD GetHostPort(nsACString& aRes) override;
150 NS_IMETHOD GetHost(nsACString& aRes) override;
151 NS_IMETHOD GetPrePath(nsACString& aResult) override;
152 NS_IMETHOD GetFilePath(nsACString& aResult) override;
153 NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
154 NS_IMETHOD GetIsIpAddress(bool* aIsIpAddress) override;
155 NS_IMETHOD GetIsLocalIpAddress(bool* aIsIpAddress) override;
156 NS_IMETHOD GetIsOnion(bool* aIsOnion) override;
157 NS_IMETHOD GetIsInIsolatedMozBrowserElement(
158 bool* aIsInIsolatedMozBrowserElement) final;
159 NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
160 NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
161 NS_IMETHOD GetSiteOrigin(nsACString& aSiteOrigin) final;
162 NS_IMETHOD GetSiteOriginNoSuffix(nsACString& aSiteOrigin) override;
163 NS_IMETHOD IsThirdPartyURI(nsIURI* uri, bool* aRes) override;
164 NS_IMETHOD IsThirdPartyPrincipal(nsIPrincipal* uri, bool* aRes) override;
165 NS_IMETHOD IsThirdPartyChannel(nsIChannel* aChannel, bool* aRes) override;
166 NS_IMETHOD GetIsOriginPotentiallyTrustworthy(bool* aResult) override;
167 NS_IMETHOD GetIsLoopbackHost(bool* aResult) override;
168 NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool* aRes) override;
169 NS_IMETHOD GetPrefLightCacheKey(nsIURI* aURI, bool aWithCredentials,
170 const OriginAttributes& aOriginAttributes,
171 nsACString& _retval) override;
172 NS_IMETHOD HasFirstpartyStorageAccess(mozIDOMWindow* aCheckWindow,
173 uint32_t* aRejectedReason,
174 bool* aOutAllowed) override;
175 NS_IMETHOD GetAsciiHost(nsACString& aAsciiHost) override;
176 NS_IMETHOD GetLocalStorageQuotaKey(nsACString& aRes) override;
177 NS_IMETHOD AllowsRelaxStrictFileOriginPolicy(nsIURI* aURI,
178 bool* aRes) override;
179 NS_IMETHOD CreateReferrerInfo(mozilla::dom::ReferrerPolicy aReferrerPolicy,
180 nsIReferrerInfo** _retval) override;
181 NS_IMETHOD GetIsScriptAllowedByPolicy(
182 bool* aIsScriptAllowedByPolicy) override;
183 NS_IMETHOD GetStorageOriginKey(nsACString& aOriginKey) override;
185 NS_IMETHOD GetNextSubDomainPrincipal(
186 nsIPrincipal** aNextSubDomainPrincipal) override;
188 NS_IMETHOD GetPrecursorPrincipal(nsIPrincipal** aPrecursor) override;
190 nsresult ToJSON(nsACString& aJSON);
191 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
192 // Method populates a passed Json::Value with serializable fields
193 // which represent all of the fields to deserialize the principal
194 virtual nsresult PopulateJSONObject(Json::Value& aObject);
196 virtual bool AddonHasPermission(const nsAtom* aPerm);
198 virtual bool IsContentPrincipal() const { return false; };
200 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
201 return static_cast<BasePrincipal*>(aPrin);
204 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
205 return *static_cast<BasePrincipal*>(&aPrin);
208 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
209 return static_cast<const BasePrincipal*>(aPrin);
212 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
213 return *static_cast<const BasePrincipal*>(&aPrin);
216 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
217 const nsACString& aOrigin);
219 // This method may not create a content principal in case it's not possible to
220 // generate a correct origin from the passed URI. If this happens, a
221 // NullPrincipal is returned.
223 // If `aInitialDomain` is specified, and a ContentPrincipal is set, it will
224 // initially have its domain set to the given value, without re-computing js
225 // wrappers. Unlike `SetDomain()` this is safe to do off-main-thread.
227 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
228 nsIURI* aURI, const OriginAttributes& aAttrs,
229 nsIURI* aInitialDomain = nullptr);
231 const OriginAttributes& OriginAttributesRef() final {
232 return mOriginAttributes;
234 extensions::WebExtensionPolicy* AddonPolicy();
235 RefPtr<extensions::WebExtensionPolicyCore> AddonPolicyCore();
236 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
237 uint32_t PrivateBrowsingId() const {
238 return mOriginAttributes.mPrivateBrowsingId;
240 bool IsInIsolatedMozBrowserElement() const {
241 return mOriginAttributes.mInIsolatedMozBrowser;
244 PrincipalKind Kind() const { return mKind; }
246 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
247 const OriginAttributes& aOriginAttributes);
249 // If this is an add-on content script principal, returns its AddonPolicy.
250 // Otherwise returns null.
251 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
252 RefPtr<extensions::WebExtensionPolicyCore> ContentScriptAddonPolicyCore();
254 // Helper to check whether this principal is associated with an addon that
255 // allows unprivileged code to load aURI. aExplicit == true will prevent
256 // use of all_urls permission, requiring the domain in its permissions.
257 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
259 // Call these to avoid the cost of virtual dispatch.
260 inline bool FastEquals(nsIPrincipal* aOther);
261 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
262 inline bool FastSubsumes(nsIPrincipal* aOther);
263 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
264 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
265 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
267 // Fast way to check whether we have a system principal.
268 inline bool IsSystemPrincipal() const;
270 // Returns the principal to inherit when a caller with this principal loads
271 // the given URI.
273 // For most principal types, this returns the principal itself. For expanded
274 // principals, it returns the first sub-principal which subsumes the given URI
275 // (or, if no URI is given, the last allowlist principal).
276 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
278 /* Returns true if this principal's CSP should override a document's CSP for
279 * loads that it triggers. Currently true for expanded principals which
280 * subsume the document principal, and add-on content principals regardless
281 * of whether they subsume the document principal.
283 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal);
285 uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }
286 uint32_t GetOriginSuffixHash() const { return mOriginSuffix->hash(); }
288 virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;
290 protected:
291 BasePrincipal(PrincipalKind aKind, const nsACString& aOriginNoSuffix,
292 const OriginAttributes& aOriginAttributes);
293 BasePrincipal(BasePrincipal* aOther,
294 const OriginAttributes& aOriginAttributes);
296 virtual ~BasePrincipal();
298 // Note that this does not check OriginAttributes. Callers that depend on
299 // those must call Subsumes instead.
300 virtual bool SubsumesInternal(nsIPrincipal* aOther,
301 DocumentDomainConsideration aConsider) = 0;
303 // Internal, side-effect-free check to determine whether the concrete
304 // principal would allow the load ignoring any common behavior implemented in
305 // BasePrincipal::CheckMayLoad.
307 // Safe to call from any thread, unlike 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; }
316 bool GetHasExplicitDomain() { return mHasExplicitDomain; }
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, nsIURI* aInitialDomain);
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 std::atomic<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 */