Bug 1834635 [wpt PR 40177] - Update wpt metadata, a=testonly
[gecko.git] / caps / BasePrincipal.h
blob433e5fa219a09199d0fd6ab21e6361c5ab07a09d
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 GetWebExposedOriginSerialization(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 IsContentAccessibleAboutURI(bool* aResult) override;
141 NS_IMETHOD IsL10nAllowed(nsIURI* aURI, bool* aResult) override;
142 NS_IMETHOD GetAboutModuleFlags(uint32_t* flags) override;
143 NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
144 NS_IMETHOD GetOriginAttributes(JSContext* aCx,
145 JS::MutableHandle<JS::Value> aVal) final;
146 NS_IMETHOD GetAsciiSpec(nsACString& aSpec) override;
147 NS_IMETHOD GetSpec(nsACString& aSpec) override;
148 NS_IMETHOD GetExposablePrePath(nsACString& aResult) override;
149 NS_IMETHOD GetExposableSpec(nsACString& aSpec) override;
150 NS_IMETHOD GetHostPort(nsACString& aRes) override;
151 NS_IMETHOD GetHost(nsACString& aRes) override;
152 NS_IMETHOD GetPrePath(nsACString& aResult) override;
153 NS_IMETHOD GetFilePath(nsACString& aResult) override;
154 NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
155 NS_IMETHOD GetIsIpAddress(bool* aIsIpAddress) override;
156 NS_IMETHOD GetIsLocalIpAddress(bool* aIsIpAddress) override;
157 NS_IMETHOD GetIsOnion(bool* aIsOnion) override;
158 NS_IMETHOD GetIsInIsolatedMozBrowserElement(
159 bool* aIsInIsolatedMozBrowserElement) final;
160 NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
161 NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
162 NS_IMETHOD GetSiteOrigin(nsACString& aSiteOrigin) final;
163 NS_IMETHOD GetSiteOriginNoSuffix(nsACString& aSiteOrigin) override;
164 NS_IMETHOD IsThirdPartyURI(nsIURI* uri, bool* aRes) override;
165 NS_IMETHOD IsThirdPartyPrincipal(nsIPrincipal* uri, bool* aRes) override;
166 NS_IMETHOD IsThirdPartyChannel(nsIChannel* aChannel, bool* aRes) override;
167 NS_IMETHOD GetIsOriginPotentiallyTrustworthy(bool* aResult) override;
168 NS_IMETHOD GetIsLoopbackHost(bool* aResult) override;
169 NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool* aRes) override;
170 NS_IMETHOD GetPrefLightCacheKey(nsIURI* aURI, bool aWithCredentials,
171 const OriginAttributes& aOriginAttributes,
172 nsACString& _retval) override;
173 NS_IMETHOD HasFirstpartyStorageAccess(mozIDOMWindow* aCheckWindow,
174 uint32_t* aRejectedReason,
175 bool* aOutAllowed) override;
176 NS_IMETHOD GetAsciiHost(nsACString& aAsciiHost) override;
177 NS_IMETHOD GetLocalStorageQuotaKey(nsACString& aRes) override;
178 NS_IMETHOD AllowsRelaxStrictFileOriginPolicy(nsIURI* aURI,
179 bool* aRes) override;
180 NS_IMETHOD CreateReferrerInfo(mozilla::dom::ReferrerPolicy aReferrerPolicy,
181 nsIReferrerInfo** _retval) override;
182 NS_IMETHOD GetIsScriptAllowedByPolicy(
183 bool* aIsScriptAllowedByPolicy) override;
184 NS_IMETHOD GetStorageOriginKey(nsACString& aOriginKey) override;
186 NS_IMETHOD GetNextSubDomainPrincipal(
187 nsIPrincipal** aNextSubDomainPrincipal) override;
189 NS_IMETHOD GetPrecursorPrincipal(nsIPrincipal** aPrecursor) override;
191 nsresult ToJSON(nsACString& aJSON);
192 nsresult ToJSON(Json::Value& aObject);
194 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
195 static already_AddRefed<BasePrincipal> FromJSON(const Json::Value& aJSON);
196 // Method populates a passed Json::Value with serializable fields
197 // which represent all of the fields to deserialize the principal
198 virtual nsresult PopulateJSONObject(Json::Value& aObject);
200 virtual bool AddonHasPermission(const nsAtom* aPerm);
202 virtual bool IsContentPrincipal() const { return false; };
204 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
205 return static_cast<BasePrincipal*>(aPrin);
208 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
209 return *static_cast<BasePrincipal*>(&aPrin);
212 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
213 return static_cast<const BasePrincipal*>(aPrin);
216 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
217 return *static_cast<const BasePrincipal*>(&aPrin);
220 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
221 const nsACString& aOrigin);
223 // This method may not create a content principal in case it's not possible to
224 // generate a correct origin from the passed URI. If this happens, a
225 // NullPrincipal is returned.
227 // If `aInitialDomain` is specified, and a ContentPrincipal is set, it will
228 // initially have its domain set to the given value, without re-computing js
229 // wrappers. Unlike `SetDomain()` this is safe to do off-main-thread.
231 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
232 nsIURI* aURI, const OriginAttributes& aAttrs,
233 nsIURI* aInitialDomain = nullptr);
235 const OriginAttributes& OriginAttributesRef() final {
236 return mOriginAttributes;
238 extensions::WebExtensionPolicy* AddonPolicy();
239 RefPtr<extensions::WebExtensionPolicyCore> AddonPolicyCore();
240 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
241 uint32_t PrivateBrowsingId() const {
242 return mOriginAttributes.mPrivateBrowsingId;
244 bool IsInIsolatedMozBrowserElement() const {
245 return mOriginAttributes.mInIsolatedMozBrowser;
248 PrincipalKind Kind() const { return mKind; }
250 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
251 const OriginAttributes& aOriginAttributes);
253 // If this is an add-on content script principal, returns its AddonPolicy.
254 // Otherwise returns null.
255 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
256 RefPtr<extensions::WebExtensionPolicyCore> ContentScriptAddonPolicyCore();
258 // Helper to check whether this principal is associated with an addon that
259 // allows unprivileged code to load aURI. aExplicit == true will prevent
260 // use of all_urls permission, requiring the domain in its permissions.
261 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
263 // Call these to avoid the cost of virtual dispatch.
264 inline bool FastEquals(nsIPrincipal* aOther);
265 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
266 inline bool FastSubsumes(nsIPrincipal* aOther);
267 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
268 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
269 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
271 // Fast way to check whether we have a system principal.
272 inline bool IsSystemPrincipal() const;
274 // Returns the principal to inherit when a caller with this principal loads
275 // the given URI.
277 // For most principal types, this returns the principal itself. For expanded
278 // principals, it returns the first sub-principal which subsumes the given URI
279 // (or, if no URI is given, the last allowlist principal).
280 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
282 /* Returns true if this principal's CSP should override a document's CSP for
283 * loads that it triggers. Currently true for expanded principals which
284 * subsume the document principal, and add-on content principals regardless
285 * of whether they subsume the document principal.
287 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal);
289 uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }
290 uint32_t GetOriginSuffixHash() const { return mOriginSuffix->hash(); }
292 virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;
294 protected:
295 BasePrincipal(PrincipalKind aKind, const nsACString& aOriginNoSuffix,
296 const OriginAttributes& aOriginAttributes);
297 BasePrincipal(BasePrincipal* aOther,
298 const OriginAttributes& aOriginAttributes);
300 virtual ~BasePrincipal();
302 // Note that this does not check OriginAttributes. Callers that depend on
303 // those must call Subsumes instead.
304 virtual bool SubsumesInternal(nsIPrincipal* aOther,
305 DocumentDomainConsideration aConsider) = 0;
307 // Internal, side-effect-free check to determine whether the concrete
308 // principal would allow the load ignoring any common behavior implemented in
309 // BasePrincipal::CheckMayLoad.
311 // Safe to call from any thread, unlike CheckMayLoad.
312 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
313 friend class ::ExpandedPrincipal;
315 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
316 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
317 bool aReport, uint64_t aInnerWindowID);
319 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
320 bool GetHasExplicitDomain() { return mHasExplicitDomain; }
322 // KeyValT holds a principal subtype-specific key value and the associated
323 // parsed value after JSON parsing.
324 template <typename SerializedKey>
325 struct KeyValT {
326 static_assert(sizeof(SerializedKey) == 1,
327 "SerializedKey should be a uint8_t");
328 SerializedKey key;
329 bool valueWasSerialized;
330 nsCString value;
333 // Common base class for all Deserializer implementations in concrete
334 // subclasses. Subclasses will initialize `mPrincipal` in `Read`, and then
335 // calls to `QueryInterface` will QI on the target object.
336 class Deserializer : public nsISerializable {
337 public:
338 NS_DECL_ISUPPORTS
339 NS_IMETHOD Write(nsIObjectOutputStream* aStream) override;
341 protected:
342 virtual ~Deserializer() = default;
343 RefPtr<BasePrincipal> mPrincipal;
346 private:
347 static const char* JSONEnumKeyStrings[4];
349 static void SetJSONValue(Json::Value& aObject, const char* aKey,
350 const nsCString& aValue);
352 protected:
353 template <size_t EnumValue>
354 static inline constexpr const char* JSONEnumKeyString() {
355 static_assert(EnumValue < ArrayLength(JSONEnumKeyStrings));
356 return JSONEnumKeyStrings[EnumValue];
358 template <size_t EnumValue>
359 static void SetJSONValue(Json::Value& aObject, const nsCString& aValue) {
360 SetJSONValue(aObject, JSONEnumKeyString<EnumValue>(), aValue);
363 private:
364 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
365 nsIURI* aURI, const OriginAttributes& aAttrs,
366 const nsACString& aOriginNoSuffix, nsIURI* aInitialDomain);
368 bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther,
369 DocumentDomainConsideration aConsideration);
371 const RefPtr<nsAtom> mOriginNoSuffix;
372 const RefPtr<nsAtom> mOriginSuffix;
374 const OriginAttributes mOriginAttributes;
375 const PrincipalKind mKind;
376 std::atomic<bool> mHasExplicitDomain;
379 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
380 MOZ_ASSERT(aOther);
382 auto other = Cast(aOther);
383 if (Kind() != other->Kind()) {
384 // Principals of different kinds can't be equal.
385 return false;
388 // Two principals are considered to be equal if their origins are the same.
389 // If the two principals are content principals, their origin attributes
390 // (aka the origin suffix) must also match.
391 if (Kind() == eSystemPrincipal) {
392 return this == other;
395 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
396 return mOriginNoSuffix == other->mOriginNoSuffix &&
397 mOriginSuffix == other->mOriginSuffix;
400 MOZ_ASSERT(Kind() == eExpandedPrincipal);
401 return mOriginNoSuffix == other->mOriginNoSuffix;
404 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
405 MOZ_ASSERT(aOther);
407 // If neither of the principals have document.domain set, we use the fast path
408 // in Equals(). Otherwise, we fall back to the slow path below.
409 auto other = Cast(aOther);
410 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
411 return FastEquals(aOther);
414 // Principals of different kinds can't be equal.
415 if (Kind() != other->Kind()) {
416 return false;
419 // Only ContentPrincipals should have mHasExplicitDomain set to true, so test
420 // that we haven't ended up here instead of FastEquals by mistake.
421 MOZ_ASSERT(IsContentPrincipal(),
422 "Only content principals can set mHasExplicitDomain");
424 return Subsumes(aOther, ConsiderDocumentDomain) &&
425 other->Subsumes(this, ConsiderDocumentDomain);
428 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
429 MOZ_ASSERT(aOther);
431 // If two principals are equal, then they both subsume each other.
432 if (FastEquals(aOther)) {
433 return true;
436 // Otherwise, fall back to the slow path.
437 return Subsumes(aOther, DontConsiderDocumentDomain);
440 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
441 MOZ_ASSERT(aOther);
443 // If neither of the principals have document.domain set, we hand off to
444 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
445 // fall back to the slow path below.
446 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
447 return FastSubsumes(aOther);
450 return Subsumes(aOther, ConsiderDocumentDomain);
453 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
454 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
457 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
458 nsIPrincipal* aOther) {
459 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
462 inline bool BasePrincipal::IsSystemPrincipal() const {
463 return Kind() == eSystemPrincipal;
466 } // namespace mozilla
468 inline bool nsIPrincipal::IsSystemPrincipal() const {
469 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
472 #endif /* mozilla_BasePrincipal_h */