tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

LoadInfo.cpp (77570B)


      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/. */
      6 
      7 #include "mozilla/LoadInfo.h"
      8 
      9 #include "js/Array.h"               // JS::NewArrayObject
     10 #include "js/PropertyAndElement.h"  // JS_DefineElement
     11 #include "mozilla/Assertions.h"
     12 #include "mozilla/ExpandedPrincipal.h"
     13 #include "mozilla/dom/CanonicalBrowsingContext.h"
     14 #include "mozilla/dom/ClientIPCTypes.h"
     15 #include "mozilla/dom/ClientSource.h"
     16 #include "mozilla/dom/ContentChild.h"
     17 #include "mozilla/dom/DOMTypes.h"
     18 #include "mozilla/dom/Performance.h"
     19 #include "mozilla/dom/PerformanceStorage.h"
     20 #include "mozilla/dom/PolicyContainer.h"
     21 #include "mozilla/dom/BrowserChild.h"
     22 #include "mozilla/dom/ToJSValue.h"
     23 #include "mozilla/dom/BrowsingContext.h"
     24 #include "mozilla/dom/WindowGlobalParent.h"
     25 #include "mozilla/dom/nsHTTPSOnlyUtils.h"
     26 #include "mozilla/dom/InternalRequest.h"
     27 #include "mozilla/net/CookieJarSettings.h"
     28 #include "mozilla/NullPrincipal.h"
     29 #include "mozilla/StaticPrefs_network.h"
     30 #include "mozilla/StaticPrefs_security.h"
     31 #include "mozIThirdPartyUtil.h"
     32 #include "ThirdPartyUtil.h"
     33 #include "nsContentSecurityManager.h"
     34 #include "nsFrameLoader.h"
     35 #include "nsFrameLoaderOwner.h"
     36 #include "nsIContentPolicy.h"
     37 #include "nsIContentSecurityPolicy.h"
     38 #include "nsIDocShell.h"
     39 #include "mozilla/dom/Document.h"
     40 #include "nsIHttpChannel.h"
     41 #include "nsIHttpChannelInternal.h"
     42 #include "nsIInterfaceRequestorUtils.h"
     43 #include "nsILoadInfo.h"
     44 #include "nsIScriptElement.h"
     45 #include "nsISupportsImpl.h"
     46 #include "nsISupportsUtils.h"
     47 #include "nsIXPConnect.h"
     48 #include "nsDocShell.h"
     49 #include "nsGlobalWindowInner.h"
     50 #include "nsMixedContentBlocker.h"
     51 #include "nsQueryObject.h"
     52 #include "nsRedirectHistoryEntry.h"
     53 #include "nsSandboxFlags.h"
     54 #include "nsICookieService.h"
     55 
     56 using namespace mozilla::dom;
     57 
     58 namespace mozilla::net {
     59 
     60 static nsCString CurrentRemoteType() {
     61  MOZ_ASSERT(XRE_IsParentProcess() || XRE_IsContentProcess());
     62  if (ContentChild* cc = ContentChild::GetSingleton()) {
     63    return nsCString(cc->GetRemoteType());
     64  }
     65  return NOT_REMOTE_TYPE;
     66 }
     67 
     68 static nsContentPolicyType InternalContentPolicyTypeForFrame(
     69    CanonicalBrowsingContext* aBrowsingContext) {
     70  const auto& maybeEmbedderElementType =
     71      aBrowsingContext->GetEmbedderElementType();
     72  MOZ_ASSERT(maybeEmbedderElementType.isSome());
     73  auto embedderElementType = maybeEmbedderElementType.value();
     74 
     75  // Assign same type as in nsDocShell::DetermineContentType.
     76  // N.B. internal content policy type will never be TYPE_DOCUMENT
     77  return embedderElementType.EqualsLiteral("iframe")
     78             ? nsIContentPolicy::TYPE_INTERNAL_IFRAME
     79             : nsIContentPolicy::TYPE_INTERNAL_FRAME;
     80 }
     81 
     82 /* static */ Result<already_AddRefed<LoadInfo>, nsresult> LoadInfo::Create(
     83    nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
     84    nsINode* aLoadingContext, nsSecurityFlags aSecurityFlags,
     85    nsContentPolicyType aContentPolicyType,
     86    const Maybe<mozilla::dom::ClientInfo>& aLoadingClientInfo,
     87    const Maybe<mozilla::dom::ServiceWorkerDescriptor>& aController,
     88    uint32_t aSandboxFlags) {
     89  RefPtr<LoadInfo> loadInfo(new LoadInfo(
     90      aLoadingPrincipal, aTriggeringPrincipal, aLoadingContext, aSecurityFlags,
     91      aContentPolicyType, aLoadingClientInfo, aController, aSandboxFlags));
     92  if (loadInfo->IsDocumentMissingClientInfo()) {
     93    return Err(NS_ERROR_CONTENT_BLOCKED);
     94  }
     95  return loadInfo.forget();
     96 }
     97 
     98 bool LoadInfo::IsDocumentMissingClientInfo() {
     99  // Only check in the content process for now.
    100  if (!XRE_IsContentProcess() || mClientInfo.isSome()) {
    101    return false;
    102  }
    103 
    104  // No node means no document, so there is nothing to check.
    105  nsCOMPtr<nsINode> node = LoadingNode();
    106  if (!node) {
    107    return false;
    108  }
    109 
    110  // Don't bother checking loads that will end up in a privileged context (for
    111  // now).
    112  if (mLoadingPrincipal->IsSystemPrincipal()) {
    113    return false;
    114  }
    115  if (mLoadingPrincipal->SchemeIs("about") &&
    116      !mLoadingPrincipal->IsContentAccessibleAboutURI()) {
    117    return false;
    118  }
    119 
    120  // The nsDataDocumentContentPolicy is responsible restricting these documents.
    121  Document* doc = node->OwnerDoc();
    122  if (doc->IsLoadedAsData() || doc->IsResourceDoc()) {
    123    return false;
    124  }
    125 
    126  ExtContentPolicy externalType = nsILoadInfo::GetExternalContentPolicyType();
    127  if (externalType == ExtContentPolicy::TYPE_DTD ||
    128      externalType == ExtContentPolicy::TYPE_OTHER ||
    129      externalType == ExtContentPolicy::TYPE_SPECULATIVE ||
    130      externalType == ExtContentPolicy::TYPE_SAVEAS_DOWNLOAD ||
    131      externalType == ExtContentPolicy::TYPE_DOCUMENT ||
    132      externalType == ExtContentPolicy::TYPE_SUBDOCUMENT) {
    133    return false;
    134  }
    135 
    136  NS_WARNING(
    137      "Prevented the creation of a LoadInfo for a document without a "
    138      "ClientInfo!");
    139  return true;
    140 }
    141 
    142 /* static */ already_AddRefed<LoadInfo> LoadInfo::CreateForDocument(
    143    dom::CanonicalBrowsingContext* aBrowsingContext, nsIURI* aURI,
    144    nsIPrincipal* aTriggeringPrincipal, const nsACString& aTriggeringRemoteType,
    145    const OriginAttributes& aOriginAttributes, nsSecurityFlags aSecurityFlags,
    146    uint32_t aSandboxFlags) {
    147  return MakeAndAddRef<LoadInfo>(aBrowsingContext, aURI, aTriggeringPrincipal,
    148                                 aTriggeringRemoteType, aOriginAttributes,
    149                                 aSecurityFlags, aSandboxFlags);
    150 }
    151 
    152 /* static */ already_AddRefed<LoadInfo> LoadInfo::CreateForFrame(
    153    dom::CanonicalBrowsingContext* aBrowsingContext,
    154    nsIPrincipal* aTriggeringPrincipal, const nsACString& aTriggeringRemoteType,
    155    nsSecurityFlags aSecurityFlags, uint32_t aSandboxFlags) {
    156  return MakeAndAddRef<LoadInfo>(aBrowsingContext, aTriggeringPrincipal,
    157                                 aTriggeringRemoteType, aSecurityFlags,
    158                                 aSandboxFlags);
    159 }
    160 
    161 /* static */ already_AddRefed<LoadInfo> LoadInfo::CreateForNonDocument(
    162    dom::WindowGlobalParent* aParentWGP, nsIPrincipal* aTriggeringPrincipal,
    163    nsContentPolicyType aContentPolicyType, nsSecurityFlags aSecurityFlags,
    164    uint32_t aSandboxFlags) {
    165  return MakeAndAddRef<LoadInfo>(
    166      aParentWGP, aTriggeringPrincipal, aParentWGP->GetRemoteType(),
    167      aContentPolicyType, aSecurityFlags, aSandboxFlags);
    168 }
    169 
    170 static_assert(uint8_t(ForceMediaDocument::None) == 0,
    171              "The default value of mForceMediaDocument depends on this.");
    172 
    173 LoadInfo::LoadInfo(
    174    nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
    175    nsINode* aLoadingContext, nsSecurityFlags aSecurityFlags,
    176    nsContentPolicyType aContentPolicyType,
    177    const Maybe<mozilla::dom::ClientInfo>& aLoadingClientInfo,
    178    const Maybe<mozilla::dom::ServiceWorkerDescriptor>& aController,
    179    uint32_t aSandboxFlags)
    180    : mLoadingPrincipal(aLoadingContext ? aLoadingContext->NodePrincipal()
    181                                        : aLoadingPrincipal),
    182      mTriggeringPrincipal(aTriggeringPrincipal ? aTriggeringPrincipal
    183                                                : mLoadingPrincipal.get()),
    184      mTriggeringRemoteType(CurrentRemoteType()),
    185      mSandboxedNullPrincipalID(nsID::GenerateUUID()),
    186      mClientInfo(aLoadingClientInfo),
    187      mController(aController),
    188      mLoadingContext(do_GetWeakReference(aLoadingContext)),
    189      mSecurityFlags(aSecurityFlags),
    190      mSandboxFlags(aSandboxFlags),
    191      mInternalContentPolicyType(aContentPolicyType) {
    192  MOZ_ASSERT(mLoadingPrincipal);
    193  MOZ_ASSERT(mTriggeringPrincipal);
    194 
    195 #ifdef DEBUG
    196  // TYPE_DOCUMENT loads initiated by javascript tests will go through
    197  // nsIOService and use the wrong constructor.  Don't enforce the
    198  // !TYPE_DOCUMENT check in those cases
    199  bool skipContentTypeCheck = false;
    200  skipContentTypeCheck =
    201      Preferences::GetBool("network.loadinfo.skip_type_assertion");
    202 #endif
    203 
    204  // This constructor shouldn't be used for TYPE_DOCUMENT loads that don't
    205  // have a loadingPrincipal
    206  MOZ_ASSERT(skipContentTypeCheck || mLoadingPrincipal ||
    207             mInternalContentPolicyType != nsIContentPolicy::TYPE_DOCUMENT);
    208 
    209  // We should only get an explicit controller for subresource requests.
    210  MOZ_DIAGNOSTIC_ASSERT(aController.isNothing() ||
    211                        !nsContentUtils::IsNonSubresourceInternalPolicyType(
    212                            mInternalContentPolicyType));
    213 
    214  // TODO(bug 1259873): Above, we initialize mIsThirdPartyContext to false
    215  // meaning that consumers of LoadInfo that don't pass a context or pass a
    216  // context from which we can't find a window will default to assuming that
    217  // they're 1st party. It would be nice if we could default "safe" and assume
    218  // that we are 3rd party until proven otherwise.
    219 
    220  // if consumers pass both, aLoadingContext and aLoadingPrincipal
    221  // then the loadingPrincipal must be the same as the node's principal
    222  MOZ_ASSERT(!aLoadingContext || !aLoadingPrincipal ||
    223             aLoadingContext->NodePrincipal() == aLoadingPrincipal);
    224 
    225  // if the load is sandboxed, we can not also inherit the principal
    226  if (mSandboxFlags & SANDBOXED_ORIGIN) {
    227    mForceInheritPrincipalDropped =
    228        (mSecurityFlags & nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL);
    229    mSecurityFlags &= ~nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
    230  }
    231 
    232  ExtContentPolicyType externalType =
    233      nsContentUtils::InternalContentPolicyTypeToExternal(aContentPolicyType);
    234 
    235  if (aLoadingContext) {
    236    // Ensure that all network requests for a window client have the ClientInfo
    237    // properly set.  Workers must currently pass the loading ClientInfo
    238    // explicitly. We allow main thread requests to explicitly pass the value as
    239    // well.
    240    if (mClientInfo.isNothing()) {
    241      mClientInfo = aLoadingContext->OwnerDoc()->GetClientInfo();
    242    }
    243 
    244    // For subresource loads set the service worker based on the calling
    245    // context's controller.  Workers must currently pass the controller in
    246    // explicitly.  We allow main thread requests to explicitly pass the value
    247    // as well, but otherwise extract from the loading context here.
    248    if (mController.isNothing() &&
    249        !nsContentUtils::IsNonSubresourceInternalPolicyType(
    250            mInternalContentPolicyType)) {
    251      mController = aLoadingContext->OwnerDoc()->GetController();
    252    }
    253 
    254    nsCOMPtr<nsPIDOMWindowOuter> contextOuter =
    255        aLoadingContext->OwnerDoc()->GetWindow();
    256    if (contextOuter) {
    257      ComputeIsThirdPartyContext(contextOuter);
    258      RefPtr<dom::BrowsingContext> bc = contextOuter->GetBrowsingContext();
    259      MOZ_ASSERT(bc);
    260      mBrowsingContextID = bc->Id();
    261 
    262      nsGlobalWindowInner* innerWindow =
    263          nsGlobalWindowInner::Cast(contextOuter->GetCurrentInnerWindow());
    264      if (innerWindow) {
    265        mTopLevelPrincipal = innerWindow->GetTopLevelAntiTrackingPrincipal();
    266 
    267        if (!mTopLevelPrincipal &&
    268            externalType == ExtContentPolicy::TYPE_SUBDOCUMENT && bc->IsTop()) {
    269          // If this is the first level iframe, innerWindow is our top-level
    270          // principal.
    271          mTopLevelPrincipal = innerWindow->GetPrincipal();
    272        }
    273      }
    274 
    275      // Let's clone and inherit the cookie behavior and permission from the
    276      // parent document.
    277      mCookieJarSettings = CookieJarSettings::Cast(
    278                               aLoadingContext->OwnerDoc()->CookieJarSettings())
    279                               ->Clone();
    280    }
    281    // XXX(sunil) browsing context id is not set. Check how we need to handle
    282    // setting of parent IP address space if not availble.
    283 
    284    mInnerWindowID = aLoadingContext->OwnerDoc()->InnerWindowID();
    285    RefPtr<WindowContext> ctx = WindowContext::GetById(mInnerWindowID);
    286    if (ctx) {
    287      mLoadingEmbedderPolicy = ctx->GetEmbedderPolicy();
    288    }
    289    mDocumentHasUserInteracted =
    290        aLoadingContext->OwnerDoc()->UserHasInteracted();
    291 
    292    // Inherit HTTPS-Only Mode flags from parent document.
    293    mHttpsOnlyStatus |= nsHTTPSOnlyUtils::GetStatusForSubresourceLoad(
    294        aLoadingContext->OwnerDoc()->HttpsOnlyStatus());
    295 
    296    // When the element being loaded is a frame, we choose the frame's window
    297    // for the window ID and the frame element's window as the parent
    298    // window. This is the behavior that Chrome exposes to add-ons.
    299    // NB: If the frameLoaderOwner doesn't have a frame loader, then the load
    300    // must be coming from an object (such as a plugin) that's loaded into it
    301    // instead of a document being loaded. In that case, treat this object like
    302    // any other non-document-loading element.
    303    RefPtr<nsFrameLoaderOwner> frameLoaderOwner =
    304        do_QueryObject(aLoadingContext);
    305    RefPtr<nsFrameLoader> fl =
    306        frameLoaderOwner ? frameLoaderOwner->GetFrameLoader() : nullptr;
    307    if (fl) {
    308      nsCOMPtr<nsIDocShell> docShell = fl->GetDocShell(IgnoreErrors());
    309      if (docShell) {
    310        nsCOMPtr<nsPIDOMWindowOuter> outerWindow = do_GetInterface(docShell);
    311        if (outerWindow) {
    312          RefPtr<dom::BrowsingContext> bc = outerWindow->GetBrowsingContext();
    313          mFrameBrowsingContextID = bc ? bc->Id() : 0;
    314        }
    315      }
    316    }
    317 
    318    // if the document forces all mixed content to be blocked, then we
    319    // store that bit for all requests on the loadinfo.
    320    mBlockAllMixedContent =
    321        aLoadingContext->OwnerDoc()->GetBlockAllMixedContent(false) ||
    322        (nsContentUtils::IsPreloadType(mInternalContentPolicyType) &&
    323         aLoadingContext->OwnerDoc()->GetBlockAllMixedContent(true));
    324 
    325    if (mLoadingPrincipal && BasePrincipal::Cast(mTriggeringPrincipal)
    326                                 ->OverridesCSP(mLoadingPrincipal)) {
    327      // if the load is triggered by an addon which potentially overrides the
    328      // CSP of the document, then do not force insecure requests to be
    329      // upgraded.
    330      mUpgradeInsecureRequests = false;
    331    } else {
    332      // if the document forces all requests to be upgraded from http to https,
    333      // then we should do that for all requests. If it only forces preloads to
    334      // be upgraded then we should enforce upgrade insecure requests only for
    335      // preloads.
    336      mUpgradeInsecureRequests =
    337          aLoadingContext->OwnerDoc()->GetUpgradeInsecureRequests(false) ||
    338          (nsContentUtils::IsPreloadType(mInternalContentPolicyType) &&
    339           aLoadingContext->OwnerDoc()->GetUpgradeInsecureRequests(true));
    340    }
    341 
    342    if (nsMixedContentBlocker::IsUpgradableContentType(
    343            mInternalContentPolicyType)) {
    344      // Check the load is within a secure context but ignore loopback URLs
    345      if (mLoadingPrincipal->GetIsOriginPotentiallyTrustworthy() &&
    346          !mLoadingPrincipal->GetIsLoopbackHost()) {
    347        if (StaticPrefs::security_mixed_content_upgrade_display_content()) {
    348          mBrowserUpgradeInsecureRequests = true;
    349        } else {
    350          mBrowserWouldUpgradeInsecureRequests = true;
    351        }
    352      }
    353    }
    354  }
    355  mOriginAttributes = mLoadingPrincipal->OriginAttributesRef();
    356 
    357  // We need to do this after inheriting the document's origin attributes
    358  // above, in case the loading principal ends up being the system principal.
    359  if (aLoadingContext) {
    360    nsCOMPtr<nsILoadContext> loadContext =
    361        aLoadingContext->OwnerDoc()->GetLoadContext();
    362    nsCOMPtr<nsIDocShell> docShell = aLoadingContext->OwnerDoc()->GetDocShell();
    363    if (loadContext && docShell &&
    364        docShell->GetBrowsingContext()->IsContent()) {
    365      bool usePrivateBrowsing;
    366      nsresult rv = loadContext->GetUsePrivateBrowsing(&usePrivateBrowsing);
    367      if (NS_SUCCEEDED(rv)) {
    368        mOriginAttributes.SyncAttributesWithPrivateBrowsing(usePrivateBrowsing);
    369      }
    370    }
    371 
    372    if (!loadContext) {
    373      // Things like svg documents being used as images don't have a load
    374      // context or a docshell, in that case try to inherit private browsing
    375      // from the documents channel (which is how we determine which imgLoader
    376      // is used).
    377      nsCOMPtr<nsIChannel> channel = aLoadingContext->OwnerDoc()->GetChannel();
    378      if (channel) {
    379        mOriginAttributes.SyncAttributesWithPrivateBrowsing(
    380            NS_UsePrivateBrowsing(channel));
    381      }
    382    }
    383 
    384    UpdateParentAddressSpaceInfo();
    385 
    386    // For chrome docshell, the mPrivateBrowsingId remains 0 even its
    387    // UsePrivateBrowsing() is true, so we only update the mPrivateBrowsingId in
    388    // origin attributes if the type of the docshell is content.
    389    MOZ_ASSERT(!docShell || !docShell->GetBrowsingContext()->IsChrome() ||
    390                   mOriginAttributes.mPrivateBrowsingId == 0,
    391               "chrome docshell shouldn't have mPrivateBrowsingId set.");
    392  }
    393 }
    394 
    395 /* Constructor takes an outer window, but no loadingNode or loadingPrincipal.
    396 * This constructor should only be used for TYPE_DOCUMENT loads, since they
    397 * have a null loadingNode and loadingPrincipal.
    398 */
    399 LoadInfo::LoadInfo(nsPIDOMWindowOuter* aOuterWindow, nsIURI* aURI,
    400                   nsIPrincipal* aTriggeringPrincipal,
    401                   nsISupports* aContextForTopLevelLoad,
    402                   nsSecurityFlags aSecurityFlags, uint32_t aSandboxFlags)
    403    : mTriggeringPrincipal(aTriggeringPrincipal),
    404      mTriggeringRemoteType(CurrentRemoteType()),
    405      mSandboxedNullPrincipalID(nsID::GenerateUUID()),
    406      mContextForTopLevelLoad(do_GetWeakReference(aContextForTopLevelLoad)),
    407      mSecurityFlags(aSecurityFlags),
    408      mSandboxFlags(aSandboxFlags),
    409      mInternalContentPolicyType(nsIContentPolicy::TYPE_DOCUMENT) {
    410  // Top-level loads are never third-party
    411  // Grab the information we can out of the window.
    412  MOZ_ASSERT(aOuterWindow);
    413  MOZ_ASSERT(mTriggeringPrincipal);
    414 
    415  // if the load is sandboxed, we can not also inherit the principal
    416  if (mSandboxFlags & SANDBOXED_ORIGIN) {
    417    mForceInheritPrincipalDropped =
    418        (mSecurityFlags & nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL);
    419    mSecurityFlags &= ~nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
    420  }
    421 
    422  RefPtr<BrowsingContext> bc = aOuterWindow->GetBrowsingContext();
    423  mBrowsingContextID = bc ? bc->Id() : 0;
    424 
    425  // This should be removed in bug 1618557
    426  nsGlobalWindowInner* innerWindow =
    427      nsGlobalWindowInner::Cast(aOuterWindow->GetCurrentInnerWindow());
    428  if (innerWindow) {
    429    mTopLevelPrincipal = innerWindow->GetTopLevelAntiTrackingPrincipal();
    430  }
    431 
    432  // get the docshell from the outerwindow, and then get the originattributes
    433  nsCOMPtr<nsIDocShell> docShell = aOuterWindow->GetDocShell();
    434  MOZ_ASSERT(docShell);
    435  mOriginAttributes = nsDocShell::Cast(docShell)->GetOriginAttributes();
    436 
    437  // We sometimes use this constructor for security checks for outer windows
    438  // that aren't top level.
    439  if (aSecurityFlags != nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK) {
    440    MOZ_ASSERT(aOuterWindow->GetBrowsingContext()->IsTop());
    441  }
    442 
    443 #ifdef DEBUG
    444  if (docShell->GetBrowsingContext()->IsChrome()) {
    445    MOZ_ASSERT(mOriginAttributes.mPrivateBrowsingId == 0,
    446               "chrome docshell shouldn't have mPrivateBrowsingId set.");
    447  }
    448 #endif
    449 
    450  // Let's take the current cookie behavior and current cookie permission
    451  // for the documents' loadInfo. Note that for any other loadInfos,
    452  // cookieBehavior will be BEHAVIOR_REJECT for security reasons.
    453  bool isPrivate = mOriginAttributes.IsPrivateBrowsing();
    454  bool shouldResistFingerprinting =
    455      nsContentUtils::ShouldResistFingerprinting_dangerous(
    456          aURI, mOriginAttributes,
    457          "We are creating CookieJarSettings, so we can't have one already.",
    458          RFPTarget::IsAlwaysEnabledForPrecompute);
    459  mCookieJarSettings = CookieJarSettings::Create(
    460      isPrivate ? CookieJarSettings::ePrivate : CookieJarSettings::eRegular,
    461      shouldResistFingerprinting);
    462 
    463  UpdateParentAddressSpaceInfo();
    464 }
    465 
    466 LoadInfo::LoadInfo(dom::CanonicalBrowsingContext* aBrowsingContext,
    467                   nsIURI* aURI, nsIPrincipal* aTriggeringPrincipal,
    468                   const nsACString& aTriggeringRemoteType,
    469                   const OriginAttributes& aOriginAttributes,
    470                   nsSecurityFlags aSecurityFlags, uint32_t aSandboxFlags)
    471    : mTriggeringPrincipal(aTriggeringPrincipal),
    472      mTriggeringRemoteType(aTriggeringRemoteType),
    473      mSandboxedNullPrincipalID(nsID::GenerateUUID()),
    474      mSecurityFlags(aSecurityFlags),
    475      mSandboxFlags(aSandboxFlags),
    476      mInternalContentPolicyType(nsIContentPolicy::TYPE_DOCUMENT) {
    477  // Top-level loads are never third-party
    478  // Grab the information we can out of the window.
    479  MOZ_ASSERT(aBrowsingContext);
    480  MOZ_ASSERT(mTriggeringPrincipal);
    481  MOZ_ASSERT(aSecurityFlags !=
    482             nsILoadInfo::SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK);
    483 
    484  // if the load is sandboxed, we can not also inherit the principal
    485  if (mSandboxFlags & SANDBOXED_ORIGIN) {
    486    mForceInheritPrincipalDropped =
    487        (mSecurityFlags & nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL);
    488    mSecurityFlags &= ~nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
    489  }
    490 
    491  mBrowsingContextID = aBrowsingContext->Id();
    492  mOriginAttributes = aOriginAttributes;
    493 
    494 #ifdef DEBUG
    495  if (aBrowsingContext->IsChrome()) {
    496    MOZ_ASSERT(mOriginAttributes.mPrivateBrowsingId == 0,
    497               "chrome docshell shouldn't have mPrivateBrowsingId set.");
    498  }
    499 #endif
    500 
    501  // This code path can be taken when loading an about:blank document, which
    502  // means we might think that we should be exempted from resist fingerprinting.
    503  // If we think that, we should defer to any opener, if it is present. If the
    504  // opener is also exempted, then it continues to be exempted. Regardless of
    505  // what ShouldRFP says, we _also_ need to propagate any RandomizationKey we
    506  // have.
    507  bool shouldResistFingerprinting =
    508      nsContentUtils::ShouldResistFingerprinting_dangerous(
    509          aURI, mOriginAttributes,
    510          "We are creating CookieJarSettings, so we can't have one already.",
    511          RFPTarget::IsAlwaysEnabledForPrecompute);
    512 
    513  nsresult rv = NS_ERROR_NOT_AVAILABLE;
    514  nsTArray<uint8_t> randomKey;
    515  RefPtr<BrowsingContext> opener = aBrowsingContext->GetOpener();
    516  if (opener) {
    517    MOZ_ASSERT(opener->GetCurrentWindowContext());
    518    if (opener->GetCurrentWindowContext()) {
    519      shouldResistFingerprinting |=
    520          opener->GetCurrentWindowContext()->ShouldResistFingerprinting();
    521    }
    522 
    523    // In the parent, we need to get the CJS from the CanonicalBrowsingContext's
    524    // WindowGlobalParent If we're in the child, we probably have a reference to
    525    // the opener's document, and can get it from there.
    526    if (XRE_IsParentProcess()) {
    527      MOZ_ASSERT(opener->Canonical()->GetCurrentWindowGlobal());
    528      if (opener->Canonical()->GetCurrentWindowGlobal()) {
    529        MOZ_ASSERT(
    530            opener->Canonical()->GetCurrentWindowGlobal()->CookieJarSettings());
    531        rv = opener->Canonical()
    532                 ->GetCurrentWindowGlobal()
    533                 ->CookieJarSettings()
    534                 ->GetFingerprintingRandomizationKey(randomKey);
    535      }
    536    } else if (opener->GetDocument()) {
    537      MOZ_ASSERT(false, "Code is in child");
    538      rv = opener->GetDocument()
    539               ->CookieJarSettings()
    540               ->GetFingerprintingRandomizationKey(randomKey);
    541    }
    542  }
    543 
    544  const bool isPrivate = mOriginAttributes.IsPrivateBrowsing();
    545 
    546  // Let's take the current cookie behavior and current cookie permission
    547  // for the documents' loadInfo. Note that for any other loadInfos,
    548  // cookieBehavior will be BEHAVIOR_REJECT for security reasons.
    549  mCookieJarSettings = CookieJarSettings::Create(
    550      isPrivate ? CookieJarSettings::ePrivate : CookieJarSettings::eRegular,
    551      shouldResistFingerprinting);
    552 
    553  if (NS_SUCCEEDED(rv)) {
    554    net::CookieJarSettings::Cast(mCookieJarSettings)
    555        ->SetFingerprintingRandomizationKey(randomKey);
    556  }
    557 
    558  UpdateParentAddressSpaceInfo();
    559 }
    560 
    561 LoadInfo::LoadInfo(dom::WindowGlobalParent* aParentWGP,
    562                   nsIPrincipal* aTriggeringPrincipal,
    563                   const nsACString& aTriggeringRemoteType,
    564                   nsContentPolicyType aContentPolicyType,
    565                   nsSecurityFlags aSecurityFlags, uint32_t aSandboxFlags)
    566    : mTriggeringPrincipal(aTriggeringPrincipal),
    567      mTriggeringRemoteType(aTriggeringRemoteType),
    568      mSandboxedNullPrincipalID(nsID::GenerateUUID()),
    569      mSecurityFlags(aSecurityFlags),
    570      mSandboxFlags(aSandboxFlags),
    571      mInternalContentPolicyType(aContentPolicyType) {
    572  CanonicalBrowsingContext* parentBC = aParentWGP->BrowsingContext();
    573  MOZ_ASSERT(parentBC);
    574  ComputeAncestors(parentBC, mAncestorPrincipals, mAncestorBrowsingContextIDs);
    575 
    576  RefPtr<WindowGlobalParent> topLevelWGP = aParentWGP->TopWindowContext();
    577 
    578  // if the load is sandboxed, we can not also inherit the principal
    579  if (mSandboxFlags & SANDBOXED_ORIGIN) {
    580    mForceInheritPrincipalDropped =
    581        (mSecurityFlags & nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL);
    582    mSecurityFlags &= ~nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
    583  }
    584 
    585  // Ensure that all network requests for a window client have the ClientInfo
    586  // properly set.
    587  mClientInfo = aParentWGP->GetClientInfo();
    588  mLoadingPrincipal = aParentWGP->DocumentPrincipal();
    589  ComputeIsThirdPartyContext(aParentWGP);
    590 
    591  mBrowsingContextID = parentBC->Id();
    592 
    593  // Special treatment for resources injected by add-ons if not document,
    594  // iframe, workers.
    595  if (!nsContentUtils::IsNonSubresourceInternalPolicyType(aContentPolicyType) &&
    596      aTriggeringPrincipal &&
    597      StaticPrefs::privacy_antitracking_isolateContentScriptResources() &&
    598      nsContentUtils::IsExpandedPrincipal(aTriggeringPrincipal)) {
    599    bool shouldResistFingerprinting =
    600        nsContentUtils::ShouldResistFingerprinting_dangerous(
    601            mLoadingPrincipal,
    602            "CookieJarSettings can't exist yet, we're creating it",
    603            RFPTarget::IsAlwaysEnabledForPrecompute);
    604    mCookieJarSettings = CookieJarSettings::Create(
    605        nsICookieService::BEHAVIOR_REJECT,
    606        StoragePrincipalHelper::PartitionKeyForExpandedPrincipal(
    607            aTriggeringPrincipal),
    608        OriginAttributes::IsFirstPartyEnabled(), false,
    609        shouldResistFingerprinting);
    610  }
    611 
    612  if (!mCookieJarSettings) {
    613    // Let's clone and inherit the cookie behavior and permission from the
    614    // embedder document.
    615    mCookieJarSettings =
    616        CookieJarSettings::Cast(aParentWGP->CookieJarSettings())->Clone();
    617    if (topLevelWGP->BrowsingContext()->IsTop()) {
    618      if (mCookieJarSettings) {
    619        bool stopAtOurLevel = mCookieJarSettings->GetCookieBehavior() ==
    620                              nsICookieService::BEHAVIOR_REJECT_TRACKER;
    621        if (!stopAtOurLevel ||
    622            topLevelWGP->OuterWindowId() != aParentWGP->OuterWindowId()) {
    623          mTopLevelPrincipal = topLevelWGP->DocumentPrincipal();
    624        }
    625      }
    626    }
    627  }
    628 
    629  if (!mTopLevelPrincipal && parentBC->IsTop()) {
    630    // If this is the first level iframe, embedder WindowGlobalParent's document
    631    // principal is our top-level principal.
    632    mTopLevelPrincipal = aParentWGP->DocumentPrincipal();
    633  }
    634 
    635  mInnerWindowID = aParentWGP->InnerWindowId();
    636  mDocumentHasUserInteracted = aParentWGP->DocumentHasUserInteracted();
    637 
    638  // if the document forces all mixed content to be blocked, then we
    639  // store that bit for all requests on the loadinfo.
    640  mBlockAllMixedContent = aParentWGP->GetDocumentBlockAllMixedContent();
    641 
    642  if (mTopLevelPrincipal && BasePrincipal::Cast(mTriggeringPrincipal)
    643                                ->OverridesCSP(mTopLevelPrincipal)) {
    644    // if the load is triggered by an addon which potentially overrides the
    645    // CSP of the document, then do not force insecure requests to be
    646    // upgraded.
    647    mUpgradeInsecureRequests = false;
    648  } else {
    649    // if the document forces all requests to be upgraded from http to https,
    650    // then we should do that for all requests. If it only forces preloads to
    651    // be upgraded then we should enforce upgrade insecure requests only for
    652    // preloads.
    653    mUpgradeInsecureRequests = aParentWGP->GetDocumentUpgradeInsecureRequests();
    654  }
    655  mOriginAttributes = mLoadingPrincipal->OriginAttributesRef();
    656 
    657  // We need to do this after inheriting the document's origin attributes
    658  // above, in case the loading principal ends up being the system principal.
    659  if (parentBC->IsContent()) {
    660    mOriginAttributes.SyncAttributesWithPrivateBrowsing(
    661        parentBC->UsePrivateBrowsing());
    662  }
    663 
    664  // Inherit HTTPS-Only Mode flags from embedder document.
    665  mHttpsOnlyStatus |= nsHTTPSOnlyUtils::GetStatusForSubresourceLoad(
    666      aParentWGP->HttpsOnlyStatus());
    667 
    668  // For chrome BC, the mPrivateBrowsingId remains 0 even its
    669  // UsePrivateBrowsing() is true, so we only update the mPrivateBrowsingId in
    670  // origin attributes if the type of the BC is content.
    671  if (parentBC->IsChrome()) {
    672    MOZ_ASSERT(mOriginAttributes.mPrivateBrowsingId == 0,
    673               "chrome docshell shouldn't have mPrivateBrowsingId set.");
    674  }
    675 
    676  RefPtr<WindowContext> ctx = WindowContext::GetById(mInnerWindowID);
    677  if (ctx) {
    678    mLoadingEmbedderPolicy = ctx->GetEmbedderPolicy();
    679 
    680    if (Document* document = ctx->GetDocument()) {
    681      mIsOriginTrialCoepCredentiallessEnabledForTopLevel =
    682          document->Trials().IsEnabled(OriginTrial::CoepCredentialless);
    683    }
    684  }
    685 
    686  UpdateParentAddressSpaceInfo();
    687 }
    688 
    689 // Used for TYPE_FRAME or TYPE_IFRAME load.
    690 LoadInfo::LoadInfo(dom::CanonicalBrowsingContext* aBrowsingContext,
    691                   nsIPrincipal* aTriggeringPrincipal,
    692                   const nsACString& aTriggeringRemoteType,
    693                   nsSecurityFlags aSecurityFlags, uint32_t aSandboxFlags)
    694    : LoadInfo(aBrowsingContext->GetParentWindowContext(), aTriggeringPrincipal,
    695               aTriggeringRemoteType,
    696               InternalContentPolicyTypeForFrame(aBrowsingContext),
    697               aSecurityFlags, aSandboxFlags) {
    698  mFrameBrowsingContextID = aBrowsingContext->Id();
    699 }
    700 
    701 LoadInfo::LoadInfo(const LoadInfo& rhs)
    702    : mLoadingPrincipal(rhs.mLoadingPrincipal),
    703      mTriggeringPrincipal(rhs.mTriggeringPrincipal),
    704      mPrincipalToInherit(rhs.mPrincipalToInherit),
    705      mTopLevelPrincipal(rhs.mTopLevelPrincipal),
    706      mResultPrincipalURI(rhs.mResultPrincipalURI),
    707      mChannelCreationOriginalURI(rhs.mChannelCreationOriginalURI),
    708      mCookieJarSettings(rhs.mCookieJarSettings),
    709      mPolicyContainerToInherit(rhs.mPolicyContainerToInherit),
    710      mContainerFeaturePolicyInfo(rhs.mContainerFeaturePolicyInfo),
    711      mTriggeringRemoteType(rhs.mTriggeringRemoteType),
    712      mSandboxedNullPrincipalID(rhs.mSandboxedNullPrincipalID),
    713      mClientInfo(rhs.mClientInfo),
    714      // mReservedClientSource must be handled specially during redirect
    715      // mReservedClientInfo must be handled specially during redirect
    716      // mInitialClientInfo must be handled specially during redirect
    717      mController(rhs.mController),
    718      mPerformanceStorage(rhs.mPerformanceStorage),
    719      mLoadingContext(rhs.mLoadingContext),
    720      mContextForTopLevelLoad(rhs.mContextForTopLevelLoad),
    721      mSecurityFlags(rhs.mSecurityFlags),
    722      mSandboxFlags(rhs.mSandboxFlags),
    723      mInternalContentPolicyType(rhs.mInternalContentPolicyType),
    724      mTainting(rhs.mTainting),
    725 #define DEFINE_INIT(_t, name, _n, _d) m##name(rhs.m##name),
    726      LOADINFO_FOR_EACH_FIELD(DEFINE_INIT, LOADINFO_DUMMY_SETTER)
    727 #undef DEFINE_INIT
    728 
    729          mWorkerAssociatedBrowsingContextID(
    730              rhs.mWorkerAssociatedBrowsingContextID),
    731      mInitialSecurityCheckDone(rhs.mInitialSecurityCheckDone),
    732      mIsThirdPartyContext(rhs.mIsThirdPartyContext),
    733      mIsThirdPartyContextToTopWindow(rhs.mIsThirdPartyContextToTopWindow),
    734      mOriginAttributes(rhs.mOriginAttributes),
    735      mRedirectChainIncludingInternalRedirects(
    736          rhs.mRedirectChainIncludingInternalRedirects.Clone()),
    737      mRedirectChain(rhs.mRedirectChain.Clone()),
    738      mAncestorPrincipals(rhs.mAncestorPrincipals.Clone()),
    739      mAncestorBrowsingContextIDs(rhs.mAncestorBrowsingContextIDs.Clone()),
    740      mCorsUnsafeHeaders(rhs.mCorsUnsafeHeaders.Clone()),
    741      mLoadTriggeredFromExternal(rhs.mLoadTriggeredFromExternal),
    742      mCspNonce(rhs.mCspNonce),
    743      mIntegrityMetadata(rhs.mIntegrityMetadata),
    744      mOverriddenFingerprintingSettings(rhs.mOverriddenFingerprintingSettings),
    745 #ifdef DEBUG
    746      mOverriddenFingerprintingSettingsIsSet(
    747          rhs.mOverriddenFingerprintingSettingsIsSet),
    748 #endif
    749      mUnstrippedURI(rhs.mUnstrippedURI),
    750      mInterceptionInfo(rhs.mInterceptionInfo),
    751      mSchemelessInput(rhs.mSchemelessInput),
    752      mUserNavigationInvolvement(rhs.mUserNavigationInvolvement),
    753      mSkipHTTPSUpgrade(rhs.mSkipHTTPSUpgrade) {
    754 }
    755 
    756 LoadInfo::LoadInfo(
    757    nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal,
    758    nsIPrincipal* aPrincipalToInherit, nsIPrincipal* aTopLevelPrincipal,
    759    nsIURI* aResultPrincipalURI, nsICookieJarSettings* aCookieJarSettings,
    760    nsIPolicyContainer* aPolicyContainerToInherit,
    761    const Maybe<dom::FeaturePolicyInfo>& aContainerFeaturePolicyInfo,
    762    const nsACString& aTriggeringRemoteType,
    763    const nsID& aSandboxedNullPrincipalID, const Maybe<ClientInfo>& aClientInfo,
    764    const Maybe<ClientInfo>& aReservedClientInfo,
    765    const Maybe<ClientInfo>& aInitialClientInfo,
    766    const Maybe<ServiceWorkerDescriptor>& aController,
    767    nsSecurityFlags aSecurityFlags, uint32_t aSandboxFlags,
    768    nsContentPolicyType aContentPolicyType, LoadTainting aTainting,
    769 #define DEFINE_PARAMETER(type, name, _n, _d) type a##name,
    770    LOADINFO_FOR_EACH_FIELD(DEFINE_PARAMETER, LOADINFO_DUMMY_SETTER)
    771 #undef DEFINE_PARAMETER
    772 
    773        bool aInitialSecurityCheckDone,
    774    bool aIsThirdPartyContext,
    775    const Maybe<bool>& aIsThirdPartyContextToTopWindow,
    776    const OriginAttributes& aOriginAttributes,
    777    RedirectHistoryArray&& aRedirectChainIncludingInternalRedirects,
    778    RedirectHistoryArray&& aRedirectChain,
    779    nsTArray<nsCOMPtr<nsIPrincipal>>&& aAncestorPrincipals,
    780    const nsTArray<uint64_t>& aAncestorBrowsingContextIDs,
    781    const nsTArray<nsCString>& aCorsUnsafeHeaders,
    782    bool aLoadTriggeredFromExternal, const nsAString& aCspNonce,
    783    const nsAString& aIntegrityMetadata, bool aIsSameDocumentNavigation,
    784    const Maybe<RFPTargetSet>& aOverriddenFingerprintingSettings,
    785    nsINode* aLoadingContext, nsIURI* aUnstrippedURI,
    786    nsIInterceptionInfo* aInterceptionInfo,
    787    nsILoadInfo::SchemelessInputType aSchemelessInput,
    788    dom::UserNavigationInvolvement aUserNavigationInvolvement)
    789    : mLoadingPrincipal(aLoadingPrincipal),
    790      mTriggeringPrincipal(aTriggeringPrincipal),
    791      mPrincipalToInherit(aPrincipalToInherit),
    792      mTopLevelPrincipal(aTopLevelPrincipal),
    793      mResultPrincipalURI(aResultPrincipalURI),
    794      mCookieJarSettings(aCookieJarSettings),
    795      mPolicyContainerToInherit(aPolicyContainerToInherit),
    796      mContainerFeaturePolicyInfo(aContainerFeaturePolicyInfo),
    797      mTriggeringRemoteType(aTriggeringRemoteType),
    798      mSandboxedNullPrincipalID(aSandboxedNullPrincipalID),
    799      mClientInfo(aClientInfo),
    800      mReservedClientInfo(aReservedClientInfo),
    801      mInitialClientInfo(aInitialClientInfo),
    802      mController(aController),
    803      mLoadingContext(do_GetWeakReference(aLoadingContext)),
    804      mSecurityFlags(aSecurityFlags),
    805      mSandboxFlags(aSandboxFlags),
    806      mInternalContentPolicyType(aContentPolicyType),
    807      mTainting(aTainting),
    808 
    809 #define DEFINE_INIT(_t, name, _n, _d) m##name(a##name),
    810      LOADINFO_FOR_EACH_FIELD(DEFINE_INIT, LOADINFO_DUMMY_SETTER)
    811 #undef DEFINE_INIT
    812 
    813          mInitialSecurityCheckDone(aInitialSecurityCheckDone),
    814      mIsThirdPartyContext(aIsThirdPartyContext),
    815      mIsThirdPartyContextToTopWindow(aIsThirdPartyContextToTopWindow),
    816      mOriginAttributes(aOriginAttributes),
    817      mRedirectChainIncludingInternalRedirects(
    818          std::move(aRedirectChainIncludingInternalRedirects)),
    819      mRedirectChain(std::move(aRedirectChain)),
    820      mAncestorPrincipals(std::move(aAncestorPrincipals)),
    821      mAncestorBrowsingContextIDs(aAncestorBrowsingContextIDs.Clone()),
    822      mCorsUnsafeHeaders(aCorsUnsafeHeaders.Clone()),
    823      mLoadTriggeredFromExternal(aLoadTriggeredFromExternal),
    824      mCspNonce(aCspNonce),
    825      mIntegrityMetadata(aIntegrityMetadata),
    826      mIsSameDocumentNavigation(aIsSameDocumentNavigation),
    827      mOverriddenFingerprintingSettings(aOverriddenFingerprintingSettings),
    828      mUnstrippedURI(aUnstrippedURI),
    829      mInterceptionInfo(aInterceptionInfo),
    830      mSchemelessInput(aSchemelessInput),
    831      mUserNavigationInvolvement(aUserNavigationInvolvement) {
    832  // Only top level TYPE_DOCUMENT loads can have a null loadingPrincipal
    833  MOZ_ASSERT(mLoadingPrincipal ||
    834             aContentPolicyType == nsIContentPolicy::TYPE_DOCUMENT);
    835  MOZ_ASSERT(mTriggeringPrincipal);
    836 }
    837 
    838 // static
    839 void LoadInfo::ComputeAncestors(
    840    CanonicalBrowsingContext* aBC,
    841    nsTArray<nsCOMPtr<nsIPrincipal>>& aAncestorPrincipals,
    842    nsTArray<uint64_t>& aBrowsingContextIDs) {
    843  MOZ_ASSERT(aAncestorPrincipals.IsEmpty());
    844  MOZ_ASSERT(aBrowsingContextIDs.IsEmpty());
    845  CanonicalBrowsingContext* ancestorBC = aBC;
    846  // Iterate over ancestor WindowGlobalParents, collecting principals and outer
    847  // window IDs.
    848  while (WindowGlobalParent* ancestorWGP =
    849             ancestorBC->GetParentWindowContext()) {
    850    ancestorBC = ancestorWGP->BrowsingContext();
    851 
    852    nsCOMPtr<nsIPrincipal> parentPrincipal = ancestorWGP->DocumentPrincipal();
    853    MOZ_ASSERT(parentPrincipal, "Ancestor principal is null");
    854    aAncestorPrincipals.AppendElement(parentPrincipal.forget());
    855    aBrowsingContextIDs.AppendElement(ancestorBC->Id());
    856  }
    857 }
    858 
    859 void LoadInfo::ComputeIsThirdPartyContext(nsPIDOMWindowOuter* aOuterWindow) {
    860  ExtContentPolicyType type =
    861      nsContentUtils::InternalContentPolicyTypeToExternal(
    862          mInternalContentPolicyType);
    863  if (type == ExtContentPolicy::TYPE_DOCUMENT) {
    864    // Top-level loads are never third-party.
    865    mIsThirdPartyContext = false;
    866    return;
    867  }
    868 
    869  nsCOMPtr<mozIThirdPartyUtil> util(do_GetService(THIRDPARTYUTIL_CONTRACTID));
    870  if (NS_WARN_IF(!util)) {
    871    return;
    872  }
    873 
    874  util->IsThirdPartyWindow(aOuterWindow, nullptr, &mIsThirdPartyContext);
    875 }
    876 
    877 void LoadInfo::ComputeIsThirdPartyContext(dom::WindowGlobalParent* aGlobal) {
    878  if (nsILoadInfo::GetExternalContentPolicyType() ==
    879      ExtContentPolicy::TYPE_DOCUMENT) {
    880    // Top-level loads are never third-party.
    881    mIsThirdPartyContext = false;
    882    return;
    883  }
    884 
    885  ThirdPartyUtil* thirdPartyUtil = ThirdPartyUtil::GetInstance();
    886  if (!thirdPartyUtil) {
    887    return;
    888  }
    889  thirdPartyUtil->IsThirdPartyGlobal(aGlobal, &mIsThirdPartyContext);
    890 }
    891 
    892 NS_IMPL_ISUPPORTS(LoadInfo, nsILoadInfo)
    893 
    894 LoadInfo::~LoadInfo() { MOZ_RELEASE_ASSERT(NS_IsMainThread()); }
    895 
    896 already_AddRefed<nsILoadInfo> LoadInfo::Clone() const {
    897  RefPtr<LoadInfo> copy(new LoadInfo(*this));
    898  return copy.forget();
    899 }
    900 
    901 already_AddRefed<nsILoadInfo> LoadInfo::CloneWithNewSecFlags(
    902    nsSecurityFlags aSecurityFlags) const {
    903  RefPtr<LoadInfo> copy(new LoadInfo(*this));
    904  copy->mSecurityFlags = aSecurityFlags;
    905  return copy.forget();
    906 }
    907 
    908 already_AddRefed<nsILoadInfo> LoadInfo::CloneForNewRequest() const {
    909  RefPtr<LoadInfo> copy(new LoadInfo(*this));
    910  copy->mInitialSecurityCheckDone = false;
    911  copy->mRedirectChainIncludingInternalRedirects.Clear();
    912  copy->mRedirectChain.Clear();
    913  copy->mResultPrincipalURI = nullptr;
    914  return copy.forget();
    915 }
    916 
    917 NS_IMETHODIMP
    918 LoadInfo::GetLoadingPrincipal(nsIPrincipal** aLoadingPrincipal) {
    919  *aLoadingPrincipal = do_AddRef(mLoadingPrincipal).take();
    920  return NS_OK;
    921 }
    922 
    923 nsIPrincipal* LoadInfo::VirtualGetLoadingPrincipal() {
    924  return mLoadingPrincipal;
    925 }
    926 
    927 NS_IMETHODIMP
    928 LoadInfo::GetTriggeringPrincipal(nsIPrincipal** aTriggeringPrincipal) {
    929  *aTriggeringPrincipal = do_AddRef(mTriggeringPrincipal).take();
    930  return NS_OK;
    931 }
    932 
    933 NS_IMETHODIMP
    934 LoadInfo::SetTriggeringPrincipalForTesting(nsIPrincipal* aTriggeringPrincipal) {
    935  mTriggeringPrincipal = aTriggeringPrincipal;
    936  return NS_OK;
    937 }
    938 
    939 nsIPrincipal* LoadInfo::TriggeringPrincipal() { return mTriggeringPrincipal; }
    940 
    941 NS_IMETHODIMP
    942 LoadInfo::GetPrincipalToInherit(nsIPrincipal** aPrincipalToInherit) {
    943  *aPrincipalToInherit = do_AddRef(mPrincipalToInherit).take();
    944  return NS_OK;
    945 }
    946 
    947 NS_IMETHODIMP
    948 LoadInfo::SetPrincipalToInherit(nsIPrincipal* aPrincipalToInherit) {
    949  MOZ_ASSERT(aPrincipalToInherit, "must be a valid principal to inherit");
    950  mPrincipalToInherit = aPrincipalToInherit;
    951  return NS_OK;
    952 }
    953 
    954 nsIPrincipal* LoadInfo::PrincipalToInherit() { return mPrincipalToInherit; }
    955 
    956 nsIPrincipal* LoadInfo::FindPrincipalToInherit(nsIChannel* aChannel) {
    957  if (mPrincipalToInherit) {
    958    return mPrincipalToInherit;
    959  }
    960 
    961  nsCOMPtr<nsIURI> uri = mResultPrincipalURI;
    962  if (!uri) {
    963    (void)aChannel->GetOriginalURI(getter_AddRefs(uri));
    964  }
    965 
    966  auto* prin = BasePrincipal::Cast(mTriggeringPrincipal);
    967  return prin->PrincipalToInherit(uri);
    968 }
    969 
    970 const nsID& LoadInfo::GetSandboxedNullPrincipalID() {
    971  MOZ_ASSERT(!mSandboxedNullPrincipalID.Equals(nsID{}),
    972             "mSandboxedNullPrincipalID wasn't initialized?");
    973  return mSandboxedNullPrincipalID;
    974 }
    975 
    976 void LoadInfo::ResetSandboxedNullPrincipalID() {
    977  mSandboxedNullPrincipalID = nsID::GenerateUUID();
    978 }
    979 
    980 nsIPrincipal* LoadInfo::GetTopLevelPrincipal() { return mTopLevelPrincipal; }
    981 
    982 NS_IMETHODIMP
    983 LoadInfo::GetTriggeringRemoteType(nsACString& aTriggeringRemoteType) {
    984  aTriggeringRemoteType = mTriggeringRemoteType;
    985  return NS_OK;
    986 }
    987 
    988 NS_IMETHODIMP
    989 LoadInfo::SetTriggeringRemoteType(const nsACString& aTriggeringRemoteType) {
    990  mTriggeringRemoteType = aTriggeringRemoteType;
    991  return NS_OK;
    992 }
    993 
    994 NS_IMETHODIMP
    995 LoadInfo::GetLoadingDocument(Document** aResult) {
    996  if (nsCOMPtr<nsINode> node = do_QueryReferent(mLoadingContext)) {
    997    RefPtr<Document> context = node->OwnerDoc();
    998    context.forget(aResult);
    999  }
   1000  return NS_OK;
   1001 }
   1002 NS_IMETHODIMP
   1003 LoadInfo::GetUserNavigationInvolvement(uint8_t* aUserNavigationInvolvement) {
   1004  *aUserNavigationInvolvement = uint8_t(mUserNavigationInvolvement);
   1005  return NS_OK;
   1006 }
   1007 
   1008 NS_IMETHODIMP
   1009 LoadInfo::SetUserNavigationInvolvement(uint8_t aUserNavigationInvolvement) {
   1010  mUserNavigationInvolvement =
   1011      dom::UserNavigationInvolvement(aUserNavigationInvolvement);
   1012  return NS_OK;
   1013 }
   1014 
   1015 nsINode* LoadInfo::LoadingNode() {
   1016  nsCOMPtr<nsINode> node = do_QueryReferent(mLoadingContext);
   1017  return node;
   1018 }
   1019 
   1020 already_AddRefed<nsISupports> LoadInfo::ContextForTopLevelLoad() {
   1021  // Most likely you want to query LoadingNode() instead of
   1022  // ContextForTopLevelLoad() if this assertion fires.
   1023  MOZ_ASSERT(mInternalContentPolicyType == nsIContentPolicy::TYPE_DOCUMENT,
   1024             "should only query this context for top level document loads");
   1025  nsCOMPtr<nsISupports> context = do_QueryReferent(mContextForTopLevelLoad);
   1026  return context.forget();
   1027 }
   1028 
   1029 already_AddRefed<nsISupports> LoadInfo::GetLoadingContext() {
   1030  nsCOMPtr<nsISupports> context;
   1031  if (mInternalContentPolicyType == nsIContentPolicy::TYPE_DOCUMENT) {
   1032    context = ContextForTopLevelLoad();
   1033  } else {
   1034    context = LoadingNode();
   1035  }
   1036  return context.forget();
   1037 }
   1038 
   1039 NS_IMETHODIMP
   1040 LoadInfo::GetLoadingContextXPCOM(nsISupports** aResult) {
   1041  nsCOMPtr<nsISupports> context = GetLoadingContext();
   1042  context.forget(aResult);
   1043  return NS_OK;
   1044 }
   1045 
   1046 NS_IMETHODIMP
   1047 LoadInfo::GetSecurityFlags(nsSecurityFlags* aResult) {
   1048  *aResult = mSecurityFlags;
   1049  return NS_OK;
   1050 }
   1051 
   1052 NS_IMETHODIMP
   1053 LoadInfo::GetSandboxFlags(uint32_t* aResult) {
   1054  *aResult = mSandboxFlags;
   1055  return NS_OK;
   1056 }
   1057 
   1058 NS_IMETHODIMP
   1059 LoadInfo::GetSecurityMode(uint32_t* aFlags) {
   1060  *aFlags = nsContentSecurityManager::ComputeSecurityMode(mSecurityFlags);
   1061 
   1062  return NS_OK;
   1063 }
   1064 
   1065 NS_IMETHODIMP
   1066 LoadInfo::GetIsInThirdPartyContext(bool* aIsInThirdPartyContext) {
   1067  *aIsInThirdPartyContext = mIsThirdPartyContext;
   1068  return NS_OK;
   1069 }
   1070 
   1071 NS_IMETHODIMP
   1072 LoadInfo::SetIsInThirdPartyContext(bool aIsInThirdPartyContext) {
   1073  mIsThirdPartyContext = aIsInThirdPartyContext;
   1074  return NS_OK;
   1075 }
   1076 
   1077 NS_IMETHODIMP
   1078 LoadInfo::GetIsThirdPartyContextToTopWindow(
   1079    bool* aIsThirdPartyContextToTopWindow) {
   1080  *aIsThirdPartyContextToTopWindow =
   1081      mIsThirdPartyContextToTopWindow.valueOr(true);
   1082  return NS_OK;
   1083 }
   1084 
   1085 NS_IMETHODIMP
   1086 LoadInfo::SetIsThirdPartyContextToTopWindow(
   1087    bool aIsThirdPartyContextToTopWindow) {
   1088  mIsThirdPartyContextToTopWindow = Some(aIsThirdPartyContextToTopWindow);
   1089  return NS_OK;
   1090 }
   1091 
   1092 static const uint32_t sCookiePolicyMask =
   1093    nsILoadInfo::SEC_COOKIES_DEFAULT | nsILoadInfo::SEC_COOKIES_INCLUDE |
   1094    nsILoadInfo::SEC_COOKIES_SAME_ORIGIN | nsILoadInfo::SEC_COOKIES_OMIT;
   1095 
   1096 NS_IMETHODIMP
   1097 LoadInfo::GetCookiePolicy(uint32_t* aResult) {
   1098  uint32_t policy = mSecurityFlags & sCookiePolicyMask;
   1099  if (policy == nsILoadInfo::SEC_COOKIES_DEFAULT) {
   1100    policy = (mSecurityFlags & SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT)
   1101                 ? nsILoadInfo::SEC_COOKIES_SAME_ORIGIN
   1102                 : nsILoadInfo::SEC_COOKIES_INCLUDE;
   1103  }
   1104 
   1105  *aResult = policy;
   1106  return NS_OK;
   1107 }
   1108 
   1109 namespace {
   1110 
   1111 already_AddRefed<nsICookieJarSettings> CreateCookieJarSettings(
   1112    nsIPrincipal* aTriggeringPrincipal, nsContentPolicyType aContentPolicyType,
   1113    bool aIsPrivate, bool aShouldResistFingerprinting) {
   1114  // Special treatment for resources injected by add-ons if not document,
   1115  // iframe, workers.
   1116  if (!nsContentUtils::IsNonSubresourceInternalPolicyType(aContentPolicyType) &&
   1117      aTriggeringPrincipal &&
   1118      StaticPrefs::privacy_antitracking_isolateContentScriptResources() &&
   1119      nsContentUtils::IsExpandedPrincipal(aTriggeringPrincipal)) {
   1120    return CookieJarSettings::Create(
   1121        nsICookieService::BEHAVIOR_REJECT,
   1122        StoragePrincipalHelper::PartitionKeyForExpandedPrincipal(
   1123            aTriggeringPrincipal),
   1124        OriginAttributes::IsFirstPartyEnabled(), false,
   1125        aShouldResistFingerprinting);
   1126  }
   1127 
   1128  if (StaticPrefs::network_cookieJarSettings_unblocked_for_testing()) {
   1129    return aIsPrivate ? CookieJarSettings::Create(CookieJarSettings::ePrivate,
   1130                                                  aShouldResistFingerprinting)
   1131                      : CookieJarSettings::Create(CookieJarSettings::eRegular,
   1132                                                  aShouldResistFingerprinting);
   1133  }
   1134 
   1135  // These contentPolictTypes require a real CookieJarSettings because favicon
   1136  // and save-as requests must send cookies. Anything else should not
   1137  // send/receive cookies.
   1138  if (aContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON ||
   1139      aContentPolicyType == nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD) {
   1140    return aIsPrivate ? CookieJarSettings::Create(CookieJarSettings::ePrivate,
   1141                                                  aShouldResistFingerprinting)
   1142                      : CookieJarSettings::Create(CookieJarSettings::eRegular,
   1143                                                  aShouldResistFingerprinting);
   1144  }
   1145 
   1146  return CookieJarSettings::GetBlockingAll(aShouldResistFingerprinting);
   1147 }
   1148 
   1149 }  // namespace
   1150 
   1151 NS_IMETHODIMP
   1152 LoadInfo::GetCookieJarSettings(nsICookieJarSettings** aCookieJarSettings) {
   1153  if (!mCookieJarSettings) {
   1154    bool isPrivate = mOriginAttributes.IsPrivateBrowsing();
   1155    nsCOMPtr<nsIPrincipal> loadingPrincipal;
   1156    (void)this->GetLoadingPrincipal(getter_AddRefs(loadingPrincipal));
   1157    bool shouldResistFingerprinting =
   1158        nsContentUtils::ShouldResistFingerprinting_dangerous(
   1159            loadingPrincipal,
   1160            "CookieJarSettings can't exist yet, we're creating it",
   1161            RFPTarget::IsAlwaysEnabledForPrecompute);
   1162    mCookieJarSettings = CreateCookieJarSettings(
   1163        mTriggeringPrincipal, mInternalContentPolicyType, isPrivate,
   1164        shouldResistFingerprinting);
   1165  }
   1166 
   1167  nsCOMPtr<nsICookieJarSettings> cookieJarSettings = mCookieJarSettings;
   1168  cookieJarSettings.forget(aCookieJarSettings);
   1169  return NS_OK;
   1170 }
   1171 
   1172 NS_IMETHODIMP
   1173 LoadInfo::SetCookieJarSettings(nsICookieJarSettings* aCookieJarSettings) {
   1174  MOZ_ASSERT(aCookieJarSettings);
   1175  // We allow the overwrite of CookieJarSettings.
   1176  mCookieJarSettings = aCookieJarSettings;
   1177  return NS_OK;
   1178 }
   1179 
   1180 const Maybe<RFPTargetSet>& LoadInfo::GetOverriddenFingerprintingSettings() {
   1181 #ifdef DEBUG
   1182  RefPtr<BrowsingContext> browsingContext;
   1183  GetTargetBrowsingContext(getter_AddRefs(browsingContext));
   1184 
   1185  // Exclude this check if the target browsing context is for the parent
   1186  // process.
   1187  MOZ_ASSERT_IF(XRE_IsParentProcess() && browsingContext &&
   1188                    !browsingContext->IsInProcess(),
   1189                mOverriddenFingerprintingSettingsIsSet);
   1190 #endif
   1191  return mOverriddenFingerprintingSettings;
   1192 }
   1193 
   1194 void LoadInfo::SetOverriddenFingerprintingSettings(RFPTargetSet aTargets) {
   1195  mOverriddenFingerprintingSettings.reset();
   1196  mOverriddenFingerprintingSettings.emplace(aTargets);
   1197 }
   1198 
   1199 void LoadInfo::SetIncludeCookiesSecFlag() {
   1200  MOZ_ASSERT((mSecurityFlags & sCookiePolicyMask) ==
   1201             nsILoadInfo::SEC_COOKIES_DEFAULT);
   1202  mSecurityFlags =
   1203      (mSecurityFlags & ~sCookiePolicyMask) | nsILoadInfo::SEC_COOKIES_INCLUDE;
   1204 }
   1205 
   1206 NS_IMETHODIMP
   1207 LoadInfo::GetForceInheritPrincipal(bool* aInheritPrincipal) {
   1208  *aInheritPrincipal =
   1209      (mSecurityFlags & nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL);
   1210  return NS_OK;
   1211 }
   1212 
   1213 NS_IMETHODIMP
   1214 LoadInfo::GetForceInheritPrincipalOverruleOwner(bool* aInheritPrincipal) {
   1215  *aInheritPrincipal =
   1216      (mSecurityFlags &
   1217       nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL_OVERRULE_OWNER);
   1218  return NS_OK;
   1219 }
   1220 
   1221 NS_IMETHODIMP
   1222 LoadInfo::GetLoadingSandboxed(bool* aLoadingSandboxed) {
   1223  *aLoadingSandboxed = (mSandboxFlags & SANDBOXED_ORIGIN);
   1224  return NS_OK;
   1225 }
   1226 
   1227 NS_IMETHODIMP
   1228 LoadInfo::GetAboutBlankInherits(bool* aResult) {
   1229  *aResult = (mSecurityFlags & nsILoadInfo::SEC_ABOUT_BLANK_INHERITS);
   1230  return NS_OK;
   1231 }
   1232 
   1233 NS_IMETHODIMP
   1234 LoadInfo::GetAllowChrome(bool* aResult) {
   1235  *aResult = (mSecurityFlags & nsILoadInfo::SEC_ALLOW_CHROME);
   1236  return NS_OK;
   1237 }
   1238 
   1239 NS_IMETHODIMP
   1240 LoadInfo::GetDisallowScript(bool* aResult) {
   1241  *aResult = (mSecurityFlags & nsILoadInfo::SEC_DISALLOW_SCRIPT);
   1242  return NS_OK;
   1243 }
   1244 
   1245 NS_IMETHODIMP
   1246 LoadInfo::GetDontFollowRedirects(bool* aResult) {
   1247  *aResult = (mSecurityFlags & nsILoadInfo::SEC_DONT_FOLLOW_REDIRECTS);
   1248  return NS_OK;
   1249 }
   1250 
   1251 NS_IMETHODIMP
   1252 LoadInfo::GetLoadErrorPage(bool* aResult) {
   1253  *aResult = (mSecurityFlags & nsILoadInfo::SEC_LOAD_ERROR_PAGE);
   1254  return NS_OK;
   1255 }
   1256 
   1257 NS_IMETHODIMP
   1258 LoadInfo::GetExternalContentPolicyType(nsContentPolicyType* aResult) {
   1259  // We have to use nsContentPolicyType because ExtContentPolicyType is not
   1260  // visible from xpidl.
   1261  *aResult = static_cast<nsContentPolicyType>(
   1262      nsContentUtils::InternalContentPolicyTypeToExternal(
   1263          mInternalContentPolicyType));
   1264  return NS_OK;
   1265 }
   1266 
   1267 nsContentPolicyType LoadInfo::InternalContentPolicyType() {
   1268  return mInternalContentPolicyType;
   1269 }
   1270 
   1271 #define DEFINE_GETTER(type, name, _n, _d)            \
   1272  NS_IMETHODIMP LoadInfo::Get##name(type* a##name) { \
   1273    *a##name = m##name;                              \
   1274    return NS_OK;                                    \
   1275  }
   1276 
   1277 #define DEFINE_SETTER(type, name)                   \
   1278  NS_IMETHODIMP LoadInfo::Set##name(type a##name) { \
   1279    m##name = a##name;                              \
   1280    return NS_OK;                                   \
   1281  }
   1282 
   1283 LOADINFO_FOR_EACH_FIELD(DEFINE_GETTER, DEFINE_SETTER);
   1284 
   1285 #undef DEFINE_GETTER
   1286 #undef DEFINE_SETTER
   1287 
   1288 NS_IMETHODIMP
   1289 LoadInfo::GetWorkerAssociatedBrowsingContextID(uint64_t* aResult) {
   1290  *aResult = mWorkerAssociatedBrowsingContextID;
   1291  return NS_OK;
   1292 }
   1293 
   1294 NS_IMETHODIMP
   1295 LoadInfo::SetWorkerAssociatedBrowsingContextID(uint64_t aID) {
   1296  mWorkerAssociatedBrowsingContextID = aID;
   1297  return NS_OK;
   1298 }
   1299 
   1300 NS_IMETHODIMP
   1301 LoadInfo::GetTargetBrowsingContextID(uint64_t* aResult) {
   1302  return (nsILoadInfo::GetExternalContentPolicyType() ==
   1303          ExtContentPolicy::TYPE_SUBDOCUMENT)
   1304             ? GetFrameBrowsingContextID(aResult)
   1305             : GetBrowsingContextID(aResult);
   1306 }
   1307 
   1308 NS_IMETHODIMP
   1309 LoadInfo::GetBrowsingContext(dom::BrowsingContext** aResult) {
   1310  *aResult = BrowsingContext::Get(mBrowsingContextID).take();
   1311  return NS_OK;
   1312 }
   1313 
   1314 NS_IMETHODIMP
   1315 LoadInfo::GetWorkerAssociatedBrowsingContext(dom::BrowsingContext** aResult) {
   1316  *aResult = BrowsingContext::Get(mWorkerAssociatedBrowsingContextID).take();
   1317  return NS_OK;
   1318 }
   1319 
   1320 NS_IMETHODIMP
   1321 LoadInfo::GetFrameBrowsingContext(dom::BrowsingContext** aResult) {
   1322  *aResult = BrowsingContext::Get(mFrameBrowsingContextID).take();
   1323  return NS_OK;
   1324 }
   1325 
   1326 NS_IMETHODIMP
   1327 LoadInfo::GetTargetBrowsingContext(dom::BrowsingContext** aResult) {
   1328  uint64_t targetBrowsingContextID = 0;
   1329  MOZ_ALWAYS_SUCCEEDS(GetTargetBrowsingContextID(&targetBrowsingContextID));
   1330  *aResult = BrowsingContext::Get(targetBrowsingContextID).take();
   1331  return NS_OK;
   1332 }
   1333 
   1334 NS_IMETHODIMP
   1335 LoadInfo::GetScriptableOriginAttributes(
   1336    JSContext* aCx, JS::MutableHandle<JS::Value> aOriginAttributes) {
   1337  if (NS_WARN_IF(!ToJSValue(aCx, mOriginAttributes, aOriginAttributes))) {
   1338    return NS_ERROR_FAILURE;
   1339  }
   1340  return NS_OK;
   1341 }
   1342 
   1343 NS_IMETHODIMP
   1344 LoadInfo::ResetPrincipalToInheritToNullPrincipal() {
   1345  // take the originAttributes from the LoadInfo and create
   1346  // a new NullPrincipal using those origin attributes.
   1347  nsCOMPtr<nsIPrincipal> newNullPrincipal =
   1348      NullPrincipal::Create(mOriginAttributes);
   1349 
   1350  mPrincipalToInherit = newNullPrincipal;
   1351 
   1352  // setting SEC_FORCE_INHERIT_PRINCIPAL_OVERRULE_OWNER will overrule
   1353  // any non null owner set on the channel and will return the principal
   1354  // form the loadinfo instead.
   1355  mSecurityFlags |= SEC_FORCE_INHERIT_PRINCIPAL_OVERRULE_OWNER;
   1356 
   1357  return NS_OK;
   1358 }
   1359 
   1360 NS_IMETHODIMP
   1361 LoadInfo::SetScriptableOriginAttributes(
   1362    JSContext* aCx, JS::Handle<JS::Value> aOriginAttributes) {
   1363  OriginAttributes attrs;
   1364  if (!aOriginAttributes.isObject() || !attrs.Init(aCx, aOriginAttributes)) {
   1365    return NS_ERROR_INVALID_ARG;
   1366  }
   1367 
   1368  mOriginAttributes = attrs;
   1369  return NS_OK;
   1370 }
   1371 
   1372 nsresult LoadInfo::GetOriginAttributes(
   1373    mozilla::OriginAttributes* aOriginAttributes) {
   1374  NS_ENSURE_ARG(aOriginAttributes);
   1375  *aOriginAttributes = mOriginAttributes;
   1376  return NS_OK;
   1377 }
   1378 
   1379 nsresult LoadInfo::SetOriginAttributes(
   1380    const mozilla::OriginAttributes& aOriginAttributes) {
   1381  mOriginAttributes = aOriginAttributes;
   1382  return NS_OK;
   1383 }
   1384 
   1385 NS_IMETHODIMP
   1386 LoadInfo::SetInitialSecurityCheckDone(bool aInitialSecurityCheckDone) {
   1387  // Indicates whether the channel was ever evaluated by the
   1388  // ContentSecurityManager. Once set to true, this flag must
   1389  // remain true throughout the lifetime of the channel.
   1390  // Setting it to anything else than true will be discarded.
   1391  MOZ_ASSERT(aInitialSecurityCheckDone,
   1392             "aInitialSecurityCheckDone must be true");
   1393  mInitialSecurityCheckDone =
   1394      mInitialSecurityCheckDone || aInitialSecurityCheckDone;
   1395  return NS_OK;
   1396 }
   1397 
   1398 NS_IMETHODIMP
   1399 LoadInfo::GetInitialSecurityCheckDone(bool* aResult) {
   1400  *aResult = mInitialSecurityCheckDone;
   1401  return NS_OK;
   1402 }
   1403 
   1404 // To prevent unintenional credential and information leaks in content
   1405 // processes we can use this function to truncate a Principal's URI as much as
   1406 // possible.
   1407 already_AddRefed<nsIPrincipal> CreateTruncatedPrincipal(
   1408    nsIPrincipal* aPrincipal) {
   1409  nsCOMPtr<nsIPrincipal> truncatedPrincipal;
   1410  // System Principal URIs don't need to be truncated as they don't contain any
   1411  // sensitive browsing history information.
   1412  if (aPrincipal->IsSystemPrincipal()) {
   1413    truncatedPrincipal = aPrincipal;
   1414    return truncatedPrincipal.forget();
   1415  }
   1416 
   1417  // Content Principal URIs are the main location of the information we need to
   1418  // truncate.
   1419  if (aPrincipal->GetIsContentPrincipal()) {
   1420    // Certain URIs (chrome, resource, about, jar) don't need to be truncated
   1421    // as they should be free of any sensitive user browsing history.
   1422    if (aPrincipal->SchemeIs("chrome") || aPrincipal->SchemeIs("resource") ||
   1423        aPrincipal->SchemeIs("about") || aPrincipal->SchemeIs("jar")) {
   1424      truncatedPrincipal = aPrincipal;
   1425      return truncatedPrincipal.forget();
   1426    }
   1427 
   1428    // Different parts of the URI are preserved due to being vital to the
   1429    // browser's operation.
   1430    // Scheme for differentiating between different types of URIs and how to
   1431    // truncate them and later on utilize them.
   1432    // Host and Port to retain the redirect chain's core functionality.
   1433    // Path would ideally be removed but needs to be retained to ensure that
   1434    // http/https redirect loops can be detected.
   1435    // The entirety of the Query String, Reference Fragment, and User Info
   1436    // subcomponents must be stripped to avoid leaking Oauth tokens, user
   1437    // identifiers, and similar bits of information that these subcomponents may
   1438    // contain.
   1439    nsAutoCString scheme;
   1440    nsAutoCString separator("://");
   1441    nsAutoCString hostPort;
   1442    nsAutoCString path;
   1443    nsAutoCString uriString("");
   1444    if (aPrincipal->SchemeIs("view-source")) {
   1445      // The path portion of the view-source URI will be the URI whose source is
   1446      // being viewed, so we create a new URI object with a truncated form of
   1447      // the path and append the view-source scheme to the front again.
   1448      nsAutoCString viewSourcePath;
   1449      aPrincipal->GetFilePath(viewSourcePath);
   1450 
   1451      nsCOMPtr<nsIURI> nestedURI;
   1452      nsresult rv = NS_NewURI(getter_AddRefs(nestedURI), viewSourcePath);
   1453 
   1454      if (NS_FAILED(rv)) {
   1455        // Since the path here should be an already validated URI this should
   1456        // never happen.
   1457        NS_WARNING(viewSourcePath.get());
   1458        MOZ_ASSERT(false,
   1459                   "Failed to create truncated form of URI with NS_NewURI.");
   1460        truncatedPrincipal = aPrincipal;
   1461        return truncatedPrincipal.forget();
   1462      }
   1463 
   1464      nestedURI->GetScheme(scheme);
   1465      nestedURI->GetHostPort(hostPort);
   1466      nestedURI->GetFilePath(path);
   1467      uriString += "view-source:";
   1468    } else {
   1469      aPrincipal->GetScheme(scheme);
   1470      aPrincipal->GetHostPort(hostPort);
   1471      aPrincipal->GetFilePath(path);
   1472    }
   1473    uriString += scheme + separator + hostPort + path;
   1474 
   1475    nsCOMPtr<nsIURI> truncatedURI;
   1476    nsresult rv = NS_NewURI(getter_AddRefs(truncatedURI), uriString);
   1477    if (NS_FAILED(rv)) {
   1478      NS_WARNING(uriString.get());
   1479      MOZ_ASSERT(false,
   1480                 "Failed to create truncated form of URI with NS_NewURI.");
   1481      truncatedPrincipal = aPrincipal;
   1482      return truncatedPrincipal.forget();
   1483    }
   1484 
   1485    return BasePrincipal::CreateContentPrincipal(
   1486        truncatedURI, aPrincipal->OriginAttributesRef());
   1487  }
   1488 
   1489  // Null Principal Precursor URIs can also contain information that needs to
   1490  // be truncated.
   1491  if (aPrincipal->GetIsNullPrincipal()) {
   1492    nsCOMPtr<nsIPrincipal> precursorPrincipal =
   1493        aPrincipal->GetPrecursorPrincipal();
   1494    // If there is no precursor then nothing needs to be truncated.
   1495    if (!precursorPrincipal) {
   1496      truncatedPrincipal = aPrincipal;
   1497      return truncatedPrincipal.forget();
   1498    }
   1499 
   1500    // Otherwise we return a new Null Principal with the original's Origin
   1501    // Attributes and a truncated version of the original's precursor URI.
   1502    nsCOMPtr<nsIPrincipal> truncatedPrecursor =
   1503        CreateTruncatedPrincipal(precursorPrincipal);
   1504    return NullPrincipal::CreateWithInheritedAttributes(truncatedPrecursor);
   1505  }
   1506 
   1507  // Expanded Principals shouldn't contain sensitive information but their
   1508  // allowlists might so we truncate that information here.
   1509  if (aPrincipal->GetIsExpandedPrincipal()) {
   1510    nsTArray<nsCOMPtr<nsIPrincipal>> truncatedAllowList;
   1511 
   1512    for (const auto& allowedPrincipal : BasePrincipal::Cast(aPrincipal)
   1513                                            ->As<ExpandedPrincipal>()
   1514                                            ->AllowList()) {
   1515      nsCOMPtr<nsIPrincipal> truncatedPrincipal =
   1516          CreateTruncatedPrincipal(allowedPrincipal);
   1517 
   1518      truncatedAllowList.AppendElement(truncatedPrincipal);
   1519    }
   1520 
   1521    return ExpandedPrincipal::Create(truncatedAllowList,
   1522                                     aPrincipal->OriginAttributesRef());
   1523  }
   1524 
   1525  // If we hit this assertion we need to update this function to add the
   1526  // Principals and URIs seen as new corner cases to handle.
   1527  MOZ_ASSERT(false, "Unhandled Principal or URI type encountered.");
   1528 
   1529  truncatedPrincipal = aPrincipal;
   1530  return truncatedPrincipal.forget();
   1531 }
   1532 
   1533 NS_IMETHODIMP
   1534 LoadInfo::AppendRedirectHistoryEntry(nsIChannel* aChannel,
   1535                                     bool aIsInternalRedirect) {
   1536  NS_ENSURE_ARG(aChannel);
   1537  MOZ_ASSERT(NS_IsMainThread());
   1538 
   1539  nsCOMPtr<nsIPrincipal> uriPrincipal;
   1540  nsIScriptSecurityManager* sm = nsContentUtils::GetSecurityManager();
   1541  sm->GetChannelURIPrincipal(aChannel, getter_AddRefs(uriPrincipal));
   1542 
   1543  nsCOMPtr<nsIURI> referrer;
   1544  nsCString remoteAddress;
   1545 
   1546  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aChannel));
   1547  if (httpChannel) {
   1548    nsCOMPtr<nsIReferrerInfo> referrerInfo;
   1549    (void)httpChannel->GetReferrerInfo(getter_AddRefs(referrerInfo));
   1550    if (referrerInfo) {
   1551      referrer = referrerInfo->GetComputedReferrer();
   1552    }
   1553 
   1554    nsCOMPtr<nsIHttpChannelInternal> intChannel(do_QueryInterface(aChannel));
   1555    if (intChannel) {
   1556      (void)intChannel->GetRemoteAddress(remoteAddress);
   1557    }
   1558  }
   1559 
   1560  nsCOMPtr<nsIPrincipal> truncatedPrincipal =
   1561      CreateTruncatedPrincipal(uriPrincipal);
   1562 
   1563  nsCOMPtr<nsIRedirectHistoryEntry> entry =
   1564      new nsRedirectHistoryEntry(truncatedPrincipal, referrer, remoteAddress);
   1565 
   1566  mRedirectChainIncludingInternalRedirects.AppendElement(entry);
   1567  if (!aIsInternalRedirect) {
   1568    mRedirectChain.AppendElement(entry);
   1569  }
   1570  return NS_OK;
   1571 }
   1572 
   1573 NS_IMETHODIMP
   1574 LoadInfo::GetRedirects(JSContext* aCx, JS::MutableHandle<JS::Value> aRedirects,
   1575                       const RedirectHistoryArray& aArray) {
   1576  JS::Rooted<JSObject*> redirects(aCx,
   1577                                  JS::NewArrayObject(aCx, aArray.Length()));
   1578  NS_ENSURE_TRUE(redirects, NS_ERROR_OUT_OF_MEMORY);
   1579 
   1580  JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
   1581  NS_ENSURE_TRUE(global, NS_ERROR_UNEXPECTED);
   1582 
   1583  nsCOMPtr<nsIXPConnect> xpc = nsIXPConnect::XPConnect();
   1584 
   1585  for (size_t idx = 0; idx < aArray.Length(); idx++) {
   1586    JS::Rooted<JSObject*> jsobj(aCx);
   1587    nsresult rv =
   1588        xpc->WrapNative(aCx, global, aArray[idx],
   1589                        NS_GET_IID(nsIRedirectHistoryEntry), jsobj.address());
   1590    NS_ENSURE_SUCCESS(rv, rv);
   1591    NS_ENSURE_STATE(jsobj);
   1592 
   1593    bool rc = JS_DefineElement(aCx, redirects, idx, jsobj, JSPROP_ENUMERATE);
   1594    NS_ENSURE_TRUE(rc, NS_ERROR_UNEXPECTED);
   1595  }
   1596 
   1597  aRedirects.setObject(*redirects);
   1598  return NS_OK;
   1599 }
   1600 
   1601 NS_IMETHODIMP
   1602 LoadInfo::GetRedirectChainIncludingInternalRedirects(
   1603    JSContext* aCx, JS::MutableHandle<JS::Value> aChain) {
   1604  return GetRedirects(aCx, aChain, mRedirectChainIncludingInternalRedirects);
   1605 }
   1606 
   1607 const RedirectHistoryArray&
   1608 LoadInfo::RedirectChainIncludingInternalRedirects() {
   1609  return mRedirectChainIncludingInternalRedirects;
   1610 }
   1611 
   1612 NS_IMETHODIMP
   1613 LoadInfo::GetRedirectChain(JSContext* aCx,
   1614                           JS::MutableHandle<JS::Value> aChain) {
   1615  return GetRedirects(aCx, aChain, mRedirectChain);
   1616 }
   1617 
   1618 const RedirectHistoryArray& LoadInfo::RedirectChain() { return mRedirectChain; }
   1619 
   1620 const nsTArray<nsCOMPtr<nsIPrincipal>>& LoadInfo::AncestorPrincipals() {
   1621  return mAncestorPrincipals;
   1622 }
   1623 
   1624 const nsTArray<uint64_t>& LoadInfo::AncestorBrowsingContextIDs() {
   1625  return mAncestorBrowsingContextIDs;
   1626 }
   1627 
   1628 void LoadInfo::SetCorsPreflightInfo(const nsTArray<nsCString>& aHeaders,
   1629                                    bool aForcePreflight) {
   1630  MOZ_ASSERT(GetSecurityMode() ==
   1631             nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT);
   1632  MOZ_ASSERT(!mInitialSecurityCheckDone);
   1633  mCorsUnsafeHeaders = aHeaders.Clone();
   1634  mForcePreflight = aForcePreflight;
   1635 }
   1636 
   1637 const nsTArray<nsCString>& LoadInfo::CorsUnsafeHeaders() {
   1638  return mCorsUnsafeHeaders;
   1639 }
   1640 
   1641 void LoadInfo::SetIsPreflight() {
   1642  MOZ_ASSERT(GetSecurityMode() ==
   1643             nsILoadInfo::SEC_REQUIRE_CORS_INHERITS_SEC_CONTEXT);
   1644  MOZ_ASSERT(!mInitialSecurityCheckDone);
   1645  mIsPreflight = true;
   1646 }
   1647 
   1648 void LoadInfo::SetUpgradeInsecureRequests(bool aValue) {
   1649  mUpgradeInsecureRequests = aValue;
   1650 }
   1651 
   1652 void LoadInfo::SetBrowserUpgradeInsecureRequests() {
   1653  mBrowserUpgradeInsecureRequests = true;
   1654 }
   1655 
   1656 void LoadInfo::SetBrowserWouldUpgradeInsecureRequests() {
   1657  mBrowserWouldUpgradeInsecureRequests = true;
   1658 }
   1659 
   1660 NS_IMETHODIMP
   1661 LoadInfo::SetLoadTriggeredFromExternal(bool aLoadTriggeredFromExternal) {
   1662  MOZ_ASSERT(!aLoadTriggeredFromExternal ||
   1663                 mInternalContentPolicyType == nsIContentPolicy::TYPE_DOCUMENT,
   1664             "can only set load triggered from external for TYPE_DOCUMENT");
   1665  mLoadTriggeredFromExternal = aLoadTriggeredFromExternal;
   1666  return NS_OK;
   1667 }
   1668 
   1669 NS_IMETHODIMP
   1670 LoadInfo::GetLoadTriggeredFromExternal(bool* aLoadTriggeredFromExternal) {
   1671  *aLoadTriggeredFromExternal = mLoadTriggeredFromExternal;
   1672  return NS_OK;
   1673 }
   1674 
   1675 NS_IMETHODIMP
   1676 LoadInfo::GetTainting(uint32_t* aTaintingOut) {
   1677  MOZ_ASSERT(aTaintingOut);
   1678  *aTaintingOut = static_cast<uint32_t>(mTainting);
   1679  return NS_OK;
   1680 }
   1681 
   1682 NS_IMETHODIMP
   1683 LoadInfo::MaybeIncreaseTainting(uint32_t aTainting) {
   1684  NS_ENSURE_ARG(aTainting <= TAINTING_OPAQUE);
   1685 
   1686  // Skip if the tainting has been set by the service worker.
   1687  if (mServiceWorkerTaintingSynthesized) {
   1688    return NS_OK;
   1689  }
   1690 
   1691  LoadTainting tainting = static_cast<LoadTainting>(aTainting);
   1692  if (tainting > mTainting) {
   1693    mTainting = tainting;
   1694  }
   1695  return NS_OK;
   1696 }
   1697 
   1698 void LoadInfo::SynthesizeServiceWorkerTainting(LoadTainting aTainting) {
   1699  MOZ_DIAGNOSTIC_ASSERT(aTainting <= LoadTainting::Opaque);
   1700  mTainting = aTainting;
   1701 
   1702  // Flag to prevent the tainting from being increased.
   1703  mServiceWorkerTaintingSynthesized = true;
   1704 }
   1705 
   1706 NS_IMETHODIMP
   1707 LoadInfo::GetCspNonce(nsAString& aCspNonce) {
   1708  aCspNonce = mCspNonce;
   1709  return NS_OK;
   1710 }
   1711 
   1712 NS_IMETHODIMP
   1713 LoadInfo::SetCspNonce(const nsAString& aCspNonce) {
   1714  MOZ_ASSERT(!mInitialSecurityCheckDone,
   1715             "setting the nonce is only allowed before any sec checks");
   1716  mCspNonce = aCspNonce;
   1717  return NS_OK;
   1718 }
   1719 
   1720 NS_IMETHODIMP
   1721 LoadInfo::GetIntegrityMetadata(nsAString& aIntegrityMetadata) {
   1722  aIntegrityMetadata = mIntegrityMetadata;
   1723  return NS_OK;
   1724 }
   1725 
   1726 NS_IMETHODIMP
   1727 LoadInfo::SetIntegrityMetadata(const nsAString& aIntegrityMetadata) {
   1728  MOZ_ASSERT(!mInitialSecurityCheckDone,
   1729             "setting the nonce is only allowed before any sec checks");
   1730  mIntegrityMetadata = aIntegrityMetadata;
   1731  return NS_OK;
   1732 }
   1733 
   1734 NS_IMETHODIMP
   1735 LoadInfo::GetIsSameDocumentNavigation(bool* aIsSameDocumentNavigation) {
   1736  *aIsSameDocumentNavigation = mIsSameDocumentNavigation;
   1737  return NS_OK;
   1738 }
   1739 
   1740 NS_IMETHODIMP
   1741 LoadInfo::SetIsSameDocumentNavigation(bool aIsSameDocumentNavigation) {
   1742  mIsSameDocumentNavigation = aIsSameDocumentNavigation;
   1743  return NS_OK;
   1744 }
   1745 
   1746 NS_IMETHODIMP
   1747 LoadInfo::GetIsUserTriggeredSave(bool* aIsUserTriggeredSave) {
   1748  *aIsUserTriggeredSave =
   1749      mIsUserTriggeredSave ||
   1750      mInternalContentPolicyType == nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD;
   1751  return NS_OK;
   1752 }
   1753 
   1754 NS_IMETHODIMP
   1755 LoadInfo::SetIsUserTriggeredSave(bool aIsUserTriggeredSave) {
   1756  mIsUserTriggeredSave = aIsUserTriggeredSave;
   1757  return NS_OK;
   1758 }
   1759 
   1760 NS_IMETHODIMP
   1761 LoadInfo::GetIsTopLevelLoad(bool* aResult) {
   1762  RefPtr<dom::BrowsingContext> bc;
   1763  GetTargetBrowsingContext(getter_AddRefs(bc));
   1764  *aResult = !bc || bc->IsTop();
   1765  return NS_OK;
   1766 }
   1767 
   1768 void LoadInfo::SetIsFromProcessingFrameAttributes() {
   1769  mIsFromProcessingFrameAttributes = true;
   1770 }
   1771 
   1772 dom::ReferrerPolicy LoadInfo::GetFrameReferrerPolicySnapshot() const {
   1773  return mFrameReferrerPolicySnapshot;
   1774 }
   1775 
   1776 void LoadInfo::SetFrameReferrerPolicySnapshot(dom::ReferrerPolicy aPolicy) {
   1777  mFrameReferrerPolicySnapshot = aPolicy;
   1778 }
   1779 
   1780 NS_IMETHODIMP
   1781 LoadInfo::GetResultPrincipalURI(nsIURI** aURI) {
   1782  *aURI = do_AddRef(mResultPrincipalURI).take();
   1783  return NS_OK;
   1784 }
   1785 
   1786 NS_IMETHODIMP
   1787 LoadInfo::SetResultPrincipalURI(nsIURI* aURI) {
   1788  mResultPrincipalURI = aURI;
   1789  return NS_OK;
   1790 }
   1791 
   1792 NS_IMETHODIMP
   1793 LoadInfo::GetChannelCreationOriginalURI(nsIURI** aURI) {
   1794  *aURI = do_AddRef(mChannelCreationOriginalURI).take();
   1795  return NS_OK;
   1796 }
   1797 
   1798 NS_IMETHODIMP
   1799 LoadInfo::SetChannelCreationOriginalURI(nsIURI* aURI) {
   1800  mChannelCreationOriginalURI = aURI;
   1801  return NS_OK;
   1802 }
   1803 
   1804 NS_IMETHODIMP
   1805 LoadInfo::GetUnstrippedURI(nsIURI** aURI) {
   1806  *aURI = do_AddRef(mUnstrippedURI).take();
   1807  return NS_OK;
   1808 }
   1809 
   1810 NS_IMETHODIMP
   1811 LoadInfo::SetUnstrippedURI(nsIURI* aURI) {
   1812  mUnstrippedURI = aURI;
   1813  return NS_OK;
   1814 }
   1815 
   1816 void LoadInfo::SetClientInfo(const ClientInfo& aClientInfo) {
   1817  mClientInfo.emplace(aClientInfo);
   1818 }
   1819 
   1820 const Maybe<ClientInfo>& LoadInfo::GetClientInfo() { return mClientInfo; }
   1821 
   1822 void LoadInfo::GiveReservedClientSource(
   1823    UniquePtr<ClientSource>&& aClientSource) {
   1824  MOZ_DIAGNOSTIC_ASSERT(aClientSource);
   1825  mReservedClientSource = std::move(aClientSource);
   1826  SetReservedClientInfo(mReservedClientSource->Info());
   1827 }
   1828 
   1829 UniquePtr<ClientSource> LoadInfo::TakeReservedClientSource() {
   1830  if (mReservedClientSource) {
   1831    // If the reserved ClientInfo was set due to a ClientSource being present,
   1832    // then clear that info object when the ClientSource is taken.
   1833    mReservedClientInfo.reset();
   1834  }
   1835  return std::move(mReservedClientSource);
   1836 }
   1837 
   1838 void LoadInfo::SetReservedClientInfo(const ClientInfo& aClientInfo) {
   1839  MOZ_DIAGNOSTIC_ASSERT(mInitialClientInfo.isNothing());
   1840  // Treat assignments of the same value as a no-op.  The emplace below
   1841  // will normally assert when overwriting an existing value.
   1842  if (mReservedClientInfo.isSome()) {
   1843    if (mReservedClientInfo.ref() == aClientInfo) {
   1844      return;
   1845    }
   1846    MOZ_DIAGNOSTIC_CRASH("mReservedClientInfo already set");
   1847    mReservedClientInfo.reset();
   1848  }
   1849  mReservedClientInfo.emplace(aClientInfo);
   1850 }
   1851 
   1852 void LoadInfo::OverrideReservedClientInfoInParent(
   1853    const ClientInfo& aClientInfo) {
   1854  // This should only be called to handle redirects in the parent process.
   1855  MOZ_ASSERT(XRE_GetProcessType() == GeckoProcessType_Default);
   1856 
   1857  mInitialClientInfo.reset();
   1858  mReservedClientInfo.reset();
   1859  mReservedClientInfo.emplace(aClientInfo);
   1860 }
   1861 
   1862 const Maybe<ClientInfo>& LoadInfo::GetReservedClientInfo() {
   1863  return mReservedClientInfo;
   1864 }
   1865 
   1866 void LoadInfo::SetInitialClientInfo(const ClientInfo& aClientInfo) {
   1867  MOZ_DIAGNOSTIC_ASSERT(!mReservedClientSource);
   1868  MOZ_DIAGNOSTIC_ASSERT(mReservedClientInfo.isNothing());
   1869  // Treat assignments of the same value as a no-op.  The emplace below
   1870  // will normally assert when overwriting an existing value.
   1871  if (mInitialClientInfo.isSome() && mInitialClientInfo.ref() == aClientInfo) {
   1872    return;
   1873  }
   1874  mInitialClientInfo.emplace(aClientInfo);
   1875 }
   1876 
   1877 const Maybe<ClientInfo>& LoadInfo::GetInitialClientInfo() {
   1878  return mInitialClientInfo;
   1879 }
   1880 
   1881 void LoadInfo::SetController(const ServiceWorkerDescriptor& aServiceWorker) {
   1882  mController.emplace(aServiceWorker);
   1883 }
   1884 
   1885 void LoadInfo::ClearController() { mController.reset(); }
   1886 
   1887 const Maybe<ServiceWorkerDescriptor>& LoadInfo::GetController() {
   1888  return mController;
   1889 }
   1890 
   1891 void LoadInfo::SetPerformanceStorage(PerformanceStorage* aPerformanceStorage) {
   1892  mPerformanceStorage = aPerformanceStorage;
   1893 }
   1894 
   1895 PerformanceStorage* LoadInfo::GetPerformanceStorage() {
   1896  if (mPerformanceStorage) {
   1897    return mPerformanceStorage;
   1898  }
   1899 
   1900  auto* innerWindow = nsGlobalWindowInner::GetInnerWindowWithId(mInnerWindowID);
   1901  if (!innerWindow) {
   1902    return nullptr;
   1903  }
   1904 
   1905  if (!TriggeringPrincipal()->Equals(innerWindow->GetPrincipal())) {
   1906    return nullptr;
   1907  }
   1908 
   1909  if (nsILoadInfo::GetExternalContentPolicyType() ==
   1910          ExtContentPolicy::TYPE_SUBDOCUMENT &&
   1911      !GetIsFromProcessingFrameAttributes()) {
   1912    // We only report loads caused by processing the attributes of the
   1913    // browsing context container.
   1914    return nullptr;
   1915  }
   1916 
   1917  mozilla::dom::Performance* performance = innerWindow->GetPerformance();
   1918  if (!performance) {
   1919    return nullptr;
   1920  }
   1921 
   1922  return performance->AsPerformanceStorage();
   1923 }
   1924 
   1925 NS_IMETHODIMP
   1926 LoadInfo::GetCspEventListener(nsICSPEventListener** aCSPEventListener) {
   1927  *aCSPEventListener = do_AddRef(mCSPEventListener).take();
   1928  return NS_OK;
   1929 }
   1930 
   1931 NS_IMETHODIMP
   1932 LoadInfo::SetCspEventListener(nsICSPEventListener* aCSPEventListener) {
   1933  mCSPEventListener = aCSPEventListener;
   1934  return NS_OK;
   1935 }
   1936 
   1937 NS_IMETHODIMP
   1938 LoadInfo::GetInternalContentPolicyType(nsContentPolicyType* aResult) {
   1939  *aResult = mInternalContentPolicyType;
   1940  return NS_OK;
   1941 }
   1942 
   1943 NS_IMETHODIMP
   1944 LoadInfo::GetFetchDestination(nsACString& aDestination) {
   1945  aDestination.Assign(
   1946      GetEnumString(InternalRequest::MapContentPolicyTypeToRequestDestination(
   1947          mInternalContentPolicyType)));
   1948  return NS_OK;
   1949 }
   1950 
   1951 already_AddRefed<nsIContentSecurityPolicy> LoadInfo::GetPreloadCsp() {
   1952  if (mClientInfo.isNothing()) {
   1953    return nullptr;
   1954  }
   1955 
   1956  nsCOMPtr<nsINode> node = do_QueryReferent(mLoadingContext);
   1957  RefPtr<Document> doc = node ? node->OwnerDoc() : nullptr;
   1958 
   1959  // If the client is of type window, then we return the cached CSP
   1960  // stored on the document instead of having to deserialize the CSP
   1961  // from the ClientInfo.
   1962  if (doc && mClientInfo->Type() == ClientType::Window) {
   1963    nsCOMPtr<nsIContentSecurityPolicy> preloadCsp = doc->GetPreloadCsp();
   1964    return preloadCsp.forget();
   1965  }
   1966 
   1967  Maybe<mozilla::ipc::CSPInfo> cspInfo = mClientInfo->GetPreloadCspInfo();
   1968  if (cspInfo.isNothing()) {
   1969    return nullptr;
   1970  }
   1971  nsCOMPtr<nsIContentSecurityPolicy> preloadCSP =
   1972      CSPInfoToCSP(cspInfo.ref(), doc);
   1973  return preloadCSP.forget();
   1974 }
   1975 
   1976 already_AddRefed<nsIPolicyContainer> LoadInfo::GetPolicyContainer() {
   1977  // Before querying the CSP from the client we have to check if the
   1978  // triggeringPrincipal originates from an addon and potentially
   1979  // overrides the CSP stored within the client.
   1980  if (mLoadingPrincipal && BasePrincipal::Cast(mTriggeringPrincipal)
   1981                               ->OverridesCSP(mLoadingPrincipal)) {
   1982    nsCOMPtr<nsIExpandedPrincipal> ep = do_QueryInterface(mTriggeringPrincipal);
   1983    RefPtr<PolicyContainer> addonPolicyContainer;
   1984    if (ep) {
   1985      // Bug 1548468: Move CSP off ExpandedPrincipal
   1986      if (nsCOMPtr<nsIContentSecurityPolicy> addonCSP = ep->GetCsp()) {
   1987        // Extensions don't have anything other than CSP in the policy
   1988        // container. We need to return a PolicyContainer, so we just create one
   1989        // with the CSP from the ExpandedPrincipal.
   1990        addonPolicyContainer = new PolicyContainer();
   1991        addonPolicyContainer->SetCSP(addonCSP);
   1992      }
   1993    }
   1994    return addonPolicyContainer.forget();
   1995  }
   1996 
   1997  if (mClientInfo.isNothing()) {
   1998    return nullptr;
   1999  }
   2000 
   2001  nsCOMPtr<nsINode> node = do_QueryReferent(mLoadingContext);
   2002  RefPtr<Document> doc = node ? node->OwnerDoc() : nullptr;
   2003 
   2004  // If the client is of type window, then we return the cached CSP
   2005  // stored on the document instead of having to deserialize the CSP
   2006  // from the ClientInfo.
   2007  if (doc && mClientInfo->Type() == ClientType::Window) {
   2008    nsCOMPtr<nsIPolicyContainer> docPolicyContainer = doc->GetPolicyContainer();
   2009    return docPolicyContainer.forget();
   2010  }
   2011 
   2012  Maybe<mozilla::ipc::PolicyContainerArgs> policyContainerArgs =
   2013      mClientInfo->GetPolicyContainerArgs();
   2014  if (policyContainerArgs.isNothing()) {
   2015    return nullptr;
   2016  }
   2017  RefPtr<PolicyContainer> clientPolicyContainer;
   2018  PolicyContainer::FromArgs(policyContainerArgs.ref(), doc,
   2019                            getter_AddRefs(clientPolicyContainer));
   2020  return clientPolicyContainer.forget();
   2021 }
   2022 
   2023 void LoadInfo::SetPolicyContainerToInherit(
   2024    nsIPolicyContainer* aPolicyContainerToInherit) {
   2025  mPolicyContainerToInherit = aPolicyContainerToInherit;
   2026 }
   2027 
   2028 already_AddRefed<nsIPolicyContainer> LoadInfo::GetPolicyContainerToInherit() {
   2029  nsCOMPtr<nsIPolicyContainer> policyContainerToInherit =
   2030      mPolicyContainerToInherit;
   2031  return policyContainerToInherit.forget();
   2032 }
   2033 
   2034 Maybe<FeaturePolicyInfo> LoadInfo::GetContainerFeaturePolicyInfo() {
   2035  return mContainerFeaturePolicyInfo;
   2036 }
   2037 
   2038 void LoadInfo::SetContainerFeaturePolicyInfo(
   2039    const FeaturePolicyInfo& aContainerFeaturePolicyInfo) {
   2040  mContainerFeaturePolicyInfo = Some(aContainerFeaturePolicyInfo);
   2041 }
   2042 
   2043 nsIInterceptionInfo* LoadInfo::InterceptionInfo() { return mInterceptionInfo; }
   2044 
   2045 void LoadInfo::SetInterceptionInfo(nsIInterceptionInfo* aInfo) {
   2046  mInterceptionInfo = aInfo;
   2047 }
   2048 
   2049 NS_IMETHODIMP
   2050 LoadInfo::GetSchemelessInput(
   2051    nsILoadInfo::SchemelessInputType* aSchemelessInput) {
   2052  *aSchemelessInput = mSchemelessInput;
   2053  return NS_OK;
   2054 }
   2055 
   2056 NS_IMETHODIMP
   2057 LoadInfo::SetSchemelessInput(
   2058    nsILoadInfo::SchemelessInputType aSchemelessInput) {
   2059  mSchemelessInput = aSchemelessInput;
   2060  return NS_OK;
   2061 }
   2062 
   2063 NS_IMETHODIMP
   2064 LoadInfo::GetSkipHTTPSUpgrade(bool* aSkipHTTPSUpgrade) {
   2065  *aSkipHTTPSUpgrade = mSkipHTTPSUpgrade;
   2066  return NS_OK;
   2067 }
   2068 
   2069 NS_IMETHODIMP
   2070 LoadInfo::SetSkipHTTPSUpgrade(bool aSkipHTTPSUpgrade) {
   2071  mSkipHTTPSUpgrade = aSkipHTTPSUpgrade;
   2072  return NS_OK;
   2073 }
   2074 
   2075 void LoadInfo::UpdateParentAddressSpaceInfo() {
   2076  MOZ_ASSERT(mInternalContentPolicyType != nsContentPolicyType::TYPE_INVALID,
   2077             "Content policy must be set before updating address spsace");
   2078  ExtContentPolicyType externalType =
   2079      nsContentUtils::InternalContentPolicyTypeToExternal(
   2080          mInternalContentPolicyType);
   2081 
   2082  RefPtr<mozilla::dom::BrowsingContext> bc;
   2083  GetBrowsingContext(getter_AddRefs(bc));
   2084  if (!bc) {
   2085    mParentIpAddressSpace = nsILoadInfo::Local;
   2086    return;
   2087  }
   2088  // if this main or sub document then we need to assign IPAddressSpace of
   2089  // the parent's browsing context
   2090  if (externalType == ExtContentPolicy::TYPE_DOCUMENT ||
   2091      externalType == ExtContentPolicy::TYPE_SUBDOCUMENT) {
   2092    if (bc->GetParent()) {
   2093      mParentIpAddressSpace = bc->GetParent()->GetCurrentIPAddressSpace();
   2094    } else if (RefPtr<dom::BrowsingContext> opener = bc->GetOpener()) {
   2095      mParentIpAddressSpace = opener->GetCurrentIPAddressSpace();
   2096    } else {
   2097      // XXX (sunil): add if this was loaded from about:blank. In that case we
   2098      // need to give assign local IPAddress
   2099    }
   2100  } else {
   2101    // For non-document loads, we need to set the parent IPAddressSpace to
   2102    // IPAddress space of the browsing context
   2103    mParentIpAddressSpace = bc->GetCurrentIPAddressSpace();
   2104  }
   2105 }
   2106 
   2107 }  // namespace mozilla::net