summaryrefslogtreecommitdiffstats
path: root/netwerk/cookie/CookieJarSettings.cpp
blob: 9e598c296f2f0e2b0d870399425f16fc331dff07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozIThirdPartyUtil.h"
#include "mozilla/AntiTrackingUtils.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Components.h"
#include "mozilla/ContentBlockingAllowList.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/net/CookieJarSettings.h"
#include "mozilla/net/NeckoChannelParams.h"
#include "mozilla/Permission.h"
#include "mozilla/PermissionManager.h"
#include "mozilla/SchedulerGroup.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/StoragePrincipalHelper.h"
#include "mozilla/Unused.h"
#include "nsIPrincipal.h"
#if defined(MOZ_THUNDERBIRD) || defined(MOZ_SUITE)
#  include "nsIProtocolHandler.h"
#endif
#include "nsIClassInfoImpl.h"
#include "nsIChannel.h"
#include "nsICookieManager.h"
#include "nsICookieService.h"
#include "nsIObjectInputStream.h"
#include "nsIObjectOutputStream.h"
#include "nsNetUtil.h"

namespace mozilla {
namespace net {

NS_IMPL_CLASSINFO(CookieJarSettings, nullptr, nsIClassInfo::THREADSAFE,
                  COOKIEJARSETTINGS_CID)

NS_IMPL_ISUPPORTS_CI(CookieJarSettings, nsICookieJarSettings, nsISerializable)

static StaticRefPtr<CookieJarSettings> sBlockinAll;

namespace {

class PermissionComparator {
 public:
  static bool Equals(nsIPermission* aA, nsIPermission* aB) {
    nsCOMPtr<nsIPrincipal> principalA;
    nsresult rv = aA->GetPrincipal(getter_AddRefs(principalA));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return false;
    }

    nsCOMPtr<nsIPrincipal> principalB;
    rv = aB->GetPrincipal(getter_AddRefs(principalB));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return false;
    }

    bool equals = false;
    rv = principalA->Equals(principalB, &equals);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return false;
    }

    return equals;
  }
};

class ReleaseCookiePermissions final : public Runnable {
 public:
  explicit ReleaseCookiePermissions(nsTArray<RefPtr<nsIPermission>>&& aArray)
      : Runnable("ReleaseCookiePermissions"), mArray(std::move(aArray)) {}

  NS_IMETHOD Run() override {
    MOZ_ASSERT(NS_IsMainThread());
    mArray.Clear();
    return NS_OK;
  }

 private:
  nsTArray<RefPtr<nsIPermission>> mArray;
};

}  // namespace

// static
already_AddRefed<nsICookieJarSettings> CookieJarSettings::GetBlockingAll(
    bool aShouldResistFingerprinting) {
  MOZ_ASSERT(NS_IsMainThread());

  if (sBlockinAll) {
    return do_AddRef(sBlockinAll);
  }

  sBlockinAll = new CookieJarSettings(nsICookieService::BEHAVIOR_REJECT,
                                      OriginAttributes::IsFirstPartyEnabled(),
                                      aShouldResistFingerprinting, eFixed);
  ClearOnShutdown(&sBlockinAll);

  return do_AddRef(sBlockinAll);
}

// static
already_AddRefed<nsICookieJarSettings> CookieJarSettings::Create(
    CreateMode aMode, bool aShouldResistFingerprinting) {
  MOZ_ASSERT(NS_IsMainThread());

  RefPtr<CookieJarSettings> cookieJarSettings;

  switch (aMode) {
    case eRegular:
    case ePrivate:
      cookieJarSettings = new CookieJarSettings(
          nsICookieManager::GetCookieBehavior(aMode == ePrivate),
          OriginAttributes::IsFirstPartyEnabled(), aShouldResistFingerprinting,
          eProgressive);
      break;

    default:
      MOZ_CRASH("Unexpected create mode.");
  }

  return cookieJarSettings.forget();
}

