Bug 1883706: part 3) Implement `createHTML`, `createScript` and `createScriptURL...
[gecko.git] / caps / BasePrincipal.h
blobc1886646122dfd30e681bbf293b663a71052fc0c
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 GetUserContextId(uint32_t* aUserContextId) final;
167 NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
168 NS_IMETHOD GetSiteOrigin(nsACString& aSiteOrigin) final;
169 NS_IMETHOD GetSiteOriginNoSuffix(nsACString& aSiteOrigin) override;
170 NS_IMETHOD IsThirdPartyURI(nsIURI* uri, bool* aRes) override;
171 NS_IMETHOD IsThirdPartyPrincipal(nsIPrincipal* uri, bool* aRes) override;
172 NS_IMETHOD IsThirdPartyChannel(nsIChannel* aChannel, bool* aRes) override;
173 NS_IMETHOD GetIsOriginPotentiallyTrustworthy(bool* aResult) override;
174 NS_IMETHOD GetIsLoopbackHost(bool* aResult) override;
175 NS_IMETHOD IsSameOrigin(nsIURI* aURI, bool* aRes) override;
176 NS_IMETHOD GetPrefLightCacheKey(nsIURI* aURI, bool aWithCredentials,
177 const OriginAttributes& aOriginAttributes,
178 nsACString& _retval) override;
179 NS_IMETHOD HasFirstpartyStorageAccess(mozIDOMWindow* aCheckWindow,
180 uint32_t* aRejectedReason,
181 bool* aOutAllowed) override;
182 NS_IMETHOD GetAsciiHost(nsACString& aAsciiHost) override;
183 NS_IMETHOD GetLocalStorageQuotaKey(nsACString& aRes) override;
184 NS_IMETHOD AllowsRelaxStrictFileOriginPolicy(nsIURI* aURI,
185 bool* aRes) override;
186 NS_IMETHOD CreateReferrerInfo(mozilla::dom::ReferrerPolicy aReferrerPolicy,
187 nsIReferrerInfo** _retval) override;
188 NS_IMETHOD GetIsScriptAllowedByPolicy(
189 bool* aIsScriptAllowedByPolicy) override;
190 NS_IMETHOD GetStorageOriginKey(nsACString& aOriginKey) override;
192 NS_IMETHOD GetNextSubDomainPrincipal(
193 nsIPrincipal** aNextSubDomainPrincipal) override;
195 NS_IMETHOD GetPrecursorPrincipal(nsIPrincipal** aPrecursor) override;
197 nsresult ToJSON(nsACString& aJSON);
198 nsresult ToJSON(JSONWriter& aWriter);
199 nsresult WriteJSONProperties(JSONWriter& aWriter);
201 static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
203 // Method to write serializable fields which represent all of the fields to
204 // deserialize the principal.
205 virtual nsresult WriteJSONInnerProperties(JSONWriter& aWriter);
207 virtual bool AddonHasPermission(const nsAtom* aPerm);
209 virtual bool IsContentPrincipal() const { return false; };
211 static BasePrincipal* Cast(nsIPrincipal* aPrin) {
212 return static_cast<BasePrincipal*>(aPrin);
215 static BasePrincipal& Cast(nsIPrincipal& aPrin) {
216 return *static_cast<BasePrincipal*>(&aPrin);
219 static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
220 return static_cast<const BasePrincipal*>(aPrin);
223 static const BasePrincipal& Cast(const nsIPrincipal& aPrin) {
224 return *static_cast<const BasePrincipal*>(&aPrin);
227 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
228 const nsACString& aOrigin);
230 // This method may not create a content principal in case it's not possible to
231 // generate a correct origin from the passed URI. If this happens, a
232 // NullPrincipal is returned.
234 // If `aInitialDomain` is specified, and a ContentPrincipal is set, it will
235 // initially have its domain set to the given value, without re-computing js
236 // wrappers. Unlike `SetDomain()` this is safe to do off-main-thread.
238 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
239 nsIURI* aURI, const OriginAttributes& aAttrs,
240 nsIURI* aInitialDomain = nullptr);
242 const OriginAttributes& OriginAttributesRef() final {
243 return mOriginAttributes;
245 extensions::WebExtensionPolicy* AddonPolicy();
246 RefPtr<extensions::WebExtensionPolicyCore> AddonPolicyCore();
247 uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
248 uint32_t PrivateBrowsingId() const {
249 return mOriginAttributes.mPrivateBrowsingId;
252 PrincipalKind Kind() const { return mKind; }
254 already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
255 const OriginAttributes& aOriginAttributes);
257 // If this is an add-on content script principal, returns its AddonPolicy.
258 // Otherwise returns null.
259 extensions::WebExtensionPolicy* ContentScriptAddonPolicy();
260 RefPtr<extensions::WebExtensionPolicyCore> ContentScriptAddonPolicyCore();
262 // Helper to check whether this principal is associated with an addon that
263 // allows unprivileged code to load aURI. aExplicit == true will prevent
264 // use of all_urls permission, requiring the domain in its permissions.
265 bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);
267 // Call these to avoid the cost of virtual dispatch.
268 inline bool FastEquals(nsIPrincipal* aOther);
269 inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
270 inline bool FastSubsumes(nsIPrincipal* aOther);
271 inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
272 inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
273 inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
275 // Fast way to check whether we have a system principal.
276 inline bool IsSystemPrincipal() const;
278 // Returns the principal to inherit when a caller with this principal loads
279 // the given URI.
281 // For most principal types, this returns the principal itself. For expanded
282 // principals, it returns the first sub-principal which subsumes the given URI
283 // (or, if no URI is given, the last allowlist principal).
284 nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);
286 /* Returns true if this principal's CSP should override a document's CSP for
287 * loads that it triggers. Currently true for expanded principals which
288 * subsume the document principal, and add-on content principals regardless
289 * of whether they subsume the document principal.
291 bool OverridesCSP(nsIPrincipal* aDocumentPrincipal);
293 uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }
294 uint32_t GetOriginSuffixHash() const { return mOriginSuffix->hash(); }
296 virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;
298 protected:
299 BasePrincipal(PrincipalKind aKind, const nsACString& aOriginNoSuffix,
300 const OriginAttributes& aOriginAttributes);
301 BasePrincipal(BasePrincipal* aOther,
302 const OriginAttributes& aOriginAttributes);
304 virtual ~BasePrincipal();
306 // Note that this does not check OriginAttributes. Callers that depend on
307 // those must call Subsumes instead.
308 virtual bool SubsumesInternal(nsIPrincipal* aOther,
309 DocumentDomainConsideration aConsider) = 0;
311 // Internal, side-effect-free check to determine whether the concrete
312 // principal would allow the load ignoring any common behavior implemented in
313 // BasePrincipal::CheckMayLoad.
315 // Safe to call from any thread, unlike CheckMayLoad.
316 virtual bool MayLoadInternal(nsIURI* aURI) = 0;
317 friend class ::ExpandedPrincipal;
319 // Helper for implementing CheckMayLoad and CheckMayLoadWithReporting.
320 nsresult CheckMayLoadHelper(nsIURI* aURI, bool aAllowIfInheritsPrincipal,
321 bool aReport, uint64_t aInnerWindowID);
323 void SetHasExplicitDomain() { mHasExplicitDomain = true; }
324 bool GetHasExplicitDomain() { return mHasExplicitDomain; }
326 // KeyValT holds a principal subtype-specific key value and the associated
327 // parsed value after JSON parsing.
328 template <typename SerializedKey>
329 struct KeyValT {
330 static_assert(sizeof(SerializedKey) == 1,
331 "SerializedKey should be a uint8_t");
332 SerializedKey key;
333 bool valueWasSerialized;
334 nsCString value;
337 // Common base class for all Deserializer implementations in concrete
338 // subclasses. Subclasses will initialize `mPrincipal` in `Read`, and then
339 // calls to `QueryInterface` will QI on the target object.
340 class Deserializer : public nsISerializable {
341 public:
342 NS_DECL_ISUPPORTS
343 NS_IMETHOD Write(nsIObjectOutputStream* aStream) override;
345 protected:
346 virtual ~Deserializer() = default;
347 RefPtr<BasePrincipal> mPrincipal;
350 private:
351 static constexpr Span<const char> JSONEnumKeyStrings[4] = {
352 MakeStringSpan("0"),
353 MakeStringSpan("1"),
354 MakeStringSpan("2"),
355 MakeStringSpan("3"),
358 static void WriteJSONProperty(JSONWriter& aWriter,
359 const Span<const char>& aKey,
360 const nsCString& aValue);
362 protected:
363 template <size_t EnumValue>
364 static inline constexpr const Span<const char>& JSONEnumKeyString() {
365 static_assert(EnumValue < ArrayLength(JSONEnumKeyStrings));
366 return JSONEnumKeyStrings[EnumValue];
368 template <size_t EnumValue>
369 static void WriteJSONProperty(JSONWriter& aWriter, const nsCString& aValue) {
370 WriteJSONProperty(aWriter, JSONEnumKeyString<EnumValue>(), aValue);
373 private:
374 static already_AddRefed<BasePrincipal> CreateContentPrincipal(
375 nsIURI* aURI, const OriginAttributes& aAttrs,
376 const nsACString& aOriginNoSuffix, nsIURI* aInitialDomain);
378 bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther,
379 DocumentDomainConsideration aConsideration);
381 const RefPtr<nsAtom> mOriginNoSuffix;
382 const RefPtr<nsAtom> mOriginSuffix;
384 const OriginAttributes mOriginAttributes;
385 const PrincipalKind mKind;
386 std::atomic<bool> mHasExplicitDomain;
389 inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
390 MOZ_ASSERT(aOther);
392 auto other = Cast(aOther);
393 if (Kind() != other->Kind()) {
394 // Principals of different kinds can't be equal.
395 return false;
398 // Two principals are considered to be equal if their origins are the same.
399 // If the two principals are content principals, their origin attributes
400 // (aka the origin suffix) must also match.
401 if (Kind() == eSystemPrincipal) {
402 return this == other;
405 if (Kind() == eContentPrincipal || Kind() == eNullPrincipal) {
406 return mOriginNoSuffix == other->mOriginNoSuffix &&
407 mOriginSuffix == other->mOriginSuffix;
410 MOZ_ASSERT(Kind() == eExpandedPrincipal);
411 return mOriginNoSuffix == other->mOriginNoSuffix;
414 inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
415 MOZ_ASSERT(aOther);
417 // If neither of the principals have document.domain set, we use the fast path
418 // in Equals(). Otherwise, we fall back to the slow path below.
419 auto other = Cast(aOther);
420 if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
421 return FastEquals(aOther);
424 // Principals of different kinds can't be equal.
425 if (Kind() != other->Kind()) {
426 return false;
429 // Only ContentPrincipals should have mHasExplicitDomain set to true, so test
430 // that we haven't ended up here instead of FastEquals by mistake.
431 MOZ_ASSERT(IsContentPrincipal(),
432 "Only content principals can set mHasExplicitDomain");
434 return Subsumes(aOther, ConsiderDocumentDomain) &&
435 other->Subsumes(this, ConsiderDocumentDomain);
438 inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
439 MOZ_ASSERT(aOther);
441 // If two principals are equal, then they both subsume each other.
442 if (FastEquals(aOther)) {
443 return true;
446 // Otherwise, fall back to the slow path.
447 return Subsumes(aOther, DontConsiderDocumentDomain);
450 inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
451 MOZ_ASSERT(aOther);
453 // If neither of the principals have document.domain set, we hand off to
454 // FastSubsumes() which has fast paths for some special cases. Otherwise, we
455 // fall back to the slow path below.
456 if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
457 return FastSubsumes(aOther);
460 return Subsumes(aOther, ConsiderDocumentDomain);
463 inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
464 return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
467 inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
468 nsIPrincipal* aOther) {
469 return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
472 inline bool BasePrincipal::IsSystemPrincipal() const {
473 return Kind() == eSystemPrincipal;
476 } // namespace mozilla
478 inline bool nsIPrincipal::IsSystemPrincipal() const {
479 return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
482 #endif /* mozilla_BasePrincipal_h */