Bug 1826620 [wpt PR 39397] - Add WPTs for AuctionConfig, a=testonly
[gecko.git] / caps / BasePrincipal.h
blob7da0ef5b55c7be3d0888c030bb0020c7b06d8146
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 nsresult ToJSON(Json::Value& aObject);
193 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
194 static already_AddRefed<BasePrincipal> FromJSON(const Json::Value& aJSON);
195 // Method populates a passed Json::Value with serializable fields
196 // which represent all of the fields to deserialize the principal
197 virtual nsresult PopulateJSONObject(Json::Value& aObject);
199 virtual bool AddonHasPermission(const nsAtom* aPerm);
201 virtual bool IsContentPrincipal() const { return false; };
203 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
204 return static_cast<BasePrincipal*>(aPrin);
207 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
208 return *static_cast<BasePrincipal*>(&aPrin);
211 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
212 return static_cast<const BasePrincipal*>(aPrin);
215 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
216 return *static_cast<const BasePrincipal*>(&aPrin);
219 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
220 const nsACString& aOrigin);
222 // This method may not create a content principal in case it's not possible to
223 // generate a correct origin from the passed URI. If this happens, a
224 // NullPrincipal is returned.
226 // If `aInitialDomain` is specified, and a ContentPrincipal is set, it will
227 // initially have its domain set to the given value, without re-computing js
228 // wrappers. Unlike `SetDomain()` this is safe to do off-main-thread.
230 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
231 nsIURI* aURI, const OriginAttributes& aAttrs,
232 nsIURI* aInitialDomain = nullptr);
234 const OriginAttributes& OriginAttributesRef() final {
235 return mOriginAttributes;
237 extensions::WebExtensionPolicy* AddonPolicy();
238 RefPtr<extensions::WebExtensionPolicyCore> AddonPolicyCore();
239 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
240 uint32_t PrivateBrowsingId() const {
241 return mOriginAttributes.mPrivateBrowsingId;
243 bool IsInIsolatedMozBrowserElement() const {
244 return mOriginAttributes.mInIsolatedMozBrowser;
247 PrincipalKind Kind() const { return mKind; }
249 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
250 const OriginAttributes& aOriginAttributes);
252 // If this is an add-on content script principal, returns its AddonPolicy.
253 // Otherwise returns null.
254 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
255 RefPtr<extensions::WebExtensionPolicyCore> ContentScriptAddonPolicyCore();
257 // Helper to check whether this principal is associated with an addon that
258 // allows unprivileged code to load aURI. aExplicit == true will prevent
259 // use of all_urls permission, requiring the domain in its permissions.
260 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
262 // Call these to avoid the cost of virtual dispatch.
263 inline bool FastEquals(nsIPrincipal* aOther);
264 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
265 inline bool FastSubsumes(nsIPrincipal* aOther);
266 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
267 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
268 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
270 // Fast way to check whether we have a system principal.
271 inline bool IsSystemPrincipal() const;
273 // Returns the principal to inherit when a caller with this principal loads
274 // the given URI.
276 // For most principal types, this returns the principal itself. For expanded
277 // principals, it returns the first sub-principal which subsumes the given URI
278 // (or, if no URI is given, the last allowlist principal).
279 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
281 /* Returns true if this principal's CSP should override a document's CSP for
282 * loads that it triggers. Currently true for expanded principals which
283 * subsume the document principal, and add-on content principals regardless
284 * of whether they subsume the document principal.
286 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal);
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.
310 // Safe to call from any thread, unlike CheckMayLoad.
311 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
312 friend class ::ExpandedPrincipal;
314 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
315 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
316 bool aReport, uint64_t aInnerWindowID);
318 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
319 bool GetHasExplicitDomain() { return mHasExplicitDomain; }
321 // KeyValT holds a principal subtype-specific key value and the associated
322 // parsed value after JSON parsing.
323 template <typename SerializedKey>
324 struct KeyValT {
325 static_assert(sizeof(SerializedKey) == 1,
326 "SerializedKey should be a uint8_t");
327 SerializedKey key;
328 bool valueWasSerialized;
329 nsCString value;
332 // Common base class for all Deserializer implementations in concrete
333 // subclasses. Subclasses will initialize `mPrincipal` in `Read`, and then
334 // calls to `QueryInterface` will QI on the target object.
335 class Deserializer : public nsISerializable {
336 public:
337 NS_DECL_ISUPPORTS
338 NS_IMETHOD Write(nsIObjectOutputStream* aStream) override;
340 protected:
341 virtual ~Deserializer() = default;
342 RefPtr<BasePrincipal> mPrincipal;
345 private:
346 static const char* JSONEnumKeyStrings[4];
348 static void SetJSONValue(Json::Value& aObject, const char* aKey,
349 const nsCString& aValue);
351 protected:
352 template <size_t EnumValue>
353 static inline constexpr const char* JSONEnumKeyString() {
354 static_assert(EnumValue < ArrayLength(JSONEnumKeyStrings));
355 return JSONEnumKeyStrings[EnumValue];
357 template <size_t EnumValue>
358 static void SetJSONValue(Json::Value& aObject, const nsCString& aValue) {
359 SetJSONValue(aObject, JSONEnumKeyString<EnumValue>(), aValue);
362 private:
363 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
364 nsIURI* aURI, const OriginAttributes& aAttrs,
365 const nsACString& aOriginNoSuffix, nsIURI* aInitialDomain);
367 bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther,
368 DocumentDomainConsideration aConsideration);
370 const RefPtr<nsAtom> mOriginNoSuffix;
371 const RefPtr<nsAtom> mOriginSuffix;
373 const OriginAttributes mOriginAttributes;
374 const PrincipalKind mKind;
375 std::atomic<bool> mHasExplicitDomain;
378 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
379 MOZ_ASSERT(aOther);
381 auto other = Cast(aOther);
382 if (Kind() != other->Kind()) {
383 // Principals of different kinds can't be equal.
384 return false;
387 // Two principals are considered to be equal if their origins are the same.
388 // If the two principals are content principals, their origin attributes
389 // (aka the origin suffix) must also match.
390 if (Kind() == eSystemPrincipal) {
391 return this == other;
394 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
395 return mOriginNoSuffix == other->mOriginNoSuffix &&
396 mOriginSuffix == other->mOriginSuffix;
399 MOZ_ASSERT(Kind() == eExpandedPrincipal);
400 return mOriginNoSuffix == other->mOriginNoSuffix;
403 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
404 MOZ_ASSERT(aOther);
406 // If neither of the principals have document.domain set, we use the fast path
407 // in Equals(). Otherwise, we fall back to the slow path below.
408 auto other = Cast(aOther);
409 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
410 return FastEquals(aOther);
413 // Principals of different kinds can't be equal.
414 if (Kind() != other->Kind()) {
415 return false;
418 // Only ContentPrincipals should have mHasExplicitDomain set to true, so test
419 // that we haven't ended up here instead of FastEquals by mistake.
420 MOZ_ASSERT(IsContentPrincipal(),
421 "Only content principals can set mHasExplicitDomain");
423 return Subsumes(aOther, ConsiderDocumentDomain) &&
424 other->Subsumes(this, ConsiderDocumentDomain);
427 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
428 MOZ_ASSERT(aOther);
430 // If two principals are equal, then they both subsume each other.
431 if (FastEquals(aOther)) {
432 return true;
435 // Otherwise, fall back to the slow path.
436 return Subsumes(aOther, DontConsiderDocumentDomain);
439 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
440 MOZ_ASSERT(aOther);
442 // If neither of the principals have document.domain set, we hand off to
443 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
444 // fall back to the slow path below.
445 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
446 return FastSubsumes(aOther);
449 return Subsumes(aOther, ConsiderDocumentDomain);
452 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
453 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
456 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
457 nsIPrincipal* aOther) {
458 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
461 inline bool BasePrincipal::IsSystemPrincipal() const {
462 return Kind() == eSystemPrincipal;
465 } // namespace mozilla
467 inline bool nsIPrincipal::IsSystemPrincipal() const {
468 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
471 #endif /* mozilla_BasePrincipal_h */