no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / caps / BasePrincipal.h
blob9304be7dee3f73bd7d990fd50753ac22b0dff3ce
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;
31 namespace mozilla {
33 class JSONWriter;
35 namespace dom {
36 enum class ReferrerPolicy : uint8_t;
39 namespace extensions {
40 class WebExtensionPolicy;
41 class WebExtensionPolicyCore;
42 } // namespace extensions
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 static constexpr char NullPrincipalKey = '0';
94 static_assert(eNullPrincipal == 0);
95 static constexpr char ContentPrincipalKey = '1';
96 static_assert(eContentPrincipal == 1);
97 static constexpr char ExpandedPrincipalKey = '2';
98 static_assert(eExpandedPrincipal == 2);
99 static constexpr char SystemPrincipalKey = '3';
100 static_assert(eSystemPrincipal == 3);
102 template <typename T>
103 bool Is() const {
104 return mKind == T::Kind();
107 template <typename T>
108 T* As() {
109 MOZ_ASSERT(Is<T>());
110 return static_cast<T*>(this);
113 enum DocumentDomainConsideration {
114 DontConsiderDocumentDomain,
115 ConsiderDocumentDomain
117 bool Subsumes(nsIPrincipal* aOther,
118 DocumentDomainConsideration aConsideration);
120 NS_IMETHOD GetOrigin(nsACString& aOrigin) final;
121 NS_IMETHOD GetWebExposedOriginSerialization(nsACString& aOrigin) override;
122 NS_IMETHOD GetOriginNoSuffix(nsACString& aOrigin) final;
123 NS_IMETHOD Equals(nsIPrincipal* other, bool* _retval) final;
124 NS_IMETHOD EqualsConsideringDomain(nsIPrincipal* other, bool* _retval) final;
125 NS_IMETHOD EqualsURI(nsIURI* aOtherURI, bool* _retval) override;
126 NS_IMETHOD EqualsForPermission(nsIPrincipal* other, bool aExactHost,
127 bool* _retval) final;
128 NS_IMETHOD Subsumes(nsIPrincipal* other, bool* _retval) final;
129 NS_IMETHOD SubsumesConsideringDomain(nsIPrincipal* other,
130 bool* _retval) final;
131 NS_IMETHOD SubsumesConsideringDomainIgnoringFPD(nsIPrincipal* other,
132 bool* _retval) final;
133 NS_IMETHOD CheckMayLoad(nsIURI* uri, bool allowIfInheritsPrincipal) final;
134 NS_IMETHOD CheckMayLoadWithReporting(nsIURI* uri,
135 bool allowIfInheritsPrincipal,
136 uint64_t innerWindowID) final;
137 NS_IMETHOD GetAddonPolicy(extensions::WebExtensionPolicy** aResult) final;
138 NS_IMETHOD GetContentScriptAddonPolicy(
139 extensions::WebExtensionPolicy** aResult) final;
140 NS_IMETHOD GetIsNullPrincipal(bool* aResult) override;
141 NS_IMETHOD GetIsContentPrincipal(bool* aResult) override;
142 NS_IMETHOD GetIsExpandedPrincipal(bool* aResult) override;
143 NS_IMETHOD GetIsSystemPrincipal(bool* aResult) override;
144 NS_IMETHOD GetScheme(nsACString& aScheme) override;
145 NS_IMETHOD SchemeIs(const char* aScheme, bool* aResult) override;
146 NS_IMETHOD IsURIInPrefList(const char* aPref, bool* aResult) override;
147 NS_IMETHOD IsURIInList(const nsACString& aList, bool* aResult) override;
148 NS_IMETHOD IsContentAccessibleAboutURI(bool* aResult) override;
149 NS_IMETHOD IsL10nAllowed(nsIURI* aURI, bool* aResult) override;
150 NS_IMETHOD GetAboutModuleFlags(uint32_t* flags) override;
151 NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
152 NS_IMETHOD GetOriginAttributes(JSContext* aCx,
153 JS::MutableHandle<JS::Value> aVal) final;
154 NS_IMETHOD GetAsciiSpec(nsACString& aSpec) override;
155 NS_IMETHOD GetSpec(nsACString& aSpec) override;
156 NS_IMETHOD GetExposablePrePath(nsACString& aResult) override;
157 NS_IMETHOD GetExposableSpec(nsACString& aSpec) override;
158 NS_IMETHOD GetHostPort(nsACString& aRes) override;
159 NS_IMETHOD GetHost(nsACString& aRes) override;
160 NS_IMETHOD GetPrePath(nsACString& aResult) override;
161 NS_IMETHOD GetFilePath(nsACString& aResult) override;
162 NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
163 NS_IMETHOD GetIsIpAddress(bool* aIsIpAddress) override;
164 NS_IMETHOD GetIsLocalIpAddress(bool* aIsIpAddress) override;
165 NS_IMETHOD GetIsOnion(bool* aIsOnion) override;
166 NS_IMETHOD GetIsInIsolatedMozBrowserElement(
167 bool* aIsInIsolatedMozBrowserElement) final;
168 NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
169 NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
170 NS_IMETHOD GetSiteOrigin(nsACString& aSiteOrigin) final;
171 NS_IMETHOD GetSiteOriginNoSuffix(nsACString& aSiteOrigin) override;
172 NS_IMETHOD IsThirdPartyURI(nsIURI* uri, bool* aRes) override;
173 NS_IMETHOD IsThirdPartyPrincipal(nsIPrincipal* uri, bool* aRes) override;
174 NS_IMETHOD IsThirdPartyChannel(nsIChannel* aChannel, bool* aRes) override;
175 NS_IMETHOD GetIsOriginPotentiallyTrustworthy(bool* aResult) override;
176 NS_IMETHOD GetIsLoopbackHost(bool* aResult) override;
177 NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool* aRes) override;
178 NS_IMETHOD GetPrefLightCacheKey(nsIURI* aURI, bool aWithCredentials,
179 const OriginAttributes& aOriginAttributes,
180 nsACString& _retval) override;
181 NS_IMETHOD HasFirstpartyStorageAccess(mozIDOMWindow* aCheckWindow,
182 uint32_t* aRejectedReason,
183 bool* aOutAllowed) override;
184 NS_IMETHOD GetAsciiHost(nsACString& aAsciiHost) override;
185 NS_IMETHOD GetLocalStorageQuotaKey(nsACString& aRes) override;
186 NS_IMETHOD AllowsRelaxStrictFileOriginPolicy(nsIURI* aURI,
187 bool* aRes) override;
188 NS_IMETHOD CreateReferrerInfo(mozilla::dom::ReferrerPolicy aReferrerPolicy,
189 nsIReferrerInfo** _retval) override;
190 NS_IMETHOD GetIsScriptAllowedByPolicy(
191 bool* aIsScriptAllowedByPolicy) override;
192 NS_IMETHOD GetStorageOriginKey(nsACString& aOriginKey) override;
194 NS_IMETHOD GetNextSubDomainPrincipal(
195 nsIPrincipal** aNextSubDomainPrincipal) override;
197 NS_IMETHOD GetPrecursorPrincipal(nsIPrincipal** aPrecursor) override;
199 nsresult ToJSON(nsACString& aJSON);
200 nsresult ToJSON(JSONWriter& aWriter);
201 nsresult WriteJSONProperties(JSONWriter& aWriter);
203 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
205 // Method to write serializable fields which represent all of the fields to
206 // deserialize the principal.
207 virtual nsresult WriteJSONInnerProperties(JSONWriter& aWriter);
209 virtual bool AddonHasPermission(const nsAtom* aPerm);
211 virtual bool IsContentPrincipal() const { return false; };
213 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
214 return static_cast<BasePrincipal*>(aPrin);
217 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
218 return *static_cast<BasePrincipal*>(&aPrin);
221 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
222 return static_cast<const BasePrincipal*>(aPrin);
225 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
226 return *static_cast<const BasePrincipal*>(&aPrin);
229 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
230 const nsACString& aOrigin);
232 // This method may not create a content principal in case it's not possible to
233 // generate a correct origin from the passed URI. If this happens, a
234 // NullPrincipal is returned.
236 // If `aInitialDomain` is specified, and a ContentPrincipal is set, it will
237 // initially have its domain set to the given value, without re-computing js
238 // wrappers. Unlike `SetDomain()` this is safe to do off-main-thread.
240 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
241 nsIURI* aURI, const OriginAttributes& aAttrs,
242 nsIURI* aInitialDomain = nullptr);
244 const OriginAttributes& OriginAttributesRef() final {
245 return mOriginAttributes;
247 extensions::WebExtensionPolicy* AddonPolicy();
248 RefPtr<extensions::WebExtensionPolicyCore> AddonPolicyCore();
249 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
250 uint32_t PrivateBrowsingId() const {
251 return mOriginAttributes.mPrivateBrowsingId;
253 bool IsInIsolatedMozBrowserElement() const {
254 return mOriginAttributes.mInIsolatedMozBrowser;
257 PrincipalKind Kind() const { return mKind; }
259 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
260 const OriginAttributes& aOriginAttributes);
262 // If this is an add-on content script principal, returns its AddonPolicy.
263 // Otherwise returns null.
264 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
265 RefPtr<extensions::WebExtensionPolicyCore> ContentScriptAddonPolicyCore();
267 // Helper to check whether this principal is associated with an addon that
268 // allows unprivileged code to load aURI. aExplicit == true will prevent
269 // use of all_urls permission, requiring the domain in its permissions.
270 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
272 // Call these to avoid the cost of virtual dispatch.
273 inline bool FastEquals(nsIPrincipal* aOther);
274 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
275 inline bool FastSubsumes(nsIPrincipal* aOther);
276 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
277 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
278 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
280 // Fast way to check whether we have a system principal.
281 inline bool IsSystemPrincipal() const;
283 // Returns the principal to inherit when a caller with this principal loads
284 // the given URI.
286 // For most principal types, this returns the principal itself. For expanded
287 // principals, it returns the first sub-principal which subsumes the given URI
288 // (or, if no URI is given, the last allowlist principal).
289 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
291 /* Returns true if this principal's CSP should override a document's CSP for
292 * loads that it triggers. Currently true for expanded principals which
293 * subsume the document principal, and add-on content principals regardless
294 * of whether they subsume the document principal.
296 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal);
298 uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }
299 uint32_t GetOriginSuffixHash() const { return mOriginSuffix->hash(); }
301 virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;
303 protected:
304 BasePrincipal(PrincipalKind aKind, const nsACString& aOriginNoSuffix,
305 const OriginAttributes& aOriginAttributes);
306 BasePrincipal(BasePrincipal* aOther,
307 const OriginAttributes& aOriginAttributes);
309 virtual ~BasePrincipal();
311 // Note that this does not check OriginAttributes. Callers that depend on
312 // those must call Subsumes instead.
313 virtual bool SubsumesInternal(nsIPrincipal* aOther,
314 DocumentDomainConsideration aConsider) = 0;
316 // Internal, side-effect-free check to determine whether the concrete
317 // principal would allow the load ignoring any common behavior implemented in
318 // BasePrincipal::CheckMayLoad.
320 // Safe to call from any thread, unlike CheckMayLoad.
321 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
322 friend class ::ExpandedPrincipal;
324 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
325 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
326 bool aReport, uint64_t aInnerWindowID);
328 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
329 bool GetHasExplicitDomain() { return mHasExplicitDomain; }
331 // KeyValT holds a principal subtype-specific key value and the associated
332 // parsed value after JSON parsing.
333 template <typename SerializedKey>
334 struct KeyValT {
335 static_assert(sizeof(SerializedKey) == 1,
336 "SerializedKey should be a uint8_t");
337 SerializedKey key;
338 bool valueWasSerialized;
339 nsCString value;
342 // Common base class for all Deserializer implementations in concrete
343 // subclasses. Subclasses will initialize `mPrincipal` in `Read`, and then
344 // calls to `QueryInterface` will QI on the target object.
345 class Deserializer : public nsISerializable {
346 public:
347 NS_DECL_ISUPPORTS
348 NS_IMETHOD Write(nsIObjectOutputStream* aStream) override;
350 protected:
351 virtual ~Deserializer() = default;
352 RefPtr<BasePrincipal> mPrincipal;
355 private:
356 static constexpr Span<const char> JSONEnumKeyStrings[4] = {
357 MakeStringSpan("0"),
358 MakeStringSpan("1"),
359 MakeStringSpan("2"),
360 MakeStringSpan("3"),
363 static void WriteJSONProperty(JSONWriter& aWriter,
364 const Span<const char>& aKey,
365 const nsCString& aValue);
367 protected:
368 template <size_t EnumValue>
369 static inline constexpr const Span<const char>& JSONEnumKeyString() {
370 static_assert(EnumValue < ArrayLength(JSONEnumKeyStrings));
371 return JSONEnumKeyStrings[EnumValue];
373 template <size_t EnumValue>
374 static void WriteJSONProperty(JSONWriter& aWriter, const nsCString& aValue) {
375 WriteJSONProperty(aWriter, JSONEnumKeyString<EnumValue>(), aValue);
378 private:
379 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
380 nsIURI* aURI, const OriginAttributes& aAttrs,
381 const nsACString& aOriginNoSuffix, nsIURI* aInitialDomain);
383 bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther,
384 DocumentDomainConsideration aConsideration);
386 const RefPtr<nsAtom> mOriginNoSuffix;
387 const RefPtr<nsAtom> mOriginSuffix;
389 const OriginAttributes mOriginAttributes;
390 const PrincipalKind mKind;
391 std::atomic<bool> mHasExplicitDomain;
394 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
395 MOZ_ASSERT(aOther);
397 auto other = Cast(aOther);
398 if (Kind() != other->Kind()) {
399 // Principals of different kinds can't be equal.
400 return false;
403 // Two principals are considered to be equal if their origins are the same.
404 // If the two principals are content principals, their origin attributes
405 // (aka the origin suffix) must also match.
406 if (Kind() == eSystemPrincipal) {
407 return this == other;
410 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
411 return mOriginNoSuffix == other->mOriginNoSuffix &&
412 mOriginSuffix == other->mOriginSuffix;
415 MOZ_ASSERT(Kind() == eExpandedPrincipal);
416 return mOriginNoSuffix == other->mOriginNoSuffix;
419 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
420 MOZ_ASSERT(aOther);
422 // If neither of the principals have document.domain set, we use the fast path
423 // in Equals(). Otherwise, we fall back to the slow path below.
424 auto other = Cast(aOther);
425 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
426 return FastEquals(aOther);
429 // Principals of different kinds can't be equal.
430 if (Kind() != other->Kind()) {
431 return false;
434 // Only ContentPrincipals should have mHasExplicitDomain set to true, so test
435 // that we haven't ended up here instead of FastEquals by mistake.
436 MOZ_ASSERT(IsContentPrincipal(),
437 "Only content principals can set mHasExplicitDomain");
439 return Subsumes(aOther, ConsiderDocumentDomain) &&
440 other->Subsumes(this, ConsiderDocumentDomain);
443 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
444 MOZ_ASSERT(aOther);
446 // If two principals are equal, then they both subsume each other.
447 if (FastEquals(aOther)) {
448 return true;
451 // Otherwise, fall back to the slow path.
452 return Subsumes(aOther, DontConsiderDocumentDomain);
455 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
456 MOZ_ASSERT(aOther);
458 // If neither of the principals have document.domain set, we hand off to
459 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
460 // fall back to the slow path below.
461 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
462 return FastSubsumes(aOther);
465 return Subsumes(aOther, ConsiderDocumentDomain);
468 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
469 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
472 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
473 nsIPrincipal* aOther) {
474 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
477 inline bool BasePrincipal::IsSystemPrincipal() const {
478 return Kind() == eSystemPrincipal;
481 } // namespace mozilla
483 inline bool nsIPrincipal::IsSystemPrincipal() const {
484 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
487 #endif /* mozilla_BasePrincipal_h */