Bug 1771374 - Fix build and lint warnings. r=gfx-reviewers,aosmond
[gecko.git] / caps / BasePrincipal.h
blob1169414bc6521a7d32b0d296f94edaffb28ac67a
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* 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 bool IsLoopbackHost();
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.
310 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
311 friend class ::ExpandedPrincipal;
313 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
314 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
315 bool aReport, uint64_t aInnerWindowID);
317 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
319 // KeyValT holds a principal subtype-specific key value and the associated
320 // parsed value after JSON parsing.
321 template <typename SerializedKey>
322 struct KeyValT {
323 static_assert(sizeof(SerializedKey) == 1,
324 "SerializedKey should be a uint8_t");
325 SerializedKey key;
326 bool valueWasSerialized;
327 nsCString value;
330 // Common base class for all Deserializer implementations in concrete
331 // subclasses. Subclasses will initialize `mPrincipal` in `Read`, and then
332 // calls to `QueryInterface` will QI on the target object.
333 class Deserializer : public nsISerializable {
334 public:
335 NS_DECL_ISUPPORTS
336 NS_IMETHOD Write(nsIObjectOutputStream* aStream) override;
338 protected:
339 virtual ~Deserializer() = default;
340 RefPtr<BasePrincipal> mPrincipal;
343 private:
344 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
345 nsIURI* aURI, const OriginAttributes& aAttrs,
346 const nsACString& aOriginNoSuffix);
348 bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther,
349 DocumentDomainConsideration aConsideration);
351 const RefPtr<nsAtom> mOriginNoSuffix;
352 const RefPtr<nsAtom> mOriginSuffix;
354 const OriginAttributes mOriginAttributes;
355 const PrincipalKind mKind;
356 bool mHasExplicitDomain;
359 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
360 MOZ_ASSERT(aOther);
362 auto other = Cast(aOther);
363 if (Kind() != other->Kind()) {
364 // Principals of different kinds can't be equal.
365 return false;
368 // Two principals are considered to be equal if their origins are the same.
369 // If the two principals are content principals, their origin attributes
370 // (aka the origin suffix) must also match.
371 if (Kind() == eSystemPrincipal) {
372 return this == other;
375 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
376 return mOriginNoSuffix == other->mOriginNoSuffix &&
377 mOriginSuffix == other->mOriginSuffix;
380 MOZ_ASSERT(Kind() == eExpandedPrincipal);
381 return mOriginNoSuffix == other->mOriginNoSuffix;
384 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
385 MOZ_ASSERT(aOther);
387 // If neither of the principals have document.domain set, we use the fast path
388 // in Equals(). Otherwise, we fall back to the slow path below.
389 auto other = Cast(aOther);
390 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
391 return FastEquals(aOther);
394 return Subsumes(aOther, ConsiderDocumentDomain) &&
395 other->Subsumes(this, ConsiderDocumentDomain);
398 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
399 MOZ_ASSERT(aOther);
401 // If two principals are equal, then they both subsume each other.
402 if (FastEquals(aOther)) {
403 return true;
406 // Otherwise, fall back to the slow path.
407 return Subsumes(aOther, DontConsiderDocumentDomain);
410 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
411 MOZ_ASSERT(aOther);
413 // If neither of the principals have document.domain set, we hand off to
414 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
415 // fall back to the slow path below.
416 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
417 return FastSubsumes(aOther);
420 return Subsumes(aOther, ConsiderDocumentDomain);
423 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
424 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
427 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
428 nsIPrincipal* aOther) {
429 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
432 inline bool BasePrincipal::IsSystemPrincipal() const {
433 return Kind() == eSystemPrincipal;
436 } // namespace mozilla
438 inline bool nsIPrincipal::IsSystemPrincipal() const {
439 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
442 #endif /* mozilla_BasePrincipal_h */