// static
already_AddRefed<nsICookieJarSettings> CookieJarSettings::Create(
    nsIPrincipal* aPrincipal) {
  MOZ_ASSERT(NS_IsMainThread());

  bool shouldResistFingerprinting =
      nsContentUtils::ShouldResistFingerprinting_dangerous(
          aPrincipal, "We are constructing CookieJarSettings here.",
          RFPTarget::IsAlwaysEnabledForPrecompute);

  if (aPrincipal && aPrincipal->OriginAttributesRef().mPrivateBrowsingId > 0) {
    return Create(ePrivate, shouldResistFingerprinting);
  }

  return Create(eRegular, shouldResistFingerprinting);
}

// static
already_AddRefed<nsICookieJarSettings> CookieJarSettings::Create(
    uint32_t aCookieBehavior, const nsAString& aPartitionKey,
    bool aIsFirstPartyIsolated, bool aIsOnContentBlockingAllowList,
    bool aShouldResistFingerprinting) {
  MOZ_ASSERT(NS_IsMainThread());

  RefPtr<CookieJarSettings> cookieJarSettings =
      new CookieJarSettings(aCookieBehavior, aIsFirstPartyIsolated,
                            aShouldResistFingerprinting, eProgressive);
  cookieJarSettings->mPartitionKey = aPartitionKey;
  cookieJarSettings->mIsOnContentBlockingAllowList =
      aIsOnContentBlockingAllowList;

  return cookieJarSettings.forget();
}

// static
already_AddRefed<nsICookieJarSettings> CookieJarSettings::CreateForXPCOM() {
  MOZ_ASSERT(NS_IsMainThread());
  return Create(eRegular, /* shouldResistFingerprinting */ false);
}

CookieJarSettings::CookieJarSettings(uint32_t aCookieBehavior,
                                     bool aIsFirstPartyIsolated,
                                     bool aShouldResistFingerprinting,
                                     State aState)
    : mCookieBehavior(aCookieBehavior),
      mIsFirstPartyIsolated(aIsFirstPartyIsolated),
      mIsOnContentBlockingAllowList(false),
      mIsOnContentBlockingAllowListUpdated(false),
      mState(aState),
      mToBeMerged(false),
      mShouldResistFingerprinting(aShouldResistFingerprinting),
      mTopLevelWindowContextId(0) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT_IF(
      mIsFirstPartyIsolated,
      mCookieBehavior !=
          nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN);
}

CookieJarSettings::~CookieJarSettings() {
  if (!NS_IsMainThread() && !mCookiePermissions.IsEmpty()) {
    RefPtr<Runnable> r =
        new ReleaseCookiePermissions(std::move(mCookiePermissions));
    MOZ_ASSERT(mCookiePermissions.IsEmpty());
    SchedulerGroup::Dispatch(r.forget());
  }
}

NS_IMETHODIMP
CookieJarSettings::InitWithURI(nsIURI* aURI, bool aIsPrivate) {
  NS_ENSURE_ARG(aURI);

  mCookieBehavior = nsICookieManager::GetCookieBehavior(aIsPrivate);

  SetPartitionKey(aURI, false);
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetCookieBehavior(uint32_t* aCookieBehavior) {
  *aCookieBehavior = mCookieBehavior;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetIsFirstPartyIsolated(bool* aIsFirstPartyIsolated) {
  *aIsFirstPartyIsolated = mIsFirstPartyIsolated;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetShouldResistFingerprinting(
    bool* aShouldResistFingerprinting) {
  *aShouldResistFingerprinting = mShouldResistFingerprinting;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetRejectThirdPartyContexts(
    bool* aRejectThirdPartyContexts) {
  *aRejectThirdPartyContexts =
      CookieJarSettings::IsRejectThirdPartyContexts(mCookieBehavior);
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetLimitForeignContexts(bool* aLimitForeignContexts) {
  *aLimitForeignContexts =
      mCookieBehavior == nsICookieService::BEHAVIOR_LIMIT_FOREIGN ||
      (StaticPrefs::privacy_dynamic_firstparty_limitForeign() &&
       mCookieBehavior ==
           nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN);
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetBlockingAllThirdPartyContexts(
    bool* aBlockingAllThirdPartyContexts) {
  // XXX For non-cookie forms of storage, we handle BEHAVIOR_LIMIT_FOREIGN by
  // simply rejecting the request to use the storage. In the future, if we
  // change the meaning of BEHAVIOR_LIMIT_FOREIGN to be one which makes sense
  // for non-cookie storage types, this may change.
  *aBlockingAllThirdPartyContexts =
      mCookieBehavior == nsICookieService::BEHAVIOR_LIMIT_FOREIGN ||
      mCookieBehavior == nsICookieService::BEHAVIOR_REJECT_FOREIGN;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetBlockingAllContexts(bool* aBlockingAllContexts) {
  *aBlockingAllContexts = mCookieBehavior == nsICookieService::BEHAVIOR_REJECT;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetPartitionForeign(bool* aPartitionForeign) {
  *aPartitionForeign =
      mCookieBehavior ==
      nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::SetPartitionForeign(bool aPartitionForeign) {
  if (mIsFirstPartyIsolated) {
    return NS_OK;
  }

  if (aPartitionForeign) {
    mCookieBehavior =
        nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
  }
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetIsOnContentBlockingAllowList(
    bool* aIsOnContentBlockingAllowList) {
  *aIsOnContentBlockingAllowList = mIsOnContentBlockingAllowList;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetPartitionKey(nsAString& aPartitionKey) {
  aPartitionKey = mPartitionKey;
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::GetFingerprintingRandomizationKey(
    nsTArray<uint8_t>& aFingerprintingRandomizationKey) {
  if (!mFingerprintingRandomKey) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  aFingerprintingRandomizationKey = mFingerprintingRandomKey->Clone();
  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::CookiePermission(nsIPrincipal* aPrincipal,
                                    uint32_t* aCookiePermission) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  NS_ENSURE_ARG_POINTER(aPrincipal);
  NS_ENSURE_ARG_POINTER(aCookiePermission);

  *aCookiePermission = nsIPermissionManager::UNKNOWN_ACTION;

  nsresult rv;

  // Let's see if we know this permission.
  if (!mCookiePermissions.IsEmpty()) {
    for (const RefPtr<nsIPermission>& permission : mCookiePermissions) {
      bool match = false;
      rv = permission->Matches(aPrincipal, false, &match);
      if (NS_WARN_IF(NS_FAILED(rv)) || !match) {
        continue;
      }

      rv = permission->GetCapability(aCookiePermission);
      if (NS_WARN_IF(NS_FAILED(rv))) {
        return rv;
      }

      return NS_OK;
    }
  }

  // Let's ask the permission manager.
  PermissionManager* pm = PermissionManager::GetInstance();
  if (NS_WARN_IF(!pm)) {
    return NS_ERROR_FAILURE;
  }

#if defined(MOZ_THUNDERBIRD) || defined(MOZ_SUITE)
  // Check if this protocol doesn't allow cookies.
  bool hasFlags;
  nsCOMPtr<nsIURI> uri;
  BasePrincipal::Cast(aPrincipal)->GetURI(getter_AddRefs(uri));

  rv = NS_URIChainHasFlags(uri, nsIProtocolHandler::URI_FORBIDS_COOKIE_ACCESS,
                           &hasFlags);
  if (NS_FAILED(rv) || hasFlags) {
    *aCookiePermission = PermissionManager::DENY_ACTION;
    rv = NS_OK;  // Reset, so it's not caught as a bad status after the `else`.
  } else         // Note the tricky `else` which controls the call below.
#endif

    rv = pm->TestPermissionFromPrincipal(aPrincipal, "cookie"_ns,
                                         aCookiePermission);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Let's store the permission, also if the result is UNKNOWN in order to avoid
  // race conditions.

  nsCOMPtr<nsIPermission> permission =
      Permission::Create(aPrincipal, "cookie"_ns, *aCookiePermission, 0, 0, 0);
  if (permission) {
    mCookiePermissions.AppendElement(permission);
  }

  mToBeMerged = true;
  return NS_OK;
}

void CookieJarSettings::Serialize(CookieJarSettingsArgs& aData) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());

  aData.isFixed() = mState == eFixed;
  aData.cookieBehavior() = mCookieBehavior;
  aData.isFirstPartyIsolated() = mIsFirstPartyIsolated;
  aData.shouldResistFingerprinting() = mShouldResistFingerprinting;
  aData.isOnContentBlockingAllowList() = mIsOnContentBlockingAllowList;
  aData.partitionKey() = mPartitionKey;
  if (mFingerprintingRandomKey) {
    aData.hasFingerprintingRandomizationKey() = true;
    aData.fingerprintingRandomizationKey() = mFingerprintingRandomKey->Clone();
  } else {
    aData.hasFingerprintingRandomizationKey() = false;
  }

  for (const RefPtr<nsIPermission>& permission : mCookiePermissions) {
    nsCOMPtr<nsIPrincipal> principal;
    nsresult rv = permission->GetPrincipal(getter_AddRefs(principal));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      continue;
    }

    ipc::PrincipalInfo principalInfo;
    rv = PrincipalToPrincipalInfo(principal, &principalInfo,
                                  true /* aSkipBaseDomain */);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      continue;
    }

    uint32_t cookiePermission = 0;
    rv = permission->GetCapability(&cookiePermission);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      continue;
    }

    aData.cookiePermissions().AppendElement(
        CookiePermissionData(principalInfo, cookiePermission));
  }

  aData.topLevelWindowContextId() = mTopLevelWindowContextId;

  mToBeMerged = false;
}

/* static */ void CookieJarSettings::Deserialize(
    const CookieJarSettingsArgs& aData,
    nsICookieJarSettings** aCookieJarSettings) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());

  CookiePermissionList list;
  for (const CookiePermissionData& data : aData.cookiePermissions()) {
    auto principalOrErr = PrincipalInfoToPrincipal(data.principalInfo());
    if (NS_WARN_IF(principalOrErr.isErr())) {
      continue;
    }

    nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();

    nsCOMPtr<nsIPermission> permission = Permission::Create(
        principal, "cookie"_ns, data.cookiePermission(), 0, 0, 0);
    if (NS_WARN_IF(!permission)) {
      continue;
    }

    list.AppendElement(permission);
  }

  RefPtr<CookieJarSettings> cookieJarSettings = new CookieJarSettings(
      aData.cookieBehavior(), aData.isFirstPartyIsolated(),
      aData.shouldResistFingerprinting(),
      aData.isFixed() ? eFixed : eProgressive);

  cookieJarSettings->mIsOnContentBlockingAllowList =
      aData.isOnContentBlockingAllowList();
  cookieJarSettings->mCookiePermissions = std::move(list);
  cookieJarSettings->mPartitionKey = aData.partitionKey();
  cookieJarSettings->mShouldResistFingerprinting =
      aData.shouldResistFingerprinting();

  if (aData.hasFingerprintingRandomizationKey()) {
    cookieJarSettings->mFingerprintingRandomKey.emplace(
        aData.fingerprintingRandomizationKey().Clone());
  }

  cookieJarSettings->mTopLevelWindowContextId = aData.topLevelWindowContextId();

  cookieJarSettings.forget(aCookieJarSettings);
}

void CookieJarSettings::Merge(const CookieJarSettingsArgs& aData) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(
      mCookieBehavior == aData.cookieBehavior() ||
      (mCookieBehavior == nsICookieService::BEHAVIOR_REJECT_TRACKER &&
       aData.cookieBehavior() ==
           nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN) ||
      (mCookieBehavior ==
           nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN &&
       aData.cookieBehavior() == nsICookieService::BEHAVIOR_REJECT_TRACKER));

  if (mState == eFixed) {
    return;
  }

  // Merge cookie behavior pref values
  if (mCookieBehavior == nsICookieService::BEHAVIOR_REJECT_TRACKER &&
      aData.cookieBehavior() ==
          nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN) {
    // If the other side has decided to partition third-party cookies, update
    // our side when first-party isolation is disabled.
    if (!mIsFirstPartyIsolated) {
      mCookieBehavior =
          nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
    }
  }
  if (mCookieBehavior ==
          nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN &&
      aData.cookieBehavior() == nsICookieService::BEHAVIOR_REJECT_TRACKER) {
    // If we've decided to partition third-party cookies, the other side may not
    // have caught up yet unless it has first-party isolation enabled.
    if (aData.isFirstPartyIsolated()) {
      mCookieBehavior = nsICookieService::BEHAVIOR_REJECT_TRACKER;
      mIsFirstPartyIsolated = true;
    }
  }
  // Ignore all other cases.
  MOZ_ASSERT_IF(
      mIsFirstPartyIsolated,
      mCookieBehavior !=
          nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN);

  if (aData.shouldResistFingerprinting()) {
    mShouldResistFingerprinting = true;
  }

  PermissionComparator comparator;

  for (const CookiePermissionData& data : aData.cookiePermissions()) {
    auto principalOrErr = PrincipalInfoToPrincipal(data.principalInfo());
    if (NS_WARN_IF(principalOrErr.isErr())) {
      continue;
    }

    nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
    nsCOMPtr<nsIPermission> permission = Permission::Create(
        principal, "cookie"_ns, data.cookiePermission(), 0, 0, 0);
    if (NS_WARN_IF(!permission)) {
      continue;
    }

    if (!mCookiePermissions.Contains(permission, comparator)) {
      mCookiePermissions.AppendElement(permission);
    }
  }
}

void CookieJarSettings::SetPartitionKey(nsIURI* aURI,
                                        bool aForeignByAncestorContext) {
  MOZ_ASSERT(aURI);

  OriginAttributes attrs;
  attrs.SetPartitionKey(aURI, aForeignByAncestorContext);
  mPartitionKey = std::move(attrs.mPartitionKey);
}

void CookieJarSettings::UpdatePartitionKeyForDocumentLoadedByChannel(
    nsIChannel* aChannel) {
  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();
  bool thirdParty = AntiTrackingUtils::IsThirdPartyChannel(aChannel);
  bool foreignByAncestorContext =
      thirdParty && !loadInfo->GetIsThirdPartyContextToTopWindow();
  StoragePrincipalHelper::UpdatePartitionKeyWithForeignAncestorBit(
      mPartitionKey, foreignByAncestorContext);
}

void CookieJarSettings::UpdateIsOnContentBlockingAllowList(
    nsIChannel* aChannel) {
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
  MOZ_ASSERT(aChannel);

  // Early return if the flag was updated before.
  if (mIsOnContentBlockingAllowListUpdated) {
    return;
  }
  mIsOnContentBlockingAllowListUpdated = true;

  nsCOMPtr<nsILoadInfo> loadInfo = aChannel->LoadInfo();

  nsCOMPtr<nsIURI> uri;
  nsresult rv = aChannel->GetURI(getter_AddRefs(uri));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  // We need to recompute the ContentBlockingAllowListPrincipal here for the
  // top level channel because we might navigate from the the initial
  // about:blank page or the existing page which may have a different origin
  // than the URI we are going to load here. Thus, we need to recompute the
  // prinicpal in order to get the correct ContentBlockingAllowListPrincipal.
  nsCOMPtr<nsIPrincipal> contentBlockingAllowListPrincipal;
  OriginAttributes attrs;
  loadInfo->GetOriginAttributes(&attrs);
  ContentBlockingAllowList::RecomputePrincipal(
      uri, attrs, getter_AddRefs(contentBlockingAllowListPrincipal));

  if (!contentBlockingAllowListPrincipal ||
      !contentBlockingAllowListPrincipal->GetIsContentPrincipal()) {
    return;
  }

  Unused << ContentBlockingAllowList::Check(contentBlockingAllowListPrincipal,
                                            NS_UsePrivateBrowsing(aChannel),
                                            mIsOnContentBlockingAllowList);
}

// static
bool CookieJarSettings::IsRejectThirdPartyContexts(uint32_t aCookieBehavior) {
  return aCookieBehavior == nsICookieService::BEHAVIOR_REJECT_TRACKER ||
         aCookieBehavior ==
             nsICookieService::BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN;
}

NS_IMETHODIMP
CookieJarSettings::Read(nsIObjectInputStream* aStream) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  nsresult rv = aStream->Read32(&mCookieBehavior);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->ReadBoolean(&mIsFirstPartyIsolated);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->ReadBoolean(&mShouldResistFingerprinting);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  bool isFixed;
  aStream->ReadBoolean(&isFixed);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }
  mState = isFixed ? eFixed : eProgressive;

  rv = aStream->ReadBoolean(&mIsOnContentBlockingAllowList);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->ReadString(mPartitionKey);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Deserializing the cookie permission list.
  uint32_t cookiePermissionsLength;
  rv = aStream->Read32(&cookiePermissionsLength);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  if (!cookiePermissionsLength) {
    // Bailing out early because there is no cookie permission.
    return NS_OK;
  }

  CookiePermissionList list;
  mCookiePermissions.SetCapacity(cookiePermissionsLength);
  for (uint32_t i = 0; i < cookiePermissionsLength; ++i) {
    nsAutoCString principalJSON;
    aStream->ReadCString(principalJSON);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    nsCOMPtr<nsIPrincipal> principal = BasePrincipal::FromJSON(principalJSON);

    if (NS_WARN_IF(!principal)) {
      continue;
    }

    uint32_t cookiePermission;
    aStream->Read32(&cookiePermission);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    nsCOMPtr<nsIPermission> permission =
        Permission::Create(principal, "cookie"_ns, cookiePermission, 0, 0, 0);
    if (NS_WARN_IF(!permission)) {
      continue;
    }

    list.AppendElement(permission);
  }

  mCookiePermissions = std::move(list);

  return NS_OK;
}

NS_IMETHODIMP
CookieJarSettings::Write(nsIObjectOutputStream* aStream) {
  MOZ_RELEASE_ASSERT(NS_IsMainThread());
  nsresult rv = aStream->Write32(mCookieBehavior);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->WriteBoolean(mIsFirstPartyIsolated);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->WriteBoolean(mShouldResistFingerprinting);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->WriteBoolean(mState == eFixed);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->WriteBoolean(mIsOnContentBlockingAllowList);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = aStream->WriteWStringZ(mPartitionKey.get());
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  // Serializing the cookie permission list. It will first write the length of
  // the list, and then, write the cookie permission consecutively.
  uint32_t cookiePermissionsLength = mCookiePermissions.Length();
  rv = aStream->Write32(cookiePermissionsLength);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  for (const RefPtr<nsIPermission>& permission : mCookiePermissions) {
    nsCOMPtr<nsIPrincipal> principal;
    nsresult rv = permission->GetPrincipal(getter_AddRefs(principal));
    if (NS_WARN_IF(NS_FAILED(rv))) {
      continue;
    }

    nsAutoCString principalJSON;
    BasePrincipal::Cast(principal)->ToJSON(principalJSON);

    rv = aStream->WriteStringZ(principalJSON.get());
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    uint32_t cookiePermission = 0;
    rv = permission->GetCapability(&cookiePermission);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      continue;
    }

    rv = aStream->Write32(cookiePermission);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
  }

  return NS_OK;
}

}  // namespace net
}  // namespace mozilla