Bug 1613876 [wpt PR 21654] - Reland "Move SMIL events tests to WPT", a=testonly
[gecko.git] / caps / BasePrincipal.h
blob0a5320c06f35a9be61d63881fb94a85614b1fa6e
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 "nsJSPrincipals.h"
12 #include "mozilla/Attributes.h"
13 #include "mozilla/OriginAttributes.h"
15 class nsAtom;
16 class nsIContentSecurityPolicy;
17 class nsIObjectOutputStream;
18 class nsIObjectInputStream;
19 class nsIURI;
21 class ExpandedPrincipal;
23 namespace Json {
24 class Value;
26 namespace mozilla {
27 namespace dom {
28 class Document;
30 namespace extensions {
31 class WebExtensionPolicy;
34 class BasePrincipal;
36 // Content principals (and content principals embedded within expanded
37 // principals) stored in SiteIdentifier are guaranteed to contain only the
38 // eTLD+1 part of the original domain. This is used to determine whether two
39 // origins are same-site: if it's possible for two origins to access each other
40 // (maybe after mutating document.domain), then they must have the same site
41 // identifier.
42 class SiteIdentifier {
43 public:
44 void Init(BasePrincipal* aPrincipal) {
45 MOZ_ASSERT(aPrincipal);
46 mPrincipal = aPrincipal;
49 bool IsInitialized() const { return !!mPrincipal; }
51 bool Equals(const SiteIdentifier& aOther) const;
53 private:
54 friend class ::ExpandedPrincipal;
56 BasePrincipal* GetPrincipal() const {
57 MOZ_ASSERT(IsInitialized());
58 return mPrincipal;
61 RefPtr<BasePrincipal> mPrincipal;
65 * Base class from which all nsIPrincipal implementations inherit. Use this for
66 * default implementations and other commonalities between principal
67 * implementations.
69 * We should merge nsJSPrincipals into this class at some point.
71 class BasePrincipal : public nsJSPrincipals {
72 public:
73 // Warning: this enum impacts Principal serialization into JSON format.
74 // Only update if you know exactly what you are doing
75 enum PrincipalKind {
76 eNullPrincipal = 0,
77 eContentPrincipal,
78 eExpandedPrincipal,
79 eSystemPrincipal,
80 eKindMax = eSystemPrincipal
83 explicit BasePrincipal(PrincipalKind aKind);
85 template <typename T>
86 bool Is() const {
87 return mKind == T::Kind();
90 template <typename T>
91 T* As() {
92 MOZ_ASSERT(Is<T>());
93 return static_cast<T*>(this);
96 enum DocumentDomainConsideration {
97 DontConsiderDocumentDomain,
98 ConsiderDocumentDomain
100 bool Subsumes(nsIPrincipal* aOther,
101 DocumentDomainConsideration aConsideration);
103 NS_IMETHOD GetOrigin(nsACString& aOrigin) final;
104 NS_IMETHOD GetAsciiOrigin(nsACString& aOrigin) override;
105 NS_IMETHOD GetOriginNoSuffix(nsACString& aOrigin) final;
106 NS_IMETHOD Equals(nsIPrincipal* other, bool* _retval) final;
107 NS_IMETHOD EqualsConsideringDomain(nsIPrincipal* other, bool* _retval) final;
108 NS_IMETHOD EqualsURI(nsIURI* aOtherURI, bool* _retval) override;
109 NS_IMETHOD Subsumes(nsIPrincipal* other, bool* _retval) final;
110 NS_IMETHOD SubsumesConsideringDomain(nsIPrincipal* other,
111 bool* _retval) final;
112 NS_IMETHOD SubsumesConsideringDomainIgnoringFPD(nsIPrincipal* other,
113 bool* _retval) final;
114 NS_IMETHOD CheckMayLoad(nsIURI* uri, bool allowIfInheritsPrincipal) final;
115 NS_IMETHOD CheckMayLoadWithReporting(nsIURI* uri,
116 bool allowIfInheritsPrincipal,
117 uint64_t innerWindowID) final;
118 NS_IMETHOD GetAddonPolicy(nsISupports** aResult) final;
119 NS_IMETHOD GetIsNullPrincipal(bool* aResult) override;
120 NS_IMETHOD GetIsContentPrincipal(bool* aResult) override;
121 NS_IMETHOD GetIsExpandedPrincipal(bool* aResult) override;
122 NS_IMETHOD GetIsSystemPrincipal(bool* aResult) override;
123 NS_IMETHOD SchemeIs(const char* aScheme, bool* aResult) override;
124 NS_IMETHOD IsURIInPrefList(const char* aPref, bool* aResult) override;
125 NS_IMETHOD GetAboutModuleFlags(uint32_t* flags) override;
126 NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
127 NS_IMETHOD GetOriginAttributes(JSContext* aCx,
128 JS::MutableHandle<JS::Value> aVal) final;
129 NS_IMETHOD GetAsciiSpec(nsACString& aSpec) override;
130 NS_IMETHOD GetExposablePrePath(nsACString& aResult) override;
131 NS_IMETHOD GetHostPort(nsACString& aRes) override;
132 NS_IMETHOD GetPrepath(nsACString& aResult) override;
133 NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
134 NS_IMETHOD GetIsOnion(bool* aIsOnion) override;
135 NS_IMETHOD GetIsInIsolatedMozBrowserElement(
136 bool* aIsInIsolatedMozBrowserElement) final;
137 NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
138 NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
139 NS_IMETHOD GetSiteOrigin(nsACString& aOrigin) override;
140 NS_IMETHOD IsThirdPartyURI(nsIURI* uri, bool* aRes) override;
141 NS_IMETHOD IsThirdPartyPrincipal(nsIPrincipal* uri, bool* aRes) override;
142 NS_IMETHOD GetIsOriginPotentiallyTrustworthy(bool* aResult) override;
143 NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool aIsPrivateWin,
144 bool* aRes) override;
146 nsresult ToJSON(nsACString& aJSON);
147 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
148 // Method populates a passed Json::Value with serializable fields
149 // which represent all of the fields to deserialize the principal
150 virtual nsresult PopulateJSONObject(Json::Value& aObject);
152 virtual bool AddonHasPermission(const nsAtom* aPerm);
154 virtual bool IsContentPrincipal() const { return false; };
156 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
157 return static_cast<BasePrincipal*>(aPrin);
160 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
161 return *static_cast<BasePrincipal*>(&aPrin);
164 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
165 return static_cast<const BasePrincipal*>(aPrin);
168 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
169 return *static_cast<const BasePrincipal*>(&aPrin);
172 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
173 const nsACString& aOrigin);
175 // These following method may not create a content principal in case it's
176 // not possible to generate a correct origin from the passed URI. If this
177 // happens, a NullPrincipal is returned.
179 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
180 nsIURI* aURI, const OriginAttributes& aAttrs);
182 const OriginAttributes& OriginAttributesRef() final {
183 return mOriginAttributes;
185 extensions::WebExtensionPolicy* AddonPolicy();
186 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
187 uint32_t PrivateBrowsingId() const {
188 return mOriginAttributes.mPrivateBrowsingId;
190 bool IsInIsolatedMozBrowserElement() const {
191 return mOriginAttributes.mInIsolatedMozBrowser;
194 PrincipalKind Kind() const { return mKind; }
196 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
197 const OriginAttributes& aOriginAttributes);
199 // If this is an add-on content script principal, returns its AddonPolicy.
200 // Otherwise returns null.
201 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
203 // Helper to check whether this principal is associated with an addon that
204 // allows unprivileged code to load aURI. aExplicit == true will prevent
205 // use of all_urls permission, requiring the domain in its permissions.
206 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
208 // Call these to avoid the cost of virtual dispatch.
209 inline bool FastEquals(nsIPrincipal* aOther);
210 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
211 inline bool FastSubsumes(nsIPrincipal* aOther);
212 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
213 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
214 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
216 // Fast way to check whether we have a system principal.
217 inline bool IsSystemPrincipal() const;
219 // Returns the principal to inherit when a caller with this principal loads
220 // the given URI.
222 // For most principal types, this returns the principal itself. For expanded
223 // principals, it returns the first sub-principal which subsumes the given URI
224 // (or, if no URI is given, the last allowlist principal).
225 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
227 /* Returns true if this principal's CSP should override a document's CSP for
228 * loads that it triggers. Currently true for expanded principals which
229 * subsume the document principal, and add-on content principals regardless
230 * of whether they subsume the document principal.
232 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal) {
233 MOZ_ASSERT(aDocumentPrincipal);
235 // Expanded principals override CSP if and only if they subsume the document
236 // principal.
237 if (mKind == eExpandedPrincipal) {
238 return FastSubsumes(aDocumentPrincipal);
240 // Extension principals always override the CSP non-extension principals.
241 // This is primarily for the sake of their stylesheets, which are usually
242 // loaded from channels and cannot have expanded principals.
243 return (AddonPolicy() &&
244 !BasePrincipal::Cast(aDocumentPrincipal)->AddonPolicy());
247 uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }
248 uint32_t GetOriginSuffixHash() const { return mOriginSuffix->hash(); }
250 virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;
252 protected:
253 virtual ~BasePrincipal();
255 // Note that this does not check OriginAttributes. Callers that depend on
256 // those must call Subsumes instead.
257 virtual bool SubsumesInternal(nsIPrincipal* aOther,
258 DocumentDomainConsideration aConsider) = 0;
260 // Internal, side-effect-free check to determine whether the concrete
261 // principal would allow the load ignoring any common behavior implemented in
262 // BasePrincipal::CheckMayLoad.
263 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
264 friend class ::ExpandedPrincipal;
266 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
267 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
268 bool aReport, uint64_t aInnerWindowID);
270 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
272 // Either of these functions should be called as the last step of the
273 // initialization of the principal objects. It's typically called as the
274 // last step from the Init() method of the child classes.
275 void FinishInit(const nsACString& aOriginNoSuffix,
276 const OriginAttributes& aOriginAttributes);
277 void FinishInit(BasePrincipal* aOther,
278 const OriginAttributes& aOriginAttributes);
280 // KeyValT holds a principal subtype-specific key value and the associated
281 // parsed value after JSON parsing.
282 template <typename SerializedKey>
283 struct KeyValT {
284 static_assert(sizeof(SerializedKey) == 1,
285 "SerializedKey should be a uint8_t");
286 SerializedKey key;
287 bool valueWasSerialized;
288 nsCString value;
291 private:
292 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
293 nsIURI* aURI, const OriginAttributes& aAttrs,
294 const nsACString& aOriginNoSuffix);
296 inline bool FastSubsumesIgnoringFPD(
297 nsIPrincipal* aOther, DocumentDomainConsideration aConsideration);
299 RefPtr<nsAtom> mOriginNoSuffix;
300 RefPtr<nsAtom> mOriginSuffix;
302 OriginAttributes mOriginAttributes;
303 PrincipalKind mKind;
304 bool mHasExplicitDomain;
305 bool mInitialized;
308 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
309 MOZ_ASSERT(aOther);
311 auto other = Cast(aOther);
312 if (Kind() != other->Kind()) {
313 // Principals of different kinds can't be equal.
314 return false;
317 // Two principals are considered to be equal if their origins are the same.
318 // If the two principals are content principals, their origin attributes
319 // (aka the origin suffix) must also match.
320 if (Kind() == eSystemPrincipal) {
321 return this == other;
324 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
325 return mOriginNoSuffix == other->mOriginNoSuffix &&
326 mOriginSuffix == other->mOriginSuffix;
329 MOZ_ASSERT(Kind() == eExpandedPrincipal);
330 return mOriginNoSuffix == other->mOriginNoSuffix;
333 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
334 MOZ_ASSERT(aOther);
336 // If neither of the principals have document.domain set, we use the fast path
337 // in Equals(). Otherwise, we fall back to the slow path below.
338 auto other = Cast(aOther);
339 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
340 return FastEquals(aOther);
343 return Subsumes(aOther, ConsiderDocumentDomain) &&
344 other->Subsumes(this, ConsiderDocumentDomain);
347 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
348 MOZ_ASSERT(aOther);
350 // If two principals are equal, then they both subsume each other.
351 if (FastEquals(aOther)) {
352 return true;
355 // Otherwise, fall back to the slow path.
356 return Subsumes(aOther, DontConsiderDocumentDomain);
359 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
360 MOZ_ASSERT(aOther);
362 // If neither of the principals have document.domain set, we hand off to
363 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
364 // fall back to the slow path below.
365 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
366 return FastSubsumes(aOther);
369 return Subsumes(aOther, ConsiderDocumentDomain);
372 inline bool BasePrincipal::FastSubsumesIgnoringFPD(
373 nsIPrincipal* aOther, DocumentDomainConsideration aConsideration) {
374 MOZ_ASSERT(aOther);
376 if (Kind() == eContentPrincipal &&
377 !dom::ChromeUtils::IsOriginAttributesEqualIgnoringFPD(
378 mOriginAttributes, Cast(aOther)->mOriginAttributes)) {
379 return false;
382 return SubsumesInternal(aOther, aConsideration);
385 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
386 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
389 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
390 nsIPrincipal* aOther) {
391 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
394 inline bool BasePrincipal::IsSystemPrincipal() const {
395 return Kind() == eSystemPrincipal;
398 } // namespace mozilla
400 inline bool nsIPrincipal::IsSystemPrincipal() const {
401 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
404 #endif /* mozilla_BasePrincipal_h */