| 12
 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
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 
 | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/browsing_data/content/browsing_data_model.h"
#include <variant>
#include "base/barrier_closure.h"
#include "base/feature_list.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "components/browsing_data/content/browsing_data_model_test_util.h"
#include "components/browsing_data/content/test_browsing_data_model_delegate.h"
#include "content/public/browser/browser_context.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_storage_partition.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "net/base/schemeful_site.h"
#include "net/cookies/canonical_cookie.h"
#include "net/extras/shared_dictionary/shared_dictionary_usage_info.h"
#include "net/shared_dictionary/shared_dictionary_isolation_key.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/trust_tokens.mojom.h"
#include "services/network/test/test_network_context.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "url/origin.h"
using browsing_data_model_test_util::BrowsingDataEntry;
using browsing_data_model_test_util::ValidateBrowsingDataEntries;
namespace {
class MockNetworkContext : public network::TestNetworkContext {
 public:
  explicit MockNetworkContext(
      mojo::PendingReceiver<network::mojom::NetworkContext> receiver)
      : receiver_(this, std::move(receiver)) {}
  MOCK_METHOD(void,
              GetStoredTrustTokenCounts,
              (GetStoredTrustTokenCountsCallback),
              (override));
  MOCK_METHOD(void,
              DeleteStoredTrustTokens,
              (const url::Origin&, DeleteStoredTrustTokensCallback),
              (override));
  MOCK_METHOD(void,
              GetSharedDictionaryUsageInfo,
              (GetSharedDictionaryUsageInfoCallback),
              (override));
  MOCK_METHOD(void,
              ClearSharedDictionaryCacheForIsolationKey,
              (const net::SharedDictionaryIsolationKey&,
               ClearSharedDictionaryCacheForIsolationKeyCallback),
              (override));
 private:
  mojo::Receiver<network::mojom::NetworkContext> receiver_;
};
std::unique_ptr<net::CanonicalCookie> MakeCanonicalCookie(
    const std::string& name,
    const std::string& domain,
    std::optional<net::CookiePartitionKey> cookie_partition_key =
        std::nullopt) {
  return net::CanonicalCookie::CreateUnsafeCookieForTesting(
      name, "1", domain, /*path=*/"/", /*creation=*/base::Time(),
      /*expiration=*/base::Time(), /*last_access=*/base::Time(),
      /*last_update=*/base::Time(),
      /*secure=*/true, /*httponly=*/false, net::CookieSameSite::UNSPECIFIED,
      net::CookiePriority::COOKIE_PRIORITY_DEFAULT, cookie_partition_key);
}
}  // namespace
class BrowsingDataModelTest : public testing::Test {
 public:
  BrowsingDataModelTest() {
    mojo::PendingRemote<network::mojom::NetworkContext> network_context_remote;
    mock_network_context_ = std::make_unique<MockNetworkContext>(
        network_context_remote.InitWithNewPipeAndPassReceiver());
    storage_partition()->SetNetworkContextForTesting(
        std::move(network_context_remote));
    model_ = BrowsingDataModel::BuildEmpty(
        storage_partition(),
        std::make_unique<browsing_data::TestBrowsingDataModelDelegate>());
  }
  ~BrowsingDataModelTest() override = default;
  void TearDown() override { mock_network_context_.reset(); }
 protected:
  void BuildModel(base::OnceClosure completed) {
    model()->PopulateFromDisk(std::move(completed));
  }
  void DeleteModel() { model_.reset(); }
  content::BrowserContext* browser_context() { return &browser_context_; }
  BrowsingDataModel* model() { return model_.get(); }
  content::StoragePartition* storage_partition() {
    return browser_context()->GetDefaultStoragePartition();
  }
  MockNetworkContext* mock_network_context() {
    return mock_network_context_.get();
  }
  BrowsingDataModel::BrowsingDataEntries& browsing_data_entries() {
    return model_->browsing_data_entries_;
  }
  const url::Origin kSubdomainOrigin =
      url::Origin::Create(GURL("https://subsite.example.com"));
  const std::string kSubdomainOriginHost = "subsite.example.com";
  const std::string kSubdomainOriginSite = "example.com";
  const url::Origin kSiteOrigin =
      url::Origin::Create(GURL("https://example.com"));
  const std::string kSiteOriginHost = "example.com";
  const url::Origin kAnotherSiteOrigin =
      url::Origin::Create(GURL("https://another-example.com"));
  const std::string kAnotherSiteOriginHost = "another-example.com";
  const url::Origin kTestOrigin = url::Origin::Create(GURL("https://a.test"));
  const std::string kTestOriginHost = "a.test";
  const url::Origin kAnotherTestOrigin =
      url::Origin::Create(GURL("https://b.test"));
  const std::string kAnotherTestOriginHost = "b.test";
 private:
  content::BrowserTaskEnvironment task_environment_;
  content::TestBrowserContext browser_context_;
  std::unique_ptr<BrowsingDataModel> model_;
  content::TestStoragePartition storage_partition_;
  std::unique_ptr<MockNetworkContext> mock_network_context_;
};
TEST_F(BrowsingDataModelTest, PrimaryHostMapping) {
  model()->AddBrowsingData(kSubdomainOrigin,
                           BrowsingDataModel::StorageType::kTrustTokens, 0, 1);
  model()->AddBrowsingData(blink::StorageKey::CreateFirstParty(kTestOrigin),
                           BrowsingDataModel::StorageType::kQuotaStorage, 123,
                           0);
  ValidateBrowsingDataEntries(
      model(), {
                   {kSubdomainOriginHost,
                    kSubdomainOrigin,
                    {{BrowsingDataModel::StorageType::kTrustTokens}, 0, 1}},
                   {kTestOriginHost,
                    blink::StorageKey::CreateFirstParty(kTestOrigin),
                    {{BrowsingDataModel::StorageType::kQuotaStorage}, 123, 0}},
               });
}
TEST_F(BrowsingDataModelTest, EntryCoalescense) {
  // Check that multiple entries are correctly coalesced.
  // Browsing data with the same owner + data_key pair should update the
  // same entry's details.
  model()->AddBrowsingData(blink::StorageKey::CreateFirstParty(kSiteOrigin),
                           BrowsingDataModel::StorageType::kQuotaStorage, 123,
                           0);
  model()->AddBrowsingData(blink::StorageKey::CreateFirstParty(kSiteOrigin),
                           BrowsingDataModel::StorageType::kLocalStorage, 234,
                           5);
  auto expected_entries = std::vector<BrowsingDataEntry>(
      {{kSiteOriginHost,
        blink::StorageKey::CreateFirstParty(kSiteOrigin),
        {{BrowsingDataModel::StorageType::kQuotaStorage,
          BrowsingDataModel::StorageType::kLocalStorage},
         123 + 234,
         5}}});
  ValidateBrowsingDataEntries(model(), expected_entries);
  // Entries related to the same owner, but different data_keys, should
  // create a new entry.
  model()->AddBrowsingData(
      blink::StorageKey::CreateFirstParty(kAnotherSiteOrigin),
      BrowsingDataModel::StorageType::kQuotaStorage, 345, 0);
  model()->AddBrowsingData(
      kAnotherSiteOrigin, BrowsingDataModel::StorageType::kTrustTokens, 456, 6);
  expected_entries.push_back(
      {kAnotherSiteOriginHost,
       blink::StorageKey::CreateFirstParty(kAnotherSiteOrigin),
       {{BrowsingDataModel::StorageType::kQuotaStorage}, 345}});
  expected_entries.push_back(
      {kAnotherSiteOriginHost,
       kAnotherSiteOrigin,
       {{BrowsingDataModel::StorageType::kTrustTokens}, 456, 6}});
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model(),
                                                             expected_entries);
}
TEST_F(BrowsingDataModelTest, ConcurrentDeletions) {
  // Check that the model is able to support multiple deletion operations in
  // flight at the same time, even if the backends finish out-of-order.
  std::vector<::network::mojom::StoredTrustTokensForIssuerPtr> tokens;
  tokens.emplace_back(std::in_place, kSubdomainOrigin, 10);
  tokens.emplace_back(std::in_place, kAnotherSiteOrigin, 20);
  EXPECT_CALL(*mock_network_context(), GetStoredTrustTokenCounts(testing::_))
      .WillOnce(
          [&](network::TestNetworkContext::GetStoredTrustTokenCountsCallback
                  callback) { std::move(callback).Run(std::move(tokens)); });
  if (base::FeatureList::IsEnabled(
          network::features::kCompressionDictionaryTransportBackend)) {
    EXPECT_CALL(*mock_network_context(),
                GetSharedDictionaryUsageInfo(testing::_))
        .WillOnce([&](network::TestNetworkContext::
                          GetSharedDictionaryUsageInfoCallback callback) {
          std::move(callback).Run({});
        });
  }
  base::RunLoop run_loop;
  BuildModel(run_loop.QuitWhenIdleClosure());
  run_loop.Run();
  // The size of trust token storage is aliased to a small amount of data, 100B.
  auto expected_entries = std::vector<BrowsingDataEntry>{
      {kSubdomainOriginHost,
       kSubdomainOrigin,
       {{BrowsingDataModel::StorageType::kTrustTokens}, 100, 0}},
      {kAnotherSiteOriginHost,
       kAnotherSiteOrigin,
       {{BrowsingDataModel::StorageType::kTrustTokens}, 100, 0}},
      {kTestOriginHost,
       kTestOrigin,
       {{static_cast<BrowsingDataModel::StorageType>(
            browsing_data::TestBrowsingDataModelDelegate::StorageType::
                kTestDelegateType)},
        0,
        0}}};
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model(),
                                                             expected_entries);
  // Save the deletion callbacks provided to the mock network context, so we
  // can later fulfil them out-of-order. The mock lives on the other side of a
  // mojo interface, so the callbacks can only be populated async.
  base::RunLoop delete_run_loop;
  base::RepeatingClosure delete_barrier = base::BarrierClosure(
      2, base::BindLambdaForTesting([&]() { delete_run_loop.QuitWhenIdle(); }));
  network::TestNetworkContext::DeleteStoredTrustTokensCallback
      delete_tokens_complete_1;
  network::TestNetworkContext::DeleteStoredTrustTokensCallback
      delete_tokens_complete_2;
  {
    testing::InSequence sequence;
    EXPECT_CALL(*mock_network_context(),
                DeleteStoredTrustTokens(kSubdomainOrigin, testing::_))
        .WillOnce(
            [&](const url::Origin& origin,
                network::TestNetworkContext::DeleteStoredTrustTokensCallback
                    callback) {
              delete_tokens_complete_1 = std::move(callback);
              delete_barrier.Run();
            });
    EXPECT_CALL(*mock_network_context(),
                DeleteStoredTrustTokens(kAnotherSiteOrigin, testing::_))
        .WillOnce(
            [&](const url::Origin& origin,
                network::TestNetworkContext::DeleteStoredTrustTokensCallback
                    callback) {
              delete_tokens_complete_2 = std::move(callback);
              delete_barrier.Run();
            });
  }
  // As running the saved callbacks is also async, we need more run loops to
  // confirm that the model receives the deletion completed callback.
  base::RunLoop delete_callback_1_runloop;
  base::RunLoop delete_callback_2_runloop;
  model()->RemoveBrowsingData(kSubdomainOriginHost,
                              delete_callback_1_runloop.QuitWhenIdleClosure());
  // Removal from the model should be synchronous.
  expected_entries.erase(expected_entries.begin());
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model(),
                                                             expected_entries);
  model()->RemoveBrowsingData(kAnotherSiteOriginHost,
                              delete_callback_2_runloop.QuitWhenIdleClosure());
  expected_entries.erase(expected_entries.begin());
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model(),
                                                             expected_entries);
  delete_run_loop.Run();
  // We're now holding two unfulfilled backend deletion callbacks. Delete the
  // model (for extra test coverage) and then fire them in the opposite order
  // they were called. The callbacks provided with RemoveBrowsingData should
  // still be fired in matching order.
  DeleteModel();
  std::move(delete_tokens_complete_2)
      .Run(
          network::mojom::DeleteStoredTrustTokensStatus::kSuccessTokensDeleted);
  delete_callback_2_runloop.Run();
  EXPECT_FALSE(delete_callback_1_runloop.AnyQuitCalled());
  EXPECT_TRUE(delete_callback_2_runloop.AnyQuitCalled());
  std::move(delete_tokens_complete_1)
      .Run(
          network::mojom::DeleteStoredTrustTokensStatus::kSuccessTokensDeleted);
  delete_callback_1_runloop.Run();
  // The test not timing out is sufficient coverage, but this is easier to grok.
  EXPECT_TRUE(delete_callback_1_runloop.AnyQuitCalled());
  EXPECT_TRUE(delete_callback_2_runloop.AnyQuitCalled());
}
TEST_F(BrowsingDataModelTest, DelegateDataDeleted) {
  // Needed to when building model from disk, returning an empty list as it's
  // not needed for this test.
  EXPECT_CALL(*mock_network_context(), GetStoredTrustTokenCounts(testing::_))
      .WillOnce(
          [&](network::TestNetworkContext::GetStoredTrustTokenCountsCallback
                  callback) { std::move(callback).Run({}); });
  if (base::FeatureList::IsEnabled(
          network::features::kCompressionDictionaryTransportBackend)) {
    EXPECT_CALL(*mock_network_context(),
                GetSharedDictionaryUsageInfo(testing::_))
        .WillOnce([&](network::TestNetworkContext::
                          GetSharedDictionaryUsageInfoCallback callback) {
          std::move(callback).Run({});
        });
  }
  base::RunLoop run_loop;
  BuildModel(run_loop.QuitWhenIdleClosure());
  run_loop.Run();
  auto expected_entries = std::vector<BrowsingDataEntry>{
      {kTestOriginHost,
       kTestOrigin,
       {{static_cast<BrowsingDataModel::StorageType>(
            browsing_data::TestBrowsingDataModelDelegate::StorageType::
                kTestDelegateType)},
        0,
        0}}};
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model(),
                                                             expected_entries);
  expected_entries.erase(expected_entries.begin());
  EXPECT_TRUE(expected_entries.empty());
  model()->RemoveBrowsingData(kTestOriginHost, base::DoNothing());
  // Model should be empty after deleting delegated data.
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model(),
                                                             expected_entries);
}
// A BrowsingDataModel::Delegate that marks all Origin-keyed data belonging
// to a given host as being owned by its origin rather than its host.
class OriginOwnershipDelegate final : public BrowsingDataModel::Delegate {
 public:
  explicit OriginOwnershipDelegate(const std::string& origin_owned_host)
      : origin_owned_host_(origin_owned_host) {}
  // BrowsingDataModel::Delegate:
  void GetAllDataKeys(
      base::OnceCallback<void(std::vector<DelegateEntry>)> callback) override {
    std::move(callback).Run({});
  }
  void RemoveDataKey(const BrowsingDataModel::DataKey& data_key,
                     BrowsingDataModel::StorageTypeSet storage_types,
                     base::OnceClosure callback) override {
    std::move(callback).Run();
  }
  std::optional<BrowsingDataModel::DataOwner> GetDataOwner(
      const BrowsingDataModel::DataKey& data_key,
      BrowsingDataModel::StorageType storage_type) const override {
    const url::Origin* origin = std::get_if<url::Origin>(&data_key);
    if (origin && origin->host() == origin_owned_host_) {
      return *origin;
    }
    return std::nullopt;
  }
  std::optional<bool> IsStorageTypeCookieLike(
      BrowsingDataModel::StorageType storage_type) const override {
    return false;
  }
  std::optional<bool> IsBlockedByThirdPartyCookieBlocking(
      const BrowsingDataModel::DataKey& data_key,
      BrowsingDataModel::StorageType storage_type) const override {
    return IsStorageTypeCookieLike(storage_type);
  }
  bool IsCookieDeletionDisabled(const GURL& url) override { return false; }
  base::WeakPtr<Delegate> AsWeakPtr() override {
    return weak_ptr_factory_.GetWeakPtr();
  }
 private:
  std::string origin_owned_host_;
  base::WeakPtrFactory<OriginOwnershipDelegate> weak_ptr_factory_{this};
};
TEST_F(BrowsingDataModelTest, DelegateDataCanBeOriginOwned) {
  std::string origin_owned_host = "origin.owned.com";
  std::unique_ptr<BrowsingDataModel> model = BrowsingDataModel::BuildEmpty(
      storage_partition(),
      std::make_unique<OriginOwnershipDelegate>(origin_owned_host));
  auto httpOriginOwned = url::Origin::Create(GURL("http://origin.owned.com"));
  model->AddBrowsingData(httpOriginOwned,
                         BrowsingDataModel::StorageType::kTrustTokens, 100);
  auto httpsOriginOwned = url::Origin::Create(GURL("https://origin.owned.com"));
  model->AddBrowsingData(httpsOriginOwned,
                         BrowsingDataModel::StorageType::kTrustTokens, 100);
  auto httpHostOwned = url::Origin::Create(GURL("http://host.owned.com"));
  model->AddBrowsingData(httpHostOwned,
                         BrowsingDataModel::StorageType::kTrustTokens, 100);
  auto httpsHostOwned = url::Origin::Create(GURL("https://host.owned.com"));
  model->AddBrowsingData(httpsHostOwned,
                         BrowsingDataModel::StorageType::kTrustTokens, 100);
  auto expected_entries = std::vector<BrowsingDataEntry>{
      {httpOriginOwned,
       httpOriginOwned,
       {{BrowsingDataModel::StorageType::kTrustTokens}, 100, 0}},
      {httpsOriginOwned,
       httpsOriginOwned,
       {{BrowsingDataModel::StorageType::kTrustTokens}, 100, 0}},
      {"host.owned.com",
       httpHostOwned,
       {{BrowsingDataModel::StorageType::kTrustTokens}, 100, 0}},
      {"host.owned.com",
       httpsHostOwned,
       {{BrowsingDataModel::StorageType::kTrustTokens}, 100, 0}},
  };
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model.get(),
                                                             expected_entries);
}
// Tests that the BrowsingDataModel::Iterator can handle when the outer map
// contains an empty inner map.
//
// This is done by inserting an outer map element with an empty value
// for the inner map and then attempting to iterate over the entire model.
TEST_F(BrowsingDataModelTest, IteratorCanHandleEmptyDataKeyEntriesMaps) {
  // The BrowsingDataModel is currently empty.
  // Insert an outer map element with an empty inner map as its value. We can do
  // this by using operator[] which will default construct a key/value pair if
  // it can't find the key.
  browsing_data_entries()[kSiteOrigin];
  // Now iterate over the model. The distance should be 1 because we have our
  // empty outer element.
  EXPECT_EQ(1, std::distance(model()->begin(), model()->end()));
}
TEST_F(BrowsingDataModelTest, RemoveBasedOnPartitioning) {
  // TODO(crbug.com/40272946): Use helpers so this test can be broken up, likely
  // done alongside moving partition key detection to a visitor pattern.
  std::unique_ptr<BrowsingDataModel> model = BrowsingDataModel::BuildEmpty(
      storage_partition(),
      std::make_unique<browsing_data::TestBrowsingDataModelDelegate>());
  // Setup 4 storage keys, partitioned and unpartitioned storage for 2 sites.
  auto first_party_storage_key =
      blink::StorageKey::CreateFirstParty(kSiteOrigin);
  auto partitioned_storage_key =
      blink::StorageKey::Create(kSiteOrigin, net::SchemefulSite(kTestOrigin),
                                blink::mojom::AncestorChainBit::kCrossSite,
                                /*third_party_partitioning_allowed=*/true);
  auto another_first_party_storage_key =
      blink::StorageKey::CreateFirstParty(kAnotherSiteOrigin);
  auto another_partitioned_storage_key = blink::StorageKey::Create(
      kAnotherSiteOrigin, net::SchemefulSite(kAnotherTestOrigin),
      blink::mojom::AncestorChainBit::kCrossSite,
      /*third_party_partitioning_allowed=*/true);
  // Add all the keys to the model and ensure they are present as 4 different
  // browsing data entries.
  model->AddBrowsingData(first_party_storage_key,
                         BrowsingDataModel::StorageType::kLocalStorage, 0);
  model->AddBrowsingData(partitioned_storage_key,
                         BrowsingDataModel::StorageType::kLocalStorage, 0);
  model->AddBrowsingData(another_first_party_storage_key,
                         BrowsingDataModel::StorageType::kLocalStorage, 0);
  model->AddBrowsingData(another_partitioned_storage_key,
                         BrowsingDataModel::StorageType::kLocalStorage, 0);
  auto expected_entries = std::vector<BrowsingDataEntry>{
      {kSiteOriginHost,
       first_party_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
      {kSiteOriginHost,
       partitioned_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
      {kAnotherSiteOriginHost,
       another_first_party_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
      {kAnotherSiteOriginHost,
       another_partitioned_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
  };
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model.get(),
                                                             expected_entries);
  // Remove partitioned storage for one host, confirm that unpartitioned
  // storage for that host, and all storage for other hosts, are untouched.
  {
    base::RunLoop run_loop;
    model->RemovePartitionedBrowsingData(kSiteOriginHost,
                                         net::SchemefulSite(kTestOrigin),
                                         run_loop.QuitWhenIdleClosure());
    run_loop.Run();
  }
  expected_entries = std::vector<BrowsingDataEntry>{
      {kSiteOriginHost,
       first_party_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
      {kAnotherSiteOriginHost,
       another_first_party_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
      {kAnotherSiteOriginHost,
       another_partitioned_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
  };
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model.get(),
                                                             expected_entries);
  // Remove unpartitioned storage for the other host, ensure that partitioned
  // storage for that host, and storage for first host, is unaffected.
  {
    base::RunLoop run_loop;
    model->RemoveUnpartitionedBrowsingData(kAnotherSiteOriginHost,
                                           run_loop.QuitWhenIdleClosure());
    run_loop.Run();
  }
  expected_entries = std::vector<BrowsingDataEntry>{
      {kSiteOriginHost,
       first_party_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
      {kAnotherSiteOriginHost,
       another_partitioned_storage_key,
       {{BrowsingDataModel::StorageType::kLocalStorage}, 0, 0}},
  };
  browsing_data_model_test_util::ValidateBrowsingDataEntries(model.get(),
                                                             expected_entries);
}
TEST_F(BrowsingDataModelTest, ThirdPartyCookieTypes) {
  // Create data keys for all storage types.
  auto unpartitioned_storage_key =
      blink::StorageKey::CreateFirstParty(kSiteOrigin);
  auto partitioned_storage_key =
      blink::StorageKey::Create(kSiteOrigin, net::SchemefulSite(kTestOrigin),
                                blink::mojom::AncestorChainBit::kCrossSite,
                                /*third_party_partitioning_allowed=*/true);
  auto unpartitioned_session_storage_usage =
      content::SessionStorageUsageInfo{unpartitioned_storage_key, "example"};
  auto partitioned_session_storage_usage =
      content::SessionStorageUsageInfo{partitioned_storage_key, "example"};
  auto unpartitioned_shared_worker_info = browsing_data::SharedWorkerInfo(
      kSiteOrigin.GetURL(), "example", unpartitioned_storage_key,
      blink::mojom::SharedWorkerSameSiteCookies::kAll);
  auto partitioned_shared_worker_info = browsing_data::SharedWorkerInfo(
      kSiteOrigin.GetURL(), "example", partitioned_storage_key,
      blink::mojom::SharedWorkerSameSiteCookies::kNone);
  auto unpartitioned_cookie = MakeCanonicalCookie("name", kSiteOriginHost);
  auto partitioned_cookie = MakeCanonicalCookie(
      "__Host-partitioned", kSiteOriginHost,
      net::CookiePartitionKey::FromURLForTesting(GURL(kTestOriginHost)));
  auto partitioned_shared_dictionary_key = net::SharedDictionaryIsolationKey{
      kSiteOrigin, net::SchemefulSite(kTestOrigin)};
  content::InterestGroupManager::InterestGroupDataKey interest_group_key{
      kSiteOrigin, kSiteOrigin};
  content::AttributionDataModel::DataKey attribution_reporting_key{kSiteOrigin};
  content::PrivateAggregationDataModel::DataKey private_aggregation_key{
      kSiteOrigin};
  net::device_bound_sessions::SessionKey device_bound_session_key(
      net::SchemefulSite(kSiteOrigin.GetURL()),
      net::device_bound_sessions::SessionKey::Id("session_id"));
  std::map<BrowsingDataModel::StorageType, BrowsingDataModel::DataKey>
      third_party_cookie_types = {
          {BrowsingDataModel::StorageType::kSharedStorage,
           unpartitioned_storage_key},
          {BrowsingDataModel::StorageType::kLocalStorage,
           unpartitioned_storage_key},
          {BrowsingDataModel::StorageType::kQuotaStorage,
           unpartitioned_storage_key},
          {BrowsingDataModel::StorageType::kSessionStorage,
           unpartitioned_session_storage_usage},
          {BrowsingDataModel::StorageType::kSharedWorker,
           unpartitioned_shared_worker_info},
          {BrowsingDataModel::StorageType::kCookie, *unpartitioned_cookie},
          {BrowsingDataModel::StorageType::kDeviceBoundSession,
           device_bound_session_key}};
  std::map<BrowsingDataModel::StorageType, BrowsingDataModel::DataKey>
      non_third_party_cookie_types = {
          {BrowsingDataModel::StorageType::kSharedStorage,
           partitioned_storage_key},
          {BrowsingDataModel::StorageType::kLocalStorage,
           partitioned_storage_key},
          {BrowsingDataModel::StorageType::kQuotaStorage,
           partitioned_storage_key},
          {BrowsingDataModel::StorageType::kCdmStorage,
           partitioned_storage_key},
          {BrowsingDataModel::StorageType::kSessionStorage,
           partitioned_session_storage_usage},
          {BrowsingDataModel::StorageType::kSharedWorker,
           partitioned_shared_worker_info},
          {BrowsingDataModel::StorageType::kCookie, *partitioned_cookie},
          {BrowsingDataModel::StorageType::kTrustTokens, kSiteOrigin},
          {BrowsingDataModel::StorageType::kInterestGroup, interest_group_key},
          {BrowsingDataModel::StorageType::kAttributionReporting,
           attribution_reporting_key},
          {BrowsingDataModel::StorageType::kPrivateAggregation,
           private_aggregation_key},
          {BrowsingDataModel::StorageType::kSharedDictionary,
           partitioned_shared_dictionary_key}};
  std::unique_ptr<BrowsingDataModel> model = BrowsingDataModel::BuildEmpty(
      storage_partition(),
      std::make_unique<browsing_data::TestBrowsingDataModelDelegate>());
  for (int i = static_cast<int>(BrowsingDataModel::StorageType::kFirstType);
       i <= static_cast<int>(BrowsingDataModel::StorageType::kLastType); i++) {
    auto type = static_cast<BrowsingDataModel::StorageType>(i);
    EXPECT_TRUE(third_party_cookie_types.count(type) ||
                non_third_party_cookie_types.count(type))
        << "All storage types should be tested";
  }
  for (const auto& [type, key] : third_party_cookie_types) {
    EXPECT_TRUE(model->IsBlockedByThirdPartyCookieBlocking(key, type))
        << "Not blocking third_party_cookie_types of type: " << (int)type;
  }
  for (const auto& [type, key] : non_third_party_cookie_types) {
    EXPECT_FALSE(model->IsBlockedByThirdPartyCookieBlocking(key, type))
        << "Blocking non_third_party_cookie_types of type: " << (int)type;
  }
  // Ensure the delegate is also consulted.
  EXPECT_TRUE(model->IsBlockedByThirdPartyCookieBlocking(
      kTestOrigin, static_cast<BrowsingDataModel::StorageType>(
                       browsing_data::TestBrowsingDataModelDelegate::
                           StorageType::kTestDelegateType)));
  EXPECT_FALSE(model->IsBlockedByThirdPartyCookieBlocking(
      kTestOrigin, static_cast<BrowsingDataModel::StorageType>(
                       browsing_data::TestBrowsingDataModelDelegate::
                           StorageType::kTestDelegateTypePartitioned)));
}
TEST_F(BrowsingDataModelTest, HasThirdPartyPartitioningSite_True) {
  // Check the logic for determining whether data is partitioned.
  std::unique_ptr<BrowsingDataModel> model = BrowsingDataModel::BuildEmpty(
      storage_partition(),
      std::make_unique<browsing_data::TestBrowsingDataModelDelegate>());
  // Create a set of storage keys which all represent partitioned versions of
  // their data.
  auto partitioned_storage_key =
      blink::StorageKey::Create(kSiteOrigin, net::SchemefulSite(kTestOrigin),
                                blink::mojom::AncestorChainBit::kCrossSite,
                                /*third_party_partitioning_allowed=*/true);
  auto partitioned_session_storage_usage =
      content::SessionStorageUsageInfo{partitioned_storage_key, "example"};
  auto partitioned_shared_dictionary_key = net::SharedDictionaryIsolationKey{
      kSiteOrigin, net::SchemefulSite(kTestOrigin)};
  auto partitioned_shared_worker_info = browsing_data::SharedWorkerInfo(
      kSiteOrigin.GetURL(), "example", partitioned_storage_key,
      blink::mojom::SharedWorkerSameSiteCookies::kNone);
  model->AddBrowsingData(partitioned_storage_key,
                         BrowsingDataModel::StorageType::kQuotaStorage, 0, 0);
  model->AddBrowsingData(partitioned_session_storage_usage,
                         BrowsingDataModel::StorageType::kSessionStorage, 0, 0);
  model->AddBrowsingData(partitioned_shared_dictionary_key,
                         BrowsingDataModel::StorageType::kSharedDictionary, 0,
                         0);
  model->AddBrowsingData(partitioned_shared_worker_info,
                         BrowsingDataModel::StorageType::kSharedWorker, 0, 0);
  // Check that every model entry is partitioned, and the site matches.
  for (const auto& entry : *model) {
    EXPECT_EQ(partitioned_storage_key.top_level_site(),
              *entry.GetThirdPartyPartitioningSite());
  }
}
TEST_F(BrowsingDataModelTest, HasThirdPartyPartitioningSite_False) {
  // Check the logic for determining whether data is partitioned.
  std::unique_ptr<BrowsingDataModel> model = BrowsingDataModel::BuildEmpty(
      storage_partition(),
      std::make_unique<browsing_data::TestBrowsingDataModelDelegate>());
  // Create a set of storage keys which all represent un-partitioned versions of
  // their data.
  auto unpartitioned_storage_key =
      blink::StorageKey::CreateFirstParty(kSiteOrigin);
  auto unpartitioned_session_storage_usage =
      content::SessionStorageUsageInfo{unpartitioned_storage_key, "example"};
  auto unpartitioned_shared_dictionary_key = net::SharedDictionaryIsolationKey{
      kSubdomainOrigin, net::SchemefulSite(kSiteOrigin)};
  auto unpartitioned_shared_worker_info = browsing_data::SharedWorkerInfo(
      kSiteOrigin.GetURL(), "example", unpartitioned_storage_key,
      blink::mojom::SharedWorkerSameSiteCookies::kAll);
  auto non_partition_key = kAnotherTestOrigin;
  model->AddBrowsingData(unpartitioned_storage_key,
                         BrowsingDataModel::StorageType::kQuotaStorage, 0, 0);
  model->AddBrowsingData(unpartitioned_session_storage_usage,
                         BrowsingDataModel::StorageType::kSessionStorage, 0, 0);
  model->AddBrowsingData(unpartitioned_shared_dictionary_key,
                         BrowsingDataModel::StorageType::kSharedDictionary, 0,
                         0);
  model->AddBrowsingData(unpartitioned_shared_worker_info,
                         BrowsingDataModel::StorageType::kSharedWorker, 0, 0);
  model->AddBrowsingData(non_partition_key,
                         BrowsingDataModel::StorageType::kTrustTokens, 0, 0);
  // Check that every model entry is not partitioned, and so has no
  // partitioning site.
  for (const auto& entry : *model) {
    EXPECT_FALSE(entry.GetThirdPartyPartitioningSite().has_value());
  }
}
class BrowsingDataModelSharedDictionaryTest : public BrowsingDataModelTest {
 public:
  BrowsingDataModelSharedDictionaryTest() {
    scoped_feature_list_.InitWithFeatures(
        /*enabled_features=*/{network::features::
                                  kCompressionDictionaryTransportBackend},
        /*disabled_features=*/{});
  }
  ~BrowsingDataModelSharedDictionaryTest() override = default;
 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(BrowsingDataModelSharedDictionaryTest, GetUsageInfo) {
  net::SharedDictionaryIsolationKey isolation_key(
      kTestOrigin, net::SchemefulSite(kTestOrigin));
  EXPECT_CALL(*mock_network_context(), GetStoredTrustTokenCounts(testing::_))
      .WillOnce(
          [&](network::TestNetworkContext::GetStoredTrustTokenCountsCallback
                  callback) { std::move(callback).Run({}); });
  EXPECT_CALL(*mock_network_context(), GetSharedDictionaryUsageInfo(testing::_))
      .WillOnce(
          [&](network::TestNetworkContext::GetSharedDictionaryUsageInfoCallback
                  callback) {
            std::move(callback).Run({net::SharedDictionaryUsageInfo{
                .isolation_key = isolation_key, .total_size_bytes = 1234}});
          });
  base::RunLoop run_loop;
  BuildModel(run_loop.QuitWhenIdleClosure());
  run_loop.Run();
  ValidateBrowsingDataEntries(
      model(),
      {{kTestOriginHost,
        isolation_key,
        {{BrowsingDataModel::StorageType::kSharedDictionary}, 1234, 0}},
       {kTestOriginHost,
        kTestOrigin,
        {{static_cast<BrowsingDataModel::StorageType>(
             browsing_data::TestBrowsingDataModelDelegate::StorageType::
                 kTestDelegateType)},
         0,
         0}}});
}
TEST_F(BrowsingDataModelSharedDictionaryTest, Delete) {
  net::SharedDictionaryIsolationKey isolation_key(
      kTestOrigin, net::SchemefulSite(kTestOrigin));
  model()->AddBrowsingData(
      isolation_key, BrowsingDataModel::StorageType::kSharedDictionary, 1234);
  EXPECT_CALL(*mock_network_context(),
              ClearSharedDictionaryCacheForIsolationKey(testing::_, testing::_))
      .WillOnce(
          [&](const net::SharedDictionaryIsolationKey& key,
              MockNetworkContext::
                  ClearSharedDictionaryCacheForIsolationKeyCallback callback) {
            EXPECT_EQ(isolation_key, key);
            std::move(callback).Run();
          });
  base::RunLoop runloop;
  model()->RemoveBrowsingData(kTestOriginHost, runloop.QuitClosure());
  runloop.Run();
}
 